-1

I try to retrieve the information form database (mysql) as list view and that is work fine but if I click on item on the list to display the information it display this problem in 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)

and this is my code to retrive the whole information and display as list

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); 
        } 


    }
}

finally if the data base is empty also it display this problem in 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()
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • have you given Internet Permission in AndroidManifest.xml ? – Lucifer Sep 22 '12 at 07:45
  • @lucifer yes before application tage this problem android.os.NetworkOnMainThreadException it is gone if i change the android:targetSdkVersion="14" to android:targetSdkVersion="8" but i do no if there is i way i can fix it but the most importent is way the FATAL EXCEPTION: main if i click in one of item list – user1682578 Sep 22 '12 at 07:49

2 Answers2

0

Why would you use runOnUiThread() in the background thread of an AsyncTask? The whole point of using that is to make the operation run on the background thread.

Either way, there are two things you can do to fix this.

  1. Make your app build for an API lower than honeycomb using:

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

  2. Remove the runOnUiThread() part of the AsyncTask, and have the code run in the background thread.

Raghav Sood
  • 81,899
  • 22
  • 187
  • 195
  • make the code which is in the runOnUiThread() method run outside the runOnUiThread(). – Raghav Sood Sep 22 '12 at 07:55
  • @Override protected String doInBackground(String... arg0) { // updating UI from Background Thread runOnUiThread(new Runnable() { – Raghav Sood Sep 22 '12 at 08:00
  • You will have to move all the textview updating code to onPostExecute() as well. – Raghav Sood Sep 22 '12 at 08:01
  • I have no idea what you're talking about now. Is the problem still there? – Raghav Sood Sep 22 '12 at 08:15
  • The exception is in ViewCourseStudent, so you were right the first time. – Raghav Sood Sep 22 '12 at 08:28
  • You aren't providing any information as to what error. You could have two different errors, or 1 error that results in another error. I can't help you unless you provide more information. Also, this comments thread is getting rather long. – Raghav Sood Sep 22 '12 at 08:43
  • i am really sorry cause i am not good in engilsh first in class ViewALLCourseStudent that call class viewcoursestudent to show the information of course ok .. the problem is on class ViewALLCourseStudent because if the data base have no row it display error and second if i click in on item in list to show the the information of it the have been writen in class view course information it display also error do you understand me know – user1682578 Sep 22 '12 at 08:50
  • http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ her is the code that i do like it and the developer of it change the textview in doInBackground – user1682578 Sep 22 '12 at 08:52
  • @ Raghav Sood i really need you – user1682578 Sep 22 '12 at 09:20
0

There are two Solution of this Problem.

1) Don't write network call in Main UI Thread, Use Async Task for that.

2) Write below code into your MainActivity file after setContentView(R.layout.activity_main);

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}
Dipak Keshariya
  • 22,193
  • 18
  • 76
  • 128
  • @user1688325 this will solve "NetworkOnMainThreadException" problem. – Dipak Keshariya Sep 22 '12 at 08:17
  • so i do not need to change the sdk form 14 to 8 know right – user1682578 Sep 22 '12 at 08:19
  • @user1688325 yes, you are right. – Dipak Keshariya Sep 22 '12 at 08:25
  • there is error Description Resource Path Location Type Call requires API level 9 (current min is 8): android.os.StrictMode#setThreadPolicy Home.java /com.ksu.sms.SMS/src/com/ksu/sms line 22 Android Lint Problem – user1682578 Sep 22 '12 at 08:39
  • @SuppressLint("NewApi") i do that and the error is gone is it right or wrong and other problem is display which is 09-20 23:44:41.435: E/AndroidRuntime(5431): java.lang.NullPointerException – user1682578 Sep 22 '12 at 08:54
  • can you check why this happend – user1682578 Sep 22 '12 at 09:08
  • @user1688325 Please post full error logcat. – Dipak Keshariya Sep 22 '12 at 09:09
  • 09-20 23:44:41.435: E/AndroidRuntime(5431): java.lang.NullPointerException 09-21 00:02:58.235: E/AndroidRuntime(5512): FATAL EXCEPTION: AsyncTask #2 09-21 00:02:58.235: E/AndroidRuntime(5512): java.lang.RuntimeException: An error occured while executing doInBackground() 09-21 00:02:58.235: E/AndroidRuntime(5512): at android.os.AsyncTask$3.done(AsyncTask.java:278) 09-21 00:02:58.235: E/AndroidRuntime(5512): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) this occure if i use apl 14 viurtual machian but in 8 viurtual machian it only appear the ProgressDialog – user1682578 Sep 22 '12 at 09:19
  • @user1688325 Remove Toast line from doInBackground() code and then check. – Dipak Keshariya Sep 22 '12 at 09:26
  • yaa it is work but how can i explaine to user that there is no course @ Dipak Keshariya – user1682578 Sep 22 '12 at 09:36
  • @user1688325 Take one Boolean value and if there is no course then make this flag as false and check on post execute method after dismiss the dialog if flag is false then print toast otherwise don't. – Dipak Keshariya Sep 22 '12 at 09:41
  • thanks it is work :) but what about the other error do you have any sloution – user1682578 Sep 22 '12 at 10:01
  • @user1688325 Which error, please post latest error logcat. – Dipak Keshariya Sep 22 '12 at 10:03
  • 09-21 00:35:00.995: E/AndroidRuntime(6070): FATAL EXCEPTION: AsyncTask #2 09-21 00:35:00.995: E/AndroidRuntime(6070): this is happen if i click in one item list to show the inforamtion – user1682578 Sep 22 '12 at 10:15
  • Write this code 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); after new LoadAllCourses().execute(); line – Dipak Keshariya Sep 22 '12 at 10:18
  • and i delete it form onPostExecute right – user1682578 Sep 22 '12 at 10:25
  • @user1688325 yes, you are right. – Dipak Keshariya Sep 22 '12 at 10:29
  • 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 }); setListAdapter(adapter); a insert as you said after new LoadAllCourses but this error happened [2012-09-22 13:33:23 - com.ksu.sms.SMS] ActivityManager:Starting:Intent{ act=android.intent.action.MAIN cat[android.intent.category.LAUNCHER] cmp=com.ksu.sms/.SMS } [2012-09-22 13:33:23 - com.ksu.sms.SMS] ActivityManager: Warning: Activity not started, its current task has been brought to the front – user1682578 Sep 22 '12 at 10:34
  • @user1688325 first uninstall application and then install again. – Dipak Keshariya Sep 22 '12 at 10:36
  • first uninstall application and then install again can you explain what you means about install where i can found it @Dipak Keshariya – user1682578 Sep 22 '12 at 10:38
  • @user1688325 If you are testing this application on emulator then In emulator, go to settings > Manage Applications > Your_App_Name and then Click on uninstall button and after completion of uninstalling process run application again. – Dipak Keshariya Sep 22 '12 at 10:41
  • i do as you said after a click to show all course there is nothing happend a can not see the course that is in data base empty screen with no course that i can click to show the inforamtion – user1682578 Sep 22 '12 at 10:47
  • @user1688325 Please send me your code, i will send you solution on tuesday, for my email address go to my blog and view my complete profile. – Dipak Keshariya Sep 22 '12 at 10:53