-1

我尝试将信息表单数据库(mysql)检索为列表视图,这很好,但是如果我单击列表上的项目以显示信息,它会在 logcat 中显示此问题

09-20 21:40:12.125: E/AndroidRuntime(5003): FATAL EXCEPTION: main
09-20 21:40:12.125: E/AndroidRuntime(5003): android.os.NetworkOnMainThreadException
09-20 21:40:12.125: E/AndroidRuntime(5003):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:74)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at libcore.io.IoBridge.connect(IoBridge.java:112)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at java.net.Socket.connect(Socket.java:842)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at com.ksu.sms.JSONParser.makeHttpRequest(JSONParser.java:62)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at com.ksu.sms.ViewCourseStudent$GetCourseDetails$1.run(ViewCourseStudent.java:91)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at android.os.Handler.handleCallback(Handler.java:605)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at android.os.Looper.loop(Looper.java:137)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at android.app.ActivityThread.main(ActivityThread.java:4340)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at java.lang.reflect.Method.invokeNative(Native Method)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at java.lang.reflect.Method.invoke(Method.java:511)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-20 21:40:12.125: E/AndroidRuntime(5003):     at dalvik.system.NativeStart.main(Native Method)

这是我检索整个信息并显示为列表的代码

package com.ksu.sms;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;



public class ViewALLCourseStudent extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser(); //class

    ArrayList<HashMap<String, String>> coursesList;

    //url to get all products list
    private static String url_all_course = "http://10.0.2.2/SmsPhp/view_all_course.php";
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_course = "course";
    private static final String TAG_CourseID = "CourseID";
    private static final String TAG_Name = "Name";

    // course JSONArray
    JSONArray courses = null;

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


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

        // Loading courses in Background Thread
        new LoadAllCourses().execute();

        // Get list view
        ListView lv = getListView();
     // on seleting single course
        // launching Edit course Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

             public void onItemClick(AdapterView<?> parent, View view,
                     int position, long id) //one of the list
             {
                 // getting values from selected ListItem
                 String CourseID = ((TextView) view.findViewById(R.id.CourseID)).getText()
                         .toString();
                 // Starting new intent
                 Intent ViewCourseStudent = new Intent(getApplicationContext(),
                         ViewCourseStudent.class);
                 // sending Course ID to next activity
                 ViewCourseStudent.putExtra(TAG_CourseID, CourseID);

                 // starting new activity and expecting some response back
                 startActivityForResult(ViewCourseStudent, 100);
             }
         });

     }
 // Response from view course Activity

    @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user view course
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

}
    /**
     * Background Async Task to Load all course by making HTTP Request
     * */
    class LoadAllCourses extends AsyncTask<String, String, String>
    {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ViewALLCourseStudent.this);
            pDialog.setMessage("Loading Courses. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
        /**
         * getting All products from u r l
         * */
        @Override
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_course, "GET", params);

            // Check your log cat for JSON response
            Log.d("All courses: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // course found
                    // Getting Array of course
                    courses = json.getJSONArray(TAG_course);

                    // looping through All courses
                    for (int i = 0; i < courses.length(); i++)//course JSONArray
                    {
                        JSONObject c = courses.getJSONObject(i); // read first

                        // Storing each json item in variable
                        String CourseID = c.getString(TAG_CourseID);
                        String Name = c.getString(TAG_Name);

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

                        // adding each child node to HashMap key => value
                        map.put(TAG_CourseID, CourseID);
                        map.put(TAG_Name, Name);

                        // adding HashList to ArrayList
                        coursesList.add(map);
                    }
                } else {
                    Toast.makeText(getBaseContext(),"there is no course" ,Toast.LENGTH_LONG).show();
                }

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

            return null;
        }   

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) { 
              // dismiss the dialog after getting all products 
              pDialog.dismiss(); 

              /** 
              * Updating parsed JSON data into ListView 
              **/ 
              ListAdapter adapter = new SimpleAdapter( 
                                ViewALLCourseStudent.this, coursesList, 
                                R.layout.list_item, new String[] { TAG_CourseID, 
                                        TAG_Name}, 
                                new int[] { R.id.CourseID, R.id.Name }); 
               // updating listview 
               setListAdapter(adapter); 
        } 


    }
}

最后,如果数据库为空,它也会在 logcat 中显示此问题

09-20 22:07:20.665: E/AndroidRuntime(5260): FATAL EXCEPTION: AsyncTask #1
09-20 22:07:20.665: E/AndroidRuntime(5260): java.lang.RuntimeException: An error occured while executing doInBackground()
4

2 回答 2

0

这个问题有两个解决方案。

1)不要在主 UI 线程中编写网络调用,为此使用异步任务。

2) 在 setContentView(R.layout.activity_main); 之后将以下代码写入 MainActivity 文件;

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}
于 2012-09-22T07:59:20.057 回答
0

为什么要runOnUiThread()在 AsyncTask 的后台线程中使用?使用它的全部目的是使操作在后台线程上运行。

无论哪种方式,您都可以做两件事来解决这个问题。

  1. 使用低于蜂窝的 API 构建您的应用程序:

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="9" />

  2. 删除runOnUiThread()AsyncTask 的部分,并让代码在后台线程中运行。

于 2012-09-22T07:46:51.107 回答