1

Android開発の初心者で、次のコードでエラーが発生します。私はhttpリクエストの非同期メソッドを呼び出しています.doInBackground()の実行中にjava.lang.RuntimeExceptionエラーが発生しました

private class PostAlert extends AsyncTask<String, Integer, JSONArray>{

    private ProgressDialog progressDialog;

    @Override
    protected JSONArray doInBackground(String... params) {
        // TODO Auto-generated method stub
        JSONArray menuitemArr = null;
        String url=params[0];

        System.out.println("fsfsddddf"+params[0]);
        ControlDashboard obj = new ControlDashboard();
        try{
        JSONObject aobj = obj.getJSONFromUrl(url);

            JSONObject array = aobj.getJSONObject("alert_list");    
             menuitemArr = array.getJSONArray("array");

        }   
        catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       

        return menuitemArr;
    }

    @Override
    protected void onPostExecute(JSONArray menuitemArr) {
        // TODO Auto-generated method stub
        super.onPostExecute(menuitemArr);
        if (menuitemArr.length() == 0) {
            startActivity(new Intent("com.example.mysampleapp.ABOUT"));
            //Toast.makeText(Alert.this, "No Alerts", Toast.LENGTH_LONG).show();
        }else{
        name = new String[menuitemArr.length()];
        alert = new String[menuitemArr.length()];
        date = new String[menuitemArr.length()];
        for (int i = 0; i < menuitemArr.length(); i++) { 
            // printing the values to the logcat 
            try {
                name[i] =  menuitemArr.getJSONObject(i).getString("name").toString();
                alert[i] = menuitemArr.getJSONObject(i).getString("message").toString(); 
                date[i] = menuitemArr.getJSONObject(i).getString("date").toString();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 

        } 
        ListView list = (ListView) findViewById(R.id.listView3);
        ArrayList<HashMap<String, String>> mylistData = new ArrayList<HashMap<String, String>>();
        String[] columnTags = new String[] {"col1", "col2", "col3"};
        int[] columnIds = new int[] {R.id.alert1, R.id.alert2, R.id.alert3};
        for(int i=0; i<name.length; i++)
        {
         HashMap<String,String> map = new HashMap<String, String>();
             map.put("col1", name[i]);
             map.put("col2", alert[i]);
             map.put("col3", date[i]);
         mylistData.add(map);
        }
        SimpleAdapter arrayAdapter = new SimpleAdapter(Alert.this, mylistData, R.layout.alert_view,columnTags,columnIds);
        list.setAdapter(arrayAdapter);      
        }
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        progressDialog = new ProgressDialog(Alert.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("please wait...");
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(false);
        progressDialog.setMax(100);
        progressDialog.setProgress(0);
        progressDialog.show();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
        //progressDialog.dismiss();
    }



}

Android アプリケーションを実行するとエラーが発生します。

12-17 13:22:48.035: W/dalvikvm(1160): threadid=8: thread exiting with uncaught exception (group=0x4001d800)
12-17 13:22:48.045: E/AndroidRuntime(1160): FATAL EXCEPTION: AsyncTask #2
12-17 13:22:48.045: E/AndroidRuntime(1160): java.lang.RuntimeException: An error occured while executing doInBackground()
12-17 13:22:48.045: E/AndroidRuntime(1160):     at android.os.AsyncTask$3.done(AsyncTask.java:200)
12-17 13:22:48.045: E/AndroidRuntime(1160):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
12-17 13:22:48.045: E/AndroidRuntime(1160):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
12-17 13:22:48.045: E/AndroidRuntime(1160):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
12-17 13:22:48.045: E/AndroidRuntime(1160):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)

json リクエスト クラス:

public class ControlDashboard extends Activity {
    public static DefaultHttpClient httpClient;

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            jObj = null;
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }



}
4

2 に答える 2

3
 startActivity(new Intent("com.example.mysampleapp.ABOUT"));

また

   ListView list = (ListView) findViewById(R.id.listView3);

ここでは、バックグラウンドスレッドからUI要素にアクセスしようとしています。これはAsyncTaskからの手段doInBackgroundであり、不可能です。

ソリューション完了 onPostExecute後にUIを更新するために、すべてのUI関連コードを移動しますdoInBackground

実行が完了しonPostExecuteた後 からUIを更新する方法をここで確認できますdoInBackground

編集: またはこのPostAlert AsyncTaskクラスを使用してください:

private class PostAlert extends AsyncTask<String, Integer, JSONArray>{

        private ProgressDialog progressDialog;

        @Override
        protected JSONArray doInBackground(String... params) {
            // TODO Auto-generated method stub
           JSONArray menuitemArr=null;
            String url=params[0];
            System.out.println("fsfsddddf"+url);

        //  System.out.println("fsfsddddfobj"+obj);
            try{

            JSONObject aobj = obj.getJSONFromUrl(url);
            System.out.println("fsfsf"+aobj);

                JSONObject array = aobj.getJSONObject("alert_list");    
                menuitemArr = array.getJSONArray("array");

            catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }       
            return menuitemArr;
        }

        @Override
        protected void onPostExecute(JSONArray menuitemArr) {
            // TODO Auto-generated method stub

                if (menuitemArr.length() == 0) {
                    startActivity(new Intent("com.example.mysampleapp.ABOUT"));
                    //Toast.makeText(Alert.this, "No Alerts", Toast.LENGTH_LONG).show();
                }else{
                name = new String[menuitemArr.length()];
                System.out.println("name"+name);
                alert = new String[menuitemArr.length()];
                date = new String[menuitemArr.length()];
                for (int i = 0; i < menuitemArr.length(); i++) { 
                    // printing the values to the logcat 
                    name[i] =  menuitemArr.getJSONObject(i).getString("name").toString(); 
                    alert[i] = menuitemArr.getJSONObject(i).getString("message").toString(); 
                    date[i] = menuitemArr.getJSONObject(i).getString("date").toString();
                } 
                ListView list = (ListView) findViewById(R.id.listView3);
                ArrayList<HashMap<String, String>> mylistData = new ArrayList<HashMap<String, String>>();
                String[] columnTags = new String[] {"col1", "col2", "col3"};
                int[] columnIds = new int[] {R.id.alert1, R.id.alert2, R.id.alert3};
                for(int i=0; i<name.length; i++)
                {
                 HashMap<String,String> map = new HashMap<String, String>();
                     map.put("col1", name[i]);
                     map.put("col2", alert[i]);
                     map.put("col3", date[i]);
                 mylistData.add(map);
                }
                SimpleAdapter arrayAdapter = new SimpleAdapter(Alert.this, mylistData, R.layout.alert_view,columnTags,columnIds);
                list.setAdapter(arrayAdapter);      
                } 
            }

            super.onPostExecute(result);
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            progressDialog = new ProgressDialog(Alert.this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setMessage("please wait...");
            progressDialog.setCancelable(false);
            progressDialog.setIndeterminate(false);
            progressDialog.setMax(100);
            progressDialog.setProgress(0);
            progressDialog.show();
            System.out.println("fsgsgsg");
        }
        @Override
        protected void onProgressUpdate(Integer... values) {
            // TODO Auto-generated method stub
            progressDialog.setProgress(values[0]);  
        }



    }
}

http://developer.android.com/reference/android/os/AsyncTask.html

于 2012-12-17T08:02:44.170 に答える
1

ListAdapterをバックグラウンドで設定していますが、これはUIスレッドタスクであるため実行しないでください。コード全体をdoInBackground()onPostExecute()除くに変更しますgetJsonFromUrl(url)。結果パラメータとしてdoInBackground()取得できるjsonobjectを返すことができます。onPostExecute()それでも、そのランタイムエラーが発生する場合は、この行をonPostExecute()正しく入力してくださいlistview.setAdapter()

runOnUIThread(new Runnable(){
public void run()
{

}
});

私はそれが明確であり、それがあなたのために働くことを願っています。

于 2012-12-17T08:02:14.793 に答える