0

I'm trying to get a list by making request to server. For that I'm using asynctask to deal with it. The code goes like this. Even after doing so many experiments that are online I'm getting logcat errors as follows.

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlarmManager;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class AndroidJSONParsingActivity extends ListActivity {

public static String url = "http://ensignweb.com/sandbox/app/comment11.php";

    // JSON Node names
    protected static final String TAG_PRODUCTS = "products";
    protected static final String TAG_CID = "cid";
    public static final String TAG_NAME = "name";

    // contacts JSONArray
    JSONArray products = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        new Message().execute(url);
        startService(new Intent(this, UpdateService.class));
        Intent intent = new Intent(this,UpdateService.class);
        PendingIntent pIntent = PendingIntent.getService(this, 0, intent, 0);
        AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30000, pIntent);


    }

@Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();

    }
    //Belongs to update service
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
//      stopService(new Intent(this, UpdateService.class));
    }

    class Message extends AsyncTask<String, Integer, ArrayList<HashMap<String, String>> > {
        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

                @Override
            protected ArrayList<HashMap<String, String>> doInBackground(String... params) {

                    // Creating JSON Parser instance
                    JSONParser jParser = new JSONParser();

                    // getting JSON string from URL
                    JSONObject json = jParser.getJSONFromUrl(params[0]);


                    try {
                        // Getting Array of Contacts
                        products = json.getJSONArray(TAG_PRODUCTS);

                        // looping through All Contacts
                        for(int i = products.length()-1; i >=0; i--){
                            JSONObject c = products.getJSONObject(i);

                            // Storing each json item in variable
                            String cid = c.getString(TAG_CID);
                            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_CID, cid);
                            map.put(TAG_NAME, name);

                            // adding HashList to ArrayList
                            mylist.add(map);
                            Log.d("value", mylist.toString());
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    return mylist;
                }

            @Override
            protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
                ListAdapter adapter = new SimpleAdapter(AndroidJSONParsingActivity.this, result , R.layout.list_item,new String[] { TAG_NAME,}, new int[] {
                        R.id.name});
                AndroidJSONParsingActivity.this.setListAdapter(adapter);// If Activity extends ListActivity
                final ListView lv = getListView();
                lv.setTextFilterEnabled(true);

            }

    }
}

JSONParser.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

The logcat shows this message

    01-11 11:46:34.331: E/Buffer Error(483): Error converting result java.io.IOException: Attempted read on closed stream.
01-11 11:46:34.331: E/JSON Parser(483): Error parsing data org.json.JSONException: End of input at character 0 of 
01-11 11:46:34.331: W/dalvikvm(483): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
01-11 11:46:34.342: E/AndroidRuntime(483): FATAL EXCEPTION: AsyncTask #1
01-11 11:46:34.342: E/AndroidRuntime(483): java.lang.RuntimeException: An error occured while executing doInBackground()
01-11 11:46:34.342: E/AndroidRuntime(483):  at android.os.AsyncTask$3.done(AsyncTask.java:200)
01-11 11:46:34.342: E/AndroidRuntime(483):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-11 11:46:34.342: E/AndroidRuntime(483):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-11 11:46:34.342: E/AndroidRuntime(483):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-11 11:46:34.342: E/AndroidRuntime(483):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-11 11:46:34.342: E/AndroidRuntime(483):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
01-11 11:46:34.342: E/AndroidRuntime(483):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
01-11 11:46:34.342: E/AndroidRuntime(483):  at java.lang.Thread.run(Thread.java:1096)
01-11 11:46:34.342: E/AndroidRuntime(483): Caused by: java.lang.NullPointerException
01-11 11:46:34.342: E/AndroidRuntime(483):  at com.androidhive.jsonparsing.AndroidJSONParsingActivity$Message.doInBackground(AndroidJSONParsingActivity.java:95)
01-11 11:46:34.342: E/AndroidRuntime(483):  at com.androidhive.jsonparsing.AndroidJSONParsingActivity$Message.doInBackground(AndroidJSONParsingActivity.java:1)
01-11 11:46:34.342: E/AndroidRuntime(483):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
01-11 11:46:34.342: E/AndroidRuntime(483):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-11 11:46:34.342: E/AndroidRuntime(483):  ... 4 more

log.d "json string" shows like this

01-11 12:43:29.891: D/json string(629): {"success":1,"products":[{"cid":"1","name":"bernard"},{"cid":"2","name":"Vijay"},{"cid":"3","name":"vikas_admin"},{"cid":"4","name":"vikas_admin"},{"cid":"5","name":"vikas_admin"},{"cid":"6","name":"vikas_admin"},{"cid":"7","name":"Vikas B L"},{"cid":"8","name":"chanakyavikas"},{"cid":"9","name":"vikram"},{"cid":"10","name":"Vidya"},{"cid":"11","name":"bernard"},{"cid":"12","name":"Thenewone"},{"cid":"13","name":"another"},{"cid":"14","name":"1245"},{"cid":"15","name":"kljdf.d,samfas"},{"cid":"16","name":"this"},{"cid":"17","name":"l;asdkfjalskjf"},{"cid":"18","name":"just got refreshed "},{"cid":"19","name":"not working"},{"cid":"20","name":"Checking"},{"cid":"21","name":"trying again"},{"cid":"22","name":"checking after few minutes"},{"cid":"23","name":"checking after many minutes"},{"cid":"24","name":"this one after 40 mintues"},{"cid":"25","name":"Let me try it once again. Even after this, it must run"},{"cid":"26","name":"Coming to track"},{"cid":"27","name":"let me check after 40 minutes"},{"cid":"28","name":"Ok. Let me give some time"},{"cid":"29","name":"let me check after lunch"},{"cid":"30","name":"checking after more than 2 hours"},{"cid":"31","name":"Now trying without icon. Lets see how it will gonna work"},{"cid":"32","name":"mic checking"},{"cid":"33","name":"check check check"},{"cid":"34","name":"check check again"},{"cid":"35","name":"Back to work"},{"cid":"36","name":"trying long long long time after"},{"cid":"37","name":"bye byeeeeeeeeeee"},{"cid":"38","name":"how is it going"},{"cid":"39","name":"Good morning Ensign"},{"cid":"40","name":"Trying AlarmManager"},{"cid":"41","name":"alarm! alarm! alarm!"},{"cid":"42","name":"Its been more than 30minutes"},{"cid":"43","name":"Let me see in the mobile about its working"},{"cid":"44","name":"How is it going"},{"cid":"45","name":"How is it going after many hours"},{"cid":"46","name":"huga huga huga"},{"cid":"47","name":"bye bye"},{"cid":"48","name":"It is now 7.47"},{"cid":"49","name":"Good morning Ensign"},{"cid":"50","name":"Once again good morning"},{"cid":"51","name":"Inside the office"},{"cid":"52","name":"Not working again"},{"cid":"53","name":"asdlkfjalsjfdl"},{"cid":"54","name":"Trying again and again"},{"cid":"55","name":"akl;sdjf;las"},{"cid":"56","name":"alarm! alarm! alarm!"},{"cid":"57","name":"adding boot complete"},{"cid":"58","name":"We are three now"},{"cid":"59","name":"check check again again"},{"cid":"60","name":"How is working now"},{"cid":"61","name":"Date is 10\/01\/2013"},{"cid":"62","name":"Now working fine"},{"cid":"63","name":"Had a good lunch"},{"cid":"64","name":"I'm with Mr. Johan "},{"cid":"65","name":"Let me check if booting works or not."},{"cid":"66","name":"checking after rebooting"},{"cid":"67","name":"Nop! rebooting not working"}]}
Community
  • 1
  • 1

3 Answers3

1

use

 dialog=ProgressDialog.show(AndroidJSONParsingActivity.this, 
                                      "Processing", "Please be patient");

instead of

dialog.show(getApplicationContext(), "Processing", "Please be patient");

to show ProgressDialog from AsyncTask

ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
0

use this insteadOf getApplicationContext in onPreExecute method for showing alert

Deepzz
  • 4,573
  • 1
  • 28
  • 52
Dinesh T A
  • 2,087
  • 4
  • 26
  • 34
0

The stack trace says that you're trying to read data from a stream that has been closed. This sounds like you're trying to read the response from the web after you've already closed the stream. Double check this when reading Json from the web.

Also you're getting a null pointer. To find these you should be able to go through the code line by line in the debugger (use conditional breakpoints if in the for loop otherwise would be hellish to debug). At a glance I'd hazard a guess that it's the following line that's killing you

products = json.getJSONArray(TAG_PRODUCTS);

I'm guessing this because if the data failed to return from the net then the json object would be null.

hope this helps any more questions let me know

chris-tulip
  • 1,840
  • 1
  • 15
  • 22