-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

runOnUiThread()AsyncTask のバックグラウンド スレッドで使用するのはなぜですか? これを使用するポイントは、操作をバックグラウンド スレッドで実行することです。

いずれにせよ、これを修正するためにできることは 2 つあります。

  1. 以下を使用して、ハニカムよりも低い API 用にアプリをビルドします。

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

  2. runOnUiThread()AsyncTaskの一部を削除し、コードをバックグラウンド スレッドで実行します。

于 2012-09-22T07:46:51.107 に答える
0

この問題の解決策は 2 つあります。

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 に答える