2012-12-05 100 views
0

我已經完成了JSON解析而不使用異步任務,它在薑餅(2.3) 中工作正常,但是當我在ICS(冰淇淋三明治)應用程序上運行相同的項目時崩潰了,我將不得不做的AsyncTask解析,但我是新來的Android和不能做,有人可以幫我............使用AsynTask JSON解析

這裏是我的JSON類: -

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

這裏是我使用JSON類的MAinActivity: -

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幫助我獲得使用的AsyncTask這個工作.......

+1

如果你的應用程序崩潰,你應該總是發佈你的LogCat錯誤。 – Sam

+0

看到這個http:// stackoverflow。com/a/13599653/1765530 – appukrb

回答

0

是最後我已經做到了感謝對於所有的想法......

我已經創建了另一個asynctask這樣的類: -

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



} 
0

的問題不在於json數據的解析。這裏的問題是你一直在嘗試在Main thread上建立網絡連接。網絡連接是很長的任務,應該在單獨的線程中運行。你在這裏做什麼基本上是把你的

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

線中的AsyncTask 我希望這有助於!

+0

正如我告訴你我是新來的機器人可以üPLZ分享實際解決方案 –

+0

並感謝這....... :) –

+0

檢查我更新的答案! – Ashwani

1

更改代碼中使用的AsyncTask作爲從服務器獲取數據:

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

,並從的onCreate執行活動的AsyncTask爲:

@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..... 

最後你必須瞭解的AsyncTask從這裏下次使用

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

0

首先,考慮在Android中遇到問題/獲取異常時發佈Logcat輸出。

現在,您當前的例外情況是NetworkOnMainThreadException,這是因爲您正在直接在Main Thread上進行Web調用。

從Android 3.0開始,Android已經宣佈你不能直接在Main Thread上完成它。

要解決此問題,您可以實現的AsyncTask或撥打網絡電話之前寫下下面的代碼:

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

瞭解更多:Android StrictMode – NetworkOnMainThreadException

+1

感謝paresh,但它需要最低API級別9,在我的情況下它是API級別8 –