0

i have done JSON parsing without using async task, it is working fine in gingerbread(2.3) but when i am running the same project on ICS(ice cream sandwich) application is crashing, i heard somewhere that i will have to do the parsing in asynctask but i am new to android and unable to do that can someone help me ............

here's my JSON class :-

public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url){
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

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

      //convert response to string
        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();
                result=sb.toString();
        }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
        }

        try{

            jArray = new JSONObject(result);            
        }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
        }

        return jArray;
    }
}

and here's my MAinActivity which is using JSON class :-

public class MainActivity extends ListActivity {

    Context context;
    ArrayList<String> contentList,slugList;
    ArrayList<HashMap<String, String>> mylist;
    JSONObject json;
    JSONArray  latest;
    ImageView bck;
    String shareUrl;

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

        bck = (ImageView) findViewById(R.id.bckbtn);
        mylist = new ArrayList<HashMap<String, String>>();
        contentList=new ArrayList<String>();
        slugList=new ArrayList<String>();
        json = JSONfunctions.getJSONfromURL("http://madhuridixit-nene.com/wp/?json=get_category_posts&slug=latest");
        context=this;

        try{

            latest = json.getJSONArray("posts");

            for(int i=0;i<latest.length();i++){                     
                HashMap<String, String> map = new HashMap<String, String>();    
                JSONObject e = latest.getJSONObject(i);

                String name = e.getString("title_plain");
                String content = e.getString("content");
                contentList.add(content);
                String chng = "&#8211;";
                String  fnl_Str = name.replace(chng, "");
                String slug = e.getString("slug");
                slugList.add(slug);
                map.put("id",  String.valueOf(i));
                map.put("name", fnl_Str);
                map.put("date", e.getString("date"));
                shareUrl ="http://madhuridixit-nene.com/latest/post/";

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

        ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.activity_latest_tab, 
                new String[] { "name"}, 
                new int[] { R.id.item_title});

        setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);  
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              

                /*  HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);   */              
                //Toast.makeText(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
                Intent intent=new Intent(context,WebViewActivity.class);
                intent.putExtra("content", contentList.get(position));
                intent.putExtra("shareUrl", shareUrl+slugList.get(position));
                intent.putExtra("tab_value", 1);
                startActivity(intent);

            }
        });


}

plz help me to get this working using AsyncTask .......

Sam
  • 86,580
  • 20
  • 181
  • 179
Salman Khan
  • 2,822
  • 5
  • 32
  • 53

4 Answers4

1

Change your code Using AsyncTask as for Getting data from server :

private class LongOperation extends AsyncTask<String, Void, 
                                ArrayList<HashMap<String, String>>> {

    ArrayList<String> contentList,slugList;
    ArrayList<HashMap<String, String>> mylist;
    JSONObject json;
    JSONArray  latest;

      @Override
      protected void onPreExecute() {


      }

      @Override
      protected ArrayList<HashMap<String, String>> 
                                  doInBackground(String... params) {
        mylist = new ArrayList<HashMap<String, String>>();
        contentList=new ArrayList<String>();
        slugList=new ArrayList<String>();
        json = JSONfunctions.getJSONfromURL("http://madhuridixit-nene.com"+
                                "/wp/?json=get_category_posts&slug=latest");
        try{

            latest = json.getJSONArray("posts");

            for(int i=0;i<latest.length();i++){                     
                HashMap<String, String> map = new HashMap<String, String>();    
                JSONObject e = latest.getJSONObject(i);

                String name = e.getString("title_plain");
                String content = e.getString("content");
                contentList.add(content);
                String chng = "&#8211;";
                String  fnl_Str = name.replace(chng, "");
                String slug = e.getString("slug");
                slugList.add(slug);
                map.put("id",  String.valueOf(i));
                map.put("name", fnl_Str);
                map.put("date", e.getString("date"));
                shareUrl ="http://madhuridixit-nene.com/latest/post/";

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

        return mylist;
      }      

      @Override
      protected void onPostExecute(
                   ArrayList<HashMap<String, String>> result) {   
      ListAdapter adapter = new SimpleAdapter(this, result , 
                                 R.layout.activity_latest_tab, 
                new String[] { "name"}, 
                new int[] { R.id.item_title});

        setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);  
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, 
                         View view, int position, long id) {              

             Intent intent=new Intent(MainActivity.this,WebViewActivity.class);
             intent.putExtra("content", contentList.get(position));
             intent.putExtra("shareUrl", shareUrl+slugList.get(position));
             intent.putExtra("tab_value", 1);
             startActivity(intent);

            }
        });            
      }



      @Override
      protected void onProgressUpdate(Void... values) {
      }
}

and execute AsyncTask from onCreate of Activity as:

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

        bck = (ImageView) findViewById(R.id.bckbtn);
        new LongOperation().execute(""); // execute here
        // your code here.....

finally you must read about AsyncTask for next use from here

http://developer.android.com/reference/android/os/AsyncTask.html

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

The problem is not with parsing of json data. The problem here is that you've been trying to make network connection on the Main thread. Network connections are long tasks and should be run in a separate thread. What you have to do here is basically put your

json = JSONfunctions.getJSONfromURL("http://madhuridixit-nene.com/wp/?json=get_category_posts&slug=latest");

line in the AsyncTask I hope this helps!

Ashwani
  • 1,574
  • 14
  • 28
0

First of all, consider to post Logcat output whenever you are facing issue/getting exceptions in Android.

Now, your current exception is NetworkOnMainThreadException, which is just because of you are making a web call directly on Main Thread.

From Android 3.0, Android has announced you can't do it directly on Main Thread.

To resolve this issue, you can either implement AsyncTask or write down the below code before making a web call:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Read more: Android StrictMode – NetworkOnMainThreadException

Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
0

yes finally i have done it thanks for all the ideas ......

I have created another class for asynctask like this :-

class MyAsyncTask extends AsyncTask> > { ArrayList> mylist = new ArrayList>();

    @Override
    protected ArrayList<HashMap<String, String>> doInBackground(
            String... params) {
        // TODO Auto-generated method stub

        mylist = new ArrayList<HashMap<String, String>>();
        contentList=new ArrayList<String>();
        slugList=new ArrayList<String>();
        json = JSONfunctions.getJSONfromURL("http://madhuridixit-nene.com/wp/?json=get_category_posts&slug=latest");


        try{

            latest = json.getJSONArray("posts");

            for(int i=0;i<latest.length();i++){                     
                HashMap<String, String> map = new HashMap<String, String>();    
                JSONObject e = latest.getJSONObject(i);

                String name = e.getString("title_plain");
                String content = e.getString("content");
                contentList.add(content);
                String chng = "&#8211;";
                String  fnl_Str = name.replace(chng, "");
                String slug = e.getString("slug");
                slugList.add(slug);
                map.put("id",  String.valueOf(i));
                map.put("name", fnl_Str);
                map.put("date", e.getString("date"));
                shareUrl ="http://madhuridixit-nene.com/latest/post/";

                mylist.add(map);            
            }       
        }catch(JSONException e)        {
            Log.e("log_tag", "Error parsing data "+e.toString());
        }
        showProgress.setVisibility(View.VISIBLE);
        return mylist;
    }

    @Override
    protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
        ListAdapter adapter = new SimpleAdapter(LAtestTab.this, result , R.layout.activity_latest_tab, 
                new String[] { "name" }, 
                new int[] { R.id.item_title});
        LAtestTab.this.setListAdapter(adapter);// If Activity extends ListActivity
        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        showProgress.setVisibility(View.GONE);
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              


                Intent intent=new Intent(context,WebViewActivity.class);
                intent.putExtra("content", contentList.get(position));
                intent.putExtra("shareUrl", shareUrl+slugList.get(position));
                intent.putExtra("tab_value", 1);
                startActivity(intent);

            }
        });

    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        showProgress.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        // TODO Auto-generated method stub

        super.onProgressUpdate(values);
        showProgress.setVisibility(View.VISIBLE);
    }



 }
Salman Khan
  • 2,822
  • 5
  • 32
  • 53