编辑文本是强制关闭应用程序

时间:2013-08-05 19:41:45

标签: android json android-listview android-edittext

我设法通过编码我的编辑文本解决了我的JSONObject问题,但我的应用程序仍然强制崩溃。这次我的logcat说我在错误的帖子中调用了我的编辑文本,所以我只是希望有比我更好经验的人能给我一些建议并告诉我如何解决这个问题。

08-05 19:07:36.617: E/AndroidRuntime(772): FATAL EXCEPTION: AsyncTask #2
08-05 19:07:36.617: E/AndroidRuntime(772): java.lang.RuntimeException: An error occured while executing doInBackground()
08-05 19:07:36.617: E/AndroidRuntime(772):  at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-05 19:07:36.617: E/AndroidRuntime(772):  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
08-05 19:07:36.617: E/AndroidRuntime(772):  at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
08-05 19:07:36.617: E/AndroidRuntime(772):  at java.util.concurrent.FutureTask.run(FutureTask.java:239)
08-05 19:07:36.617: E/AndroidRuntime(772):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-05 19:07:36.617: E/AndroidRuntime(772):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
08-05 19:07:36.617: E/AndroidRuntime(772):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
08-05 19:07:36.617: E/AndroidRuntime(772):  at java.lang.Thread.run(Thread.java:856)
08-05 19:07:36.617: E/AndroidRuntime(772): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
08-05 19:07:36.617: E/AndroidRuntime(772):  at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4746)
08-05 19:07:36.617: E/AndroidRuntime(772):  at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:823)
08-05 19:07:36.617: E/AndroidRuntime(772):  at android.view.View.requestLayout(View.java:15473)
08-05 19:07:36.617: E/AndroidRuntime(772):  at android.view.ViewGroup.addView(ViewGroup.java:3208)
08-05 19:07:36.617: E/AndroidRuntime(772):  at android.view.ViewGroup.addView(ViewGroup.java:3186)
08-05 19:07:36.617: E/AndroidRuntime(772):  at com.android.internal.policy.impl.PhoneWindow.generateLayout(PhoneWindow.java:2813)
08-05 19:07:36.617: E/AndroidRuntime(772):  at com.android.internal.policy.impl.PhoneWindow.installDecor(PhoneWindow.java:2875)
08-05 19:07:36.617: E/AndroidRuntime(772):  at com.android.internal.policy.impl.PhoneWindow.getDecorView(PhoneWindow.java:1568)
08-05 19:07:36.617: E/AndroidRuntime(772):  at android.view.Window.findViewById(Window.java:900)
08-05 19:07:36.617: E/AndroidRuntime(772):  at android.app.Activity.findViewById(Activity.java:1839)
08-05 19:07:36.617: E/AndroidRuntime(772):  at com.theproblemsolver.ListView$LoadAllData.doInBackground(ListView.java:90)
08-05 19:07:36.617: E/AndroidRuntime(772):  at com.theproblemsolver.ListView$LoadAllData.doInBackground(ListView.java:1)
08-05 19:07:36.617: E/AndroidRuntime(772):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-05 19:07:36.617: E/AndroidRuntime(772):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
08-05 19:07:36.617: E/AndroidRuntime(772):  ... 4 more

MainActivity:

public class MainActivity extends Activity {

    EditText et;
    Button getanswer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button getanswer = (Button) findViewById(R.id.button1);
        getanswer.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            //} catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
            //}
            Intent i = new Intent(MainActivity.this, ListView.class);
            startActivity(i);
        }


        });
    } 
}

ListViewActivity:

public class ListView extends ListActivity {

    private ProgressDialog pDialog;

    JSONParsser jParser = new JSONParsser();
    ArrayList<HashMap<String, String>> questionList;





    //JSONObject json = jParser.getJSONFromURI(URI);

     final String TAG_RESULTS = "results";
     final String TAG_QUESTION_SUBJECT = "Subject";
     final String TAG_QUESTION_NUMANSWERS = "NumAnswers";
     final String TAG_QUESTION = "Question";
     final String TAG_QUESTION_CONTENT = "Content";
     final String TAG_QUESTION_CHOSENANSWER = "ChosenAnswer";
     final String TAG_ANSWERS = "Answers";
     final String TAG_ANSWER = "Answer";    
     final String TAG_ANSWERS_CONTENT = "Content";      

            JSONArray results;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        //setContentView(R.layout.listview);        

        //questionList = new ArrayList<HashMap<String, String>>();



    new LoadAllData().execute();
        }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == 100) {
            Intent intent = getIntent();
            startActivity(intent);
            finish();
        }
    }

    class LoadAllData extends AsyncTask<String, String, String> {


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ListView.this);
            pDialog.setMessage("Loading Data. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
            if (pDialog != null && pDialog.isShowing()) pDialog.dismiss();

        }

        protected String doInBackground(String... args) {

            EditText et = (EditText) findViewById(R.id.editText1);
            String searchTerm = et.getText().toString().trim();
            try {
                String query = URLEncoder.encode(searchTerm, "utf-8");
                String URL = "http://example.com/json";
                JSONObject jObj = jParser.readJSONFeed(URL);
                try {
                    results = jObj.getJSONArray(TAG_RESULTS);

                    for(int i = 0; i < results.length(); i++) {
                           JSONObject r = results.getJSONObject(i);

                           JSONObject Question = r.getJSONObject(TAG_QUESTION);
                           String Subject = Question.getString(TAG_QUESTION_SUBJECT);
                           String NumAnswers = Question.getString(TAG_QUESTION_NUMANSWERS);
                           String ChosenAnswers= Question.getString(TAG_QUESTION_CHOSENANSWER);
                           String Content = Question.getString(TAG_QUESTION_CONTENT);

                           JSONObject Answers = Question.getJSONObject(TAG_ANSWERS);
                           JSONObject Answer = Answers.getJSONObject(TAG_ANSWER);
                           String Content1 = Answers.getString(TAG_ANSWERS_CONTENT);

                             questionList = new ArrayList<HashMap<String, String>>();

                               HashMap<String, String> map = new HashMap<String, String>();

                               map.put(TAG_QUESTION_SUBJECT, Subject);
                               map.put(TAG_QUESTION_NUMANSWERS, NumAnswers);

                               questionList.add(map);

                           }



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

                return TAG_RESULTS ; 



        }
        @Override
        protected void onPostExecute(String file_URL) {

                ListAdapter adapter = new SimpleAdapter(getBaseContext(), questionList,
                        R.layout.listview,
                        new String[] { TAG_QUESTION_SUBJECT, TAG_QUESTION_NUMANSWERS }, new int[] {
                        R.id.Subject, R.id.NumAnswers });

                setListAdapter(adapter);

                android.widget.ListView lv = getListView();

                lv.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
                        // TODO Auto-generated method stub

                    }




                });

            }       
}}

JSONParsser类:

public class JSONParsser {

    InputStream is;
    JSONObject jObj;
    String json = "";
    public EditText et;

    public JSONParsser () {
    }

    public JSONObject readJSONFeed(String URL) {

        try{
        HttpClient client = new DefaultHttpClient();
        HttpPost request = new HttpPost(URL);
        //request.setURI(website);
        try {
            HttpResponse response = client.execute(request);
        HttpEntity httpEntity = response.getEntity();
        is = httpEntity.getContent();

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line;
            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 {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
           Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        Log.d("JSON String",json);

        return jObj;

        }finally{}

    }{
    }}

3 个答案:

答案 0 :(得分:0)

您无法访问asynctask中的任何布局项。你在doInBackground中为你的EditText调用findViewById。为了解决这个问题,您可以将EditText和searchTerm放在AsyncTask之外,并将searchTerm设置为最终的全局变量,然后您可以在AsyncTask中访问它。

答案 1 :(得分:0)

移动此行

EditText et = (EditText) findViewById(R.id.editText1);

从您doInBackground()的{​​{1}}到AsyncTask

onCreate()

无法在public class MainActivity extends Activity { EditText et; Button getanswer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EditText et = (EditText) findViewById(R.id.editText1); //Here Button getanswer = (Button) findViewById(R.id.button1); 运行UI的背景Thread上更新doInBackground(),因此您需要在EditText之外初始化AsyncTask

答案 2 :(得分:0)

永远不要从bacground-thread更新UI。

请参阅AsyncTask

  

执行异步任务时,任务将经历4个步骤:

     

onPreExecute(),在执行任务之前在UI线程上调用。   此步骤通常用于设置任务,例如通过显示   用户界面中的进度条。

     

doInBackground(Params ...),在后台线程上调用   在onPreExecute()完成执行后立即执行。使用此步骤   执行可能需要很长时间的后台计算。该   异步任务的参数传递给此步骤。该   计算结果必须由此步骤返回并且将是   回到最后一步。这一步也可以使用   publishProgress(Progress ...)发布一个或多个进度单元。   这些值发布在UI线程中   onProgressUpdate(Progress ...)步骤。

     

onProgressUpdate(Progress ...),在调用后在UI线程上调用   发布进度(进度......)。执行的时间是   未定义。此方法用于显示任何形式的进度   后台计算仍在执行时的用户界面。   例如,它可用于为进度条设置动画或显示登录   文本字段。

     

onPostExecute(Result),在后台后的UI线程上调用   计算结束。背景计算的结果是   作为参数传递给此步骤。