0

I have been searching about how to bring data from mysql and show them with custom listview. Now, I found a problem with Http request. Could anyone please help me check this code? I cannot find out why my code cannot work.

MainActivity.java

public class MainActivity extends Activity {

    ArrayList<Mall> arrayOfMallData = new ArrayList<Mall>();

    class Mall{
        public String Mall_title;
        public String Mall_desc;
    }

    FancyAdapter fancyAdapter = null;
    static ArrayList<String> resultRow;


@Override
protected void onCreate(Bundle savedInstanceState) {

    try{
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String result = "";

        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://10.0.2.2/BasicPHP/getJSON.php");
            HttpResponse response = httpClient.execute(httppost);
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();

            try {

                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }

                is.close();
                result = sb.toString();

            } catch (Exception e) {
                Log.e("log_tag", "Error converting result " + e.toString());
            }
        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        try {

            JSONArray jArray = new JSONArray(result);

            for(int i=0;i<jArray.length();i++) {
                JSONObject f = jArray.getJSONObject(i);

                Mall resultRow = new Mall();

                resultRow.Mall_title = f.getString("Mall_Name");    
                resultRow.Mall_desc = f.getString("Mall_Business_Hours");

                arrayOfMallData.add(resultRow);              
            }
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());     
        }


        ListView listView = (ListView)findViewById(R.id.listView);
        fancyAdapter = new FancyAdapter();
        listView.setAdapter(fancyAdapter); 

    } catch (Exception e) {
        Log.e("log_tag", "Error In Code: " + e.toString());
    }
}

class FancyAdapter extends ArrayAdapter<Mall> {
    FancyAdapter() {
        super(MainActivity.this, android.R.layout.simple_list_item_1, arrayOfMallData);
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null){
            LayoutInflater inflater = getLayoutInflater();
            convertView = inflater.inflate(R.layout.malllist_item, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder)convertView.getTag();
        }
        holder.populateFrom(arrayOfMallData.get(position));
        return(convertView);
    }
}

class ViewHolder {
    public TextView title = null;
    public TextView desc = null;

    ViewHolder(View row) {
        title = (TextView)row.findViewById(R.id.title);
        desc = (TextView)row.findViewById(R.id.desc);
    }

    void populateFrom(Mall r) {
        title.setText(r.Mall_title);
        desc.setText(r.Mall_desc);

    }
}  
}

This is my LogCat

05-16 15:36:53.334: I/dalvikvm(539): threadid=3: reacting to signal 3
05-16 15:36:53.384: I/dalvikvm(539): Wrote stack traces to '/data/anr/traces.txt'
05-16 15:36:53.494: E/log_tag(539): Error in http connection android.os.NetworkOnMainThreadException
05-16 15:36:53.494: E/log_tag(539): Error parsing data org.json.JSONException: End of input at character 0 of 
05-16 15:36:53.594: D/libEGL(539): loaded /system/lib/egl/libGLES_android.so
05-16 15:36:53.614: D/libEGL(539): loaded /system/lib/egl/libEGL_emulation.so
05-16 15:36:53.634: D/(539): HostConnection::get() New Host Connection established 0x1dee68, tid 539
05-16 15:36:53.654: D/libEGL(539): loaded /system/lib/egl/libGLESv1_CM_emulation.so
05-16 15:36:53.665: D/libEGL(539): loaded /system/lib/egl/libGLESv2_emulation.so
05-16 15:36:53.726: W/EGL_emulation(539): eglSurfaceAttrib not implemented
05-16 15:36:53.744: D/OpenGLRenderer(539): Enabling debug mode 0
05-16 15:36:53.854: I/dalvikvm(539): threadid=3: reacting to signal 3
05-16 15:36:53.875: I/dalvikvm(539): Wrote stack traces to '/data/anr/traces.txt'

2 Answers2

2

In the method onCreate(Bundle savedInstanceState) which is on main thread you are doing some web calls, this is the cause of the problem, you are not allowed to do this HttpResponse response = httpClient.execute(httppost); on the main thread. Move the networking part on a different thread. Take a look at this AsyncTask Android example

Community
  • 1
  • 1
bogdan
  • 782
  • 3
  • 7
0
android.os.NetworkOnMainThreadException 

This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask. Like

private class RetriveJson extends AsyncTask<String, Void, JSONObject> {

    @Override
    protected JSONObject doInBackground(String... params) {
                   //retrive your data via url from here
        }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }

}

and call this task at where you want like

new RetriveJson().execute("your url");

I hope this will help you.

Gunaseelan
  • 14,415
  • 11
  • 80
  • 128