2012-07-12 76 views
1

我重新發布我這裏爲了得到一些幫助。JSON解析器低性能

我做了一個JSON解析器至極返回JSONArray(爲了得到我的WebService的信息)。

我最後的代碼扔了NetworkException錯誤(在版本2.3.3它是長,但良好的工作),當我測試IceScreamSandwich ..

我改變了我的代碼,以阻止它,並嘗試變得更好perfs ..但它仍然沒有工作對我的ICS電話:現在沒有更多的錯誤,但一個ioexcepetion:「失敗的JSON的網址改爲」 ..

我告訴你我的活動:

public class TabNewsJSONParsingActivity extends ListActivity 

{

// url to make request 
private static String url = "http://developer.prixo.fr/API/GetEvents?zone=8"; 

//JSON names 
private static final String TAG_content = "content"; 
private static final String TAG_zone = "zone"; 
private static final String TAG_id = "id"; 
private static final String TAG_area = "area"; 
private static final String TAG_title = "title"; 
private static final String TAG_date = "date"; 
private static final String TAG_author = "author"; 

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

    // Hashmap for ListView 
    ArrayList<HashMap<String, String>> newsList = new ArrayList<HashMap<String, String>>(); 

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

    // getting JSON string from URL 
    JSONArray json; 
    try { 
     json = jParser.getJSONFromUrl1(url); 

       for(int i=0; i < json.length(); i++) 
       { 
        JSONObject child = json.getJSONObject(i); 

        String id = child.getString(TAG_id); 
        String title = child.getString(TAG_title); 
        String content = child.getString(TAG_content); 
        String date = child.getString(TAG_date); 
        String author = child.getString(TAG_author); 
        String zone = child.getString(TAG_zone); 
        String area = child.getString(TAG_area); 


        // creating new HashMap 
        HashMap<String, String> map = new HashMap<String, String>(); 

        // adding each child node to HashMap key => value 
        map.put(TAG_content, content); 
        map.put(TAG_title, title); 
        map.put(TAG_author, author); 

        // adding HashList to ArrayList 
        newsList.add(map); 
       } 
      } 
     catch (JSONException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    /** 
    * Updating parsed JSON data into ListView 
    * */ 
    ListAdapter adapter = new SimpleAdapter(this, newsList,R.layout.onglet_news_listitem,new String[] { TAG_content, TAG_title, TAG_author }, new int[] {R.id.name, R.id.email, R.id.mobile }); 
    setListAdapter(adapter); 

    // selecting single ListView item 
    ListView lv = getListView(); 

    // Launching new screen on Selecting Single ListItem 
    lv.setOnItemClickListener(new OnItemClickListener() 
    { 
     public void onItemClick(AdapterView<?> parent, View view,int position, long id) { 
      // getting values from selected ListItem 
      String name = ((TextView) view.findViewById(R.id.name)).getText().toString(); 
      String cost = ((TextView) view.findViewById(R.id.email)).getText().toString(); 
      String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString(); 

      // Starting new intent 
      Intent in = new Intent(getApplicationContext(), TabNewsSingleMenuItemActivity.class); 
      in.putExtra(TAG_content, name); 
      in.putExtra(TAG_title, cost); 
      in.putExtra(TAG_author, description); 
      startActivity(in); 

     } 
    }); 
} 

public boolean onOptionsItemSelected(MenuItem item) 
{ 
    //On regarde quel item a été cliqué grâce à son id et on déclenche une action 
    switch (item.getItemId()) 
    { 
     case R.id.credits: 
     //pop up 
     Toast.makeText(TabNewsJSONParsingActivity.this, "Un delire", Toast.LENGTH_SHORT).show(); 
     return true; 
     case R.id.quitter: 
     //Pour fermer l'application il suffit de faire finish() 
     finish(); 
     return true; 
    } 
return false; 
} 

}

我的解析器:

公共類JSONParser {

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

public JSONParser() {} 

// throws IOException just to tell the caller that something bad happened (and 
// what) instead of simply returning 'null' without any more information. 
public JSONArray getJSONFromUrl1(String url) throws IOException 
{ 
    try 
    { 
     // should be a member of the parser to allow multiple calls without recreating the client every time. 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     // Using POST means sending data (or it its not following HTTP RFCs) 
     //HttpPost httpPost = new HttpPost(url); 
     HttpGet httpGet = new HttpGet(url); 

     // Here the client may not be entirely initialized (no timeout, no agent-string). 
     HttpResponse httpResponse = httpClient.execute(httpGet); 
     //HttpResponse httpResponse = httpClient.execute(httpPost); 

     HttpEntity httpEntity = httpResponse.getEntity(); 

     // The native utility function is also handling other charsets 
     String httpString = EntityUtils.toString(httpEntity); 

     return new JSONArray(httpString); 
    } catch (IOException ioe) { 
    throw ioe; 
    } catch (Exception ex) { 
    throw new IOException("Failed to read JSON from Url"); 
    } 
} 

}

誰知道得到更好的perfs並使其朗姆酒4.0嗎? 如何將它與異步任務一起使用? 感謝

回答

1

你需要使用的AsyncTask下載和解析您的數據

代碼如下

import java.io.IOException; 
import java.util.ArrayList; 
import java.util.HashMap; 

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.os.StrictMode; 
import android.view.MenuItem; 
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 TabNewsJSONParsingActivity extends ListActivity 
{ 
    static{ 
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 

     StrictMode.setThreadPolicy(policy); 
    } 

    // url to make request 
    private static String url = "http://developer.prixo.fr/API/GetEvents?zone=8"; 

    //JSON names 
    private static final String TAG_content = "content"; 
    private static final String TAG_zone = "zone"; 
    private static final String TAG_id = "id"; 
    private static final String TAG_area = "area"; 
    private static final String TAG_title = "title"; 
    private static final String TAG_date = "date"; 
    private static final String TAG_author = "author"; 

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



     // selecting single ListView item 
     ListView lv = getListView(); 

     // Launching new screen on Selecting Single ListItem 
     lv.setOnItemClickListener(new OnItemClickListener() 
     { 
      public void onItemClick(AdapterView<?> parent, View view,int position, long id) { 
       // getting values from selected ListItem 
       String name = ((TextView) view.findViewById(R.id.name)).getText().toString(); 
       String cost = ((TextView) view.findViewById(R.id.email)).getText().toString(); 
       String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString(); 

       // Starting new intent 
       Intent in = new Intent(getApplicationContext(), TabNewsSingleMenuItemActivity.class); 
       in.putExtra(TAG_content, name); 
       in.putExtra(TAG_title, cost); 
       in.putExtra(TAG_author, description); 
       startActivity(in); 

      } 
     }); 

     new DownloadData().execute(); 
    } 

    public boolean onOptionsItemSelected(MenuItem item) 
    { 
     //On regarde quel item a été cliqué grâce à son id et on déclenche une action 
     switch (item.getItemId()) 
     { 
      case R.id.credits: 
      //pop up 
      Toast.makeText(TabNewsJSONParsingActivity.this, "Un delire", Toast.LENGTH_SHORT).show(); 
      return true; 
      case R.id.quitter: 
      //Pour fermer l'application il suffit de faire finish() 
      finish(); 
      return true; 
     } 
    return false; 
    } 


    private class DownloadData extends AsyncTask<Void, Integer, ArrayList<HashMap<String, String>>> 
    { 
     ProgressDialog pd = null; 
     /* (non-Javadoc) 
     * @see android.os.AsyncTask#onPreExecute() 
     */ 
     @Override 
     protected void onPreExecute() { 
      // TODO Auto-generated method stub 
      super.onPreExecute(); 

      pd = new ProgressDialog(TabNewsJSONParsingActivity.this); 
      pd.setTitle("Downloading..."); 
      pd.setMessage("Please wait..."); 
      pd.setCancelable(false); 
      pd.show(); 
     } 

     /* (non-Javadoc) 
     * @see android.os.AsyncTask#doInBackground(Params[]) 
     */ 
     @Override 
     protected ArrayList<HashMap<String, String>> doInBackground(Void... params) { 
      // TODO Auto-generated method stub 

      // Hashmap for ListView 
      ArrayList<HashMap<String, String>> newsList = new ArrayList<HashMap<String, String>>(); 

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

      // getting JSON string from URL 
      JSONArray json; 
      try { 
       json = jParser.getJSONFromUrl1(url); 

         for(int i=0; i < json.length(); i++) 
         { 
          JSONObject child = json.getJSONObject(i); 

          String id = child.getString(TAG_id); 
          String title = child.getString(TAG_title); 
          String content = child.getString(TAG_content); 
          String date = child.getString(TAG_date); 
          String author = child.getString(TAG_author); 
          String zone = child.getString(TAG_zone); 
          String area = child.getString(TAG_area); 


          // creating new HashMap 
          HashMap<String, String> map = new HashMap<String, String>(); 

          // adding each child node to HashMap key => value 
          map.put(TAG_content, content); 
          map.put(TAG_title, title); 
          map.put(TAG_author, author); 

          // adding HashList to ArrayList 
          newsList.add(map); 
         } 
        } 
       catch (JSONException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

      return newsList; 
     } 

     /* (non-Javadoc) 
     * @see android.os.AsyncTask#onPostExecute(java.lang.Object) 
     */ 
     @Override 
     protected void onPostExecute(ArrayList<HashMap<String, String>> newsList) { 
      // TODO Auto-generated method stub 
      super.onPostExecute(newsList); 
      pd.dismiss(); 

      /** 
      * Updating parsed JSON data into ListView 
      * */ 
      ListAdapter adapter = new SimpleAdapter(TabNewsJSONParsingActivity.this, newsList,R.layout.onglet_news_listitem,new String[] { TAG_content, TAG_title, TAG_author }, new int[] {R.id.name, R.id.email, R.id.mobile }); 
      TabNewsJSONParsingActivity.this.setListAdapter(adapter); 


     } 

    } 
} 
+0

謝謝,我嘗試過,但我在ListAdapter適配器=此編譯錯誤新SimpleAdapter(..):「SimpleAdapter構造是不確定的」 – eento 2012-07-12 14:01:24

+0

@eento請找到更新的代碼。這是由'this'參數引起的。而是請使用'TabNewsJSONParsingActivity.this' – sunil 2012-07-13 05:21:47

0

這可能是因爲你運行在主線程Web連接..嘗試運行這段代碼到的AsyncTask或不同的線程..

+0

你能給我舉一個異步任務結合的例子嗎我的下載內容和我的地圖? – eento 2012-07-12 13:08:43

1

開始你AsycnTask:

JSONTask g = new JSONTask(); 
g.execute(); 

還有一些關於如何實現它的代碼;

public abstract class JSONTask extends AsyncTask<String, Void, String> { 
@Override 
protected String doInBackground(String... arg) { 
    //Do http get json here 
    String htpStatus= ""; 
    String httpJSON = "" // this is the json data from you web service 

    // Create here your JSONObject... 
    JSONObject json = new JSONObject(httpJSON); 
    for(int i=0; i < json.length(); i++){ 
       JSONObject child = json.getJSONObject(i); 

       String id = child.getString(TAG_id); 
       String title = child.getString(TAG_title); 
       String content = child.getString(TAG_content); 
       String date = child.getString(TAG_date); 
       String author = child.getString(TAG_author); 
       String zone = child.getString(TAG_zone); 
       String area = child.getString(TAG_area); 


       // creating new HashMap 
       HashMap<String, String> map = new HashMap<String, String>(); 

       // adding each child node to HashMap key => value 
       map.put(TAG_content, content); 
       map.put(TAG_title, title); 
       map.put(TAG_author, author); 

       // adding HashList to ArrayList 
       newsList.add(map); 
    } 
    return htpStatus; // This value will be returned to your onPostExecute(result) method 
} 

@Override 
protected void onPostExecute(String result) { 

} 
} 
+1

很好的例子,但我會解析doInBackground內的JSON消息()方法,以避免UI凍結.. :) – Cata 2012-07-12 20:10:12

+0

嗚嗚......我也是,編輯;從我側P – 2012-07-13 06:55:41

+0

+1 :P – Cata 2012-07-13 09:16:28