0

我在没有使用异步任务的情况下完成了 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);

            }
        });


}

请帮助我使用 AsyncTask 完成这项工作.......

4

4 回答 4

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

于 2012-12-05T05:35:55.517 回答
0

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

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

在 AsyncTask 中的行我希望这会有所帮助!

于 2012-12-05T05:29:52.110 回答
0

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

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

从 Android 3.0 开始,Android 已经宣布您不能直接在主线程上执行此操作。

要解决此问题,您可以实现AsyncTask或在进行 Web 调用之前写下以下代码:

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

阅读更多:Android StrictMode – NetworkOnMainThreadException

于 2012-12-05T05:39:39.130 回答
0

是的,我终于做到了,感谢所有的想法......

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

类 MyAsyncTask 扩展 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);
    }



 }
于 2012-12-05T13:18:46.877 回答