android - JSON 解析器性能低下

标签 android json http parsing request

我在这里重新发布以获得一些帮助。

我制作了一个返回 JSONArray 的 JSON 解析器(以便从我的 Web 服务获取信息)。

当我在 IceScreamSandwich 上测试它时,我的最后一个代码抛出了一个 NetworkException 错误(在 2.3.3 版本上它很长但工作正常)..

我更改了我的代码以阻止它并尝试获得更好的性能..但它仍然无法在我的 ICS 手机上运行:现在没有更多错误但 ioexcepetion:“无法从 JSON URL 读取”..

我给你看我的 Activity :

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

还有我的解析器:

公共(public)类 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");
     }
 }

谁知道如何获得更好的性能并使其成为 4.0 的朗姆酒? 如何将它与异步任务一起使用? 谢谢

最佳答案

您需要使用 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);


        }

    }
}

关于android - JSON 解析器性能低下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11451703/

相关文章:

android - Nexus 5 无法连接到外围设备

android - 在 Android 上的 Crosswalk WebView 中以编程方式设置 cookie

android - 如何将 ChrisBanes 的 ActionBar-PullToRefresh 库与具有 GridView 的 fragment 一起使用

python - 在 Python 3 中导入模块时出现 AttributeError

javascript - 使用 select2 ajax 发送 data-* 属性

java - 如何使用 Wicket (Java) 获取原始 http header (用于基本身份验证)?

http - 为 HTTP 重用客户端 TCP 连接

java - dataDir 中的文件存在于 Android 中的什么位置?

javascript - 无法在 prestashop 上创建新帐户

c# - .NET:检查 URL 的响应状态代码?