设置异步任务以将Json加载到listview中

时间:2012-02-19 22:01:46

标签: android json listview asynchronous

我从我的服务器上的PHP脚本中获取json对象,然后使用图像的延迟加载将其解析为listview。问题是json将加载相对较快,或者它会挂起一两秒,具体取决于服务器上的响应,这可能令人沮丧。当我第一次打开应用程序时,挂起特别令人讨厌,因为它将挂在黑色屏幕上直到对象已加载,然后当我在应用程序中更新列表时它具有相同但至少视图已加载。这是获取json的代码:

public void getJson(String selection, String url) {
    JSONObject json = null;
    String formatedcat = selection.toLowerCase();
    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
    json = JSONfunctions
            .getJSONfromURL(url);
    try {
        //the array title that you parse
        JSONArray category = json.getJSONArray(formatedcat);
        for (int i = 0; i < category.length(); i++) {               
            HashMap<String, String> map = new HashMap<String, String>();
            JSONObject c = category.getJSONObject(i);
            map.put("id", String.valueOf(i));
            map.put("name",
                    c.getString("title"));
            //map.put("text",c.getString("title"));
            map.put("ts",c.getString("run_date") );
            map.put("image","http:"+c.getString("url"));
            mylist.add(map);
        }
    } catch (JSONException e) {

    }
    ListAdapter adapter = new JsonAdapter(this, mylist, R.layout.list,
            new String[] { "name", "text", "ts"}, new int[] { R.id.item_title,
                    R.id.item_subtitle, R.id.timestamp});
    setListAdapter(adapter);        
}

适配器代码:

public class JsonAdapter extends SimpleAdapter {

    public ImageManager imageManager;
    public ListActivity context;
    public ArrayList<HashMap<String,String>> list;
    public String[] fieldNames;
    public int[] fieldTargetIds;

    public JsonAdapter(ListActivity c, 
            ArrayList<HashMap<String, String>> mylist,
            int textViewResourceId,
            String[] fieldNames,
            int[] fieldTargetIds) {
        super(c, mylist, textViewResourceId, fieldNames, fieldTargetIds );
        this.context = c;
        this.list = mylist;
        this.fieldNames = fieldNames;
        this.fieldTargetIds = fieldTargetIds;
        this.imageManager = new ImageManager(context.getApplicationContext());
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View row = convertView;
        if (row == null) {
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = vi.inflate(R.layout.list, null);
        }
        //super.getView(position, convertView, parent);
        ImageView imgView = (ImageView) row.findViewById(R.id.doodlepic);

        try {
            String url = list.get(position).get("image");
            imgView.setTag(url);
            imageManager.displayImage(url, context, imgView);
        } catch (Exception e) {

        }

        for (int i=0; i<fieldNames.length; i++) {
            TextView tv = (TextView) row.findViewById(fieldTargetIds[i]);
            tv.setText(list.get(position).get(fieldNames[i]));              
        }


        return row;
    }

}

在生成和下载json对象时,如何实现异步任务以显示进度对话框?我尝试过使用线程和异步任务但我无法弄清楚如何将代码拆分为适当的部分。

5 个答案:

答案 0 :(得分:17)

AsyncTecute,onPostExecute的AsyncTask将在UI线程中运行,doInBackground将在另一个线程中运行,所以下面的代码应该对你很好

public class YourActivity extends Activiy{
   public void getJson(String selection, String url) { 
           new LoadJsonTask().execute( selection, url);

   }
   private class LoadJsonTask extends AsyncTask<String, Void, ArrayList<HashMap<String, String>> > {
       ProgressDialog dialog ;
       protected void onPreExecute (){
            dialog = ProgressDialog.show(YourActivity.this ,"title","message");

       }
       protected ArrayList<HashMap<String, String>> doInBackground (String... params){
           return doGetJson(params[0],params[1]);
       }
       protected void onPostExecute(ArrayList<HashMap<String, String>> mylist){

            ListAdapter adapter = new JsonAdapter(YourActivity.this, mylist, R.layout.list,
              new String[] { "name", "text", "ts"}, new int[] { R.id.item_title,
                R.id.item_subtitle, R.id.timestamp});
            setListAdapter(adapter);
            dialog.dismiss();
       }
    }

 public ArrayList<HashMap<String, String>> doGetJson(String selection, String url) {
     JSONObject json = null;
     String formatedcat = selection.toLowerCase();
     ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
     json = JSONfunctions
        .getJSONfromURL(url);
     try {
    //the array title that you parse
    JSONArray category = json.getJSONArray(formatedcat);
    for (int i = 0; i < category.length(); i++) {               
        HashMap<String, String> map = new HashMap<String, String>();
        JSONObject c = category.getJSONObject(i);
        map.put("id", String.valueOf(i));
        map.put("name",
                c.getString("title"));
        //map.put("text",c.getString("title"));
        map.put("ts",c.getString("run_date") );
        map.put("image","http:"+c.getString("url"));
        mylist.add(map);
    }
} catch (JSONException e) {

}
   return mylist;
  ....   
}

答案 1 :(得分:2)

以下是您正在寻找的内容:progressDialog in AsyncTask查看大多数upvotes的答案,应该让您了解如何使用进度对话框进行异步。此外,如果您完全不熟悉AsyncTask,请查看this

答案 2 :(得分:0)

这是一个简单的线程,它会在您获取数据时显示不确定的ProgressDialog,然后在线程执行完毕后解除自身。

...
final ProgressDialog pd = ProgessDialog.show(this, "some title", "some message", true);
Thread t = new Thread(new Runnable(){
    @Override
    public void run(){
       //your code
       ....

       pd.dimiss();
    }
 });
 t.start();
 ...

答案 3 :(得分:0)

成功运行asynctask之后,将listview更改为使用片段可能是值得的。这样,如果列表的适配器当前为空,您将获得一个很好的旋转进度轮。 当您使用默认列表视图项或在自定义布局中包含list_content布局时,会发生这种情况。

执行此操作的最佳方法是创建您的activty,启动asynctask并在任务的onpostexecute方法中,设置listfragment的适配器。通过这种方式,您可以在下载数据时获得良好的加载屏幕。

请参阅: http://developer.android.com/reference/android/app/ListFragment.html#setListShown(boolean

答案 4 :(得分:0)

如果你想使用线程,那么这是一个简单的解决方案

    public class ActivityClass extends Activity implements Runnable, OnItemClickListener {
    ProgressDialog pd;
    ListView list;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        list=(ListView) findViewById(R.id.listview);
        list.setOnItemClickListener(this);
        pd=new ProgressDialog(this);
        pd.setTitle("Please wait");
        pd.setMessage("Loading....");
        pd.setCancelable(false);pd.show();
        Thread th=new Thread(this);
        th.start();
    }

       AlertDialog dialog1;
       private ArrayList<String> titleVal=new ArrayList<String>();
       private ArrayList<String> pubDateVal=new ArrayList<String>();
       private ArrayList<String> linkVal=new ArrayList<String>();

        @Override
    public void run() {
        GetTheFout();
    }
    /**
     * Update If Needed
     */
    ArrayList<Long> count;
        AdapterClass adb;
    public void GetTheFout(){
        try{
        Do json parsing here and store values in arraylist,
        }
        hanlder.sendEmptyMessage(sendMsg);
    }
    private Handler hanlder=new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
                adb=new AdapterClass(BBNewsMain.this,titleVal,pubDateVal);
            list.setAdapter(adb);
        }

    };
//  BroadCast broad;
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
               try{
           ///Handle click event here
               }catch(ArrayIndexOutOfBoundsException e){
                   e.getMessage();
               }
    }
}

注意永远不要更新线程内的UI。这就是我采用一个处理程序类的原因。执行线程后,它将进入处理程序,然后将所有值设置为列表适配器并关闭进度对话框