-1

我手上有很多问题。我的应用程序不断崩溃,这就是我的堆栈跟踪一直在说的

07-26 10:48:30.582: E/AndroidRuntime(2334): FATAL EXCEPTION: main
07-26 10:48:30.582: E/AndroidRuntime(2334): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.theproblemsolver/com.theproblemsolver.ListView}: android.os.NetworkOnMainThreadException
07-26 10:48:30.582: E/AndroidRuntime(2334):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at android.os.Looper.loop(Looper.java:137)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at android.app.ActivityThread.main(ActivityThread.java:5041)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at java.lang.reflect.Method.invokeNative(Native Method)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at java.lang.reflect.Method.invoke(Method.java:511)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at com.theproblemsolver.JSONParsser.getJSONFromURI(JSONParsser.java:39)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at com.theproblemsolver.ListView.onCreate(ListView.java:34)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at android.app.Activity.performCreate(Activity.java:5104)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
07-26 10:48:30.582: E/AndroidRuntime(2334):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
07-26 10:48:30.582: E/AndroidRuntime(2334):     ... 11 more

有人可以告诉我为什么会发生这个错误以及我能做些什么来解决它。这是我的其余代码

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) {
                new asynctask().execute();
                Intent i = new Intent(MainActivity.this, ListView.class);
                startActivity(i);
            }

            //protected void launchNewActivity(){
            //startActivity(new Intent(MainActivity.this, ListView.class));


            });
        } 
    }

          class asynctask extends AsyncTask<String, Void, JSONObject> {

                 private static final String TAG_RESULTS = "ResultsSet";
                 private static final String TAG_SUBJECT = "Subject";
                 private static final String TAG_NUMANSWERS = "NumAnswers";
                 private static final String TAG_QUESTION = "Question";
                 private static final String TAG_QUESTION_CONTENT = "Content";
                 private static final String TAG_QUESTION_CHOSENANSWER = "ChosenAnswer";
                 private static final String TAG_QUESTION_ANSWERS = "Answers";
                public JSONArray json;

             @Override
             protected JSONObject doInBackground(String... params) {

                 JSONParsser jParser = new JSONParsser();

                 String URI = "http://example.com/json";

                 JSONObject json = jParser.getJSONFromURI(URI);

                 return json ;

             }{ }
                @Override
                 protected void onPostExecute(JSONObject json) {

                     JSONArray ResultsSet = null ; {
                     try {
                         ResultsSet = json.getJSONArray(TAG_RESULTS);
                    } catch (JSONException e) {
                       e.printStackTrace();
                    }
                return;
                 }}

列表视图活动

public class ListView extends ListActivity {


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


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

        JSONParsser jParser = new JSONParsser();

        String URI = "http://answers.yahooapis.com/AnswerService/V1/questionSearch?appid=4vCW8F3V34GzdMlXOS.yc2WfF5DCnCgqhK0nwCJmEFDgRwEbIgnAoEgJ0zynqOAWtQ&query=sort&type=resolved&results&output=json";;

        JSONObject json = jParser.getJSONFromURI(URI);


         final String TAG_RESULTS = "ResultsSet";
         final String TAG_SUBJECT = "Subject";
         final String TAG_NUMANSWERS = "NumAnswers";
         final String TAG_QUESTION = "Question";
         final String TAG_QUESTION_CONTENT = "Content";
         final String TAG_QUESTION_CHOSENANSWER = "ChosenAnswer";
         final String TAG_QUESTION_ANSWERS = "Answers";

                JSONArray ResultsSet = null;

        try {
           ResultsSet = json.getJSONArray(TAG_RESULTS);

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

               String Subject = r.getString(TAG_SUBJECT);
               String NumAnswers = r.getString(TAG_NUMANSWERS);

               JSONObject Question = r.getJSONObject(TAG_QUESTION);
               String Content = Question.getString(TAG_QUESTION_CONTENT);
               String ChosenAnswer = Question.getString(TAG_QUESTION_CHOSENANSWER);
               String Answers = Question.getString(TAG_QUESTION_ANSWERS);

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

               map.put(TAG_SUBJECT, Subject);
               map.put(TAG_NUMANSWERS, NumAnswers);

               questionList.add(map);

           }
        } catch (JSONException e) {
           e.printStackTrace();
           }

        ListAdapter adapter = new SimpleAdapter(this, questionList,
                R.layout.row,
                new String[] { TAG_SUBJECT, TAG_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<?> parent, View view,
                    int position, long id) {
                String Subject = view.findViewById(R.id.Subject).getContext().toString();

                Intent i = new Intent(getApplicationContext(), SingleListItem.class);
                i.putExtra(TAG_SUBJECT, Subject);
                startActivity(i);

SingleListItem 活动

public class SingleListItem extends Activity {

    TextView subject;

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

    subject = (TextView) findViewById(R.id.Subject2);

    Intent i = getIntent();
    String Subject = i.getStringExtra("TAG_SUBJECT");
    subject.setText(Subject);

    }
}
4

4 回答 4

0

来自 developer.android.com

Potentially long running operations such as network or database operations, or computationally expensive calculations such as resizing bitmaps should be done in a worker thread (or in the case of databases operations, via an asynchronous request).

这是为了防止 Android Not Responding 错误而强制执行的。同样来自 android 开发者网站:

In any situation in which your app performs a potentially lengthy operation, you should not perform the work on the UI thread, but instead create a worker thread and do most of the work there. This keeps the UI thread (which drives the user interface event loop) running and prevents the system from concluding that your code has frozen.

http://developer.android.com/training/articles/perf-anr.html http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

其他人已经为它提供了代码修复。

于 2013-07-26T11:34:34.643 回答
0

看起来您在 UI 线程中使用网络连接:

String URI = "http://answers.yahooapis.com/AnswerService/V1/questionSearch?appid=4vCW8F3V34GzdMlXOS.yc2WfF5DCnCgqhK0nwCJmEFDgRwEbIgnAoEgJ0zynqOAWtQ&query=sort&type=resolved&results&output=json";;
JSONObject json = jParser.getJSONFromURI(URI);

使用异步任务。

于 2013-07-26T11:26:08.483 回答
0

您的 Method.java 文件在第 511 行有问题,请查看。

于 2013-07-26T11:27:40.673 回答
0

您也应该以与 Main 活动类相同的方式运行它

             @Override
             protected JSONObject doInBackground(String... params) {

                 JSONParsser jParser = new JSONParsser();

                 String URI = "http://answers.yahooapis.com/AnswerService/V1/questionSearch?appid=4vCW8F3V34GzdMlXOS.yc2WfF5DCnCgqhK0nwCJmEFDgRwEbIgnAoEgJ0zynqOAWtQ&query=sort&type=resolved&results&output=json";;

                JSONObject json = jParser.getJSONFromURI(URI);

                 return json ;

             }
于 2013-07-26T11:31:15.160 回答