使用AsyncTask进行JSON解析

时间:2012-12-05 05:18:11

标签: android json

我在不使用异步任务的情况下完成了JSON解析,它在姜饼中运行良好(2.3) 但是当我在ICS(冰淇淋三明治)上运行相同的项目应用程序崩溃时,我听到某个地方我将不得不在asynctask中进行解析但我不熟悉android并且无法做到这一点可以有人帮助我... .........

这是我的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 .......

4 个答案:

答案 0 :(得分: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) {
      }
}

从Activity的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

答案 1 :(得分:0)

问题不在于解析json数据。这里的问题是您一直在尝试在Main thread上建立网络连接。网络连接是长任务,应该在单独的线程中运行。你在这里要做的基本上是你的

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

在AsyncTask中排队  我希望这有帮助!

答案 2 :(得分:0)

首先,考虑在Android中遇到问题/获取异常时发布Logcat输出。

现在,您当前的异常是 NetworkOnMainThreadException ,这只是因为您正在主线程上直接进行Web调用。

从Android 3.0开始,Android宣布你无法直接在主线程上进行。

要解决此问题,您可以在进行网络通话之前实施 AsyncTask 或记下以下代码:

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

了解详情:Android StrictMode – NetworkOnMainThreadException

答案 3 :(得分:0)

是的,最后我感谢所有的想法......

我为asynctask创建了另一个类,如下所示: -

类MyAsyncTask扩展了AsyncTask&gt; &GT; {          的ArrayList&GT; mylist = new ArrayList&gt;();

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



 }