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

Android 设置异步任务以将Json加载到listview,android,json,listview,asynchronous,Android,Json,Listview,Asynchronous,我从服务器上的PHP脚本生成json对象,然后使用图像的延迟加载将其解析为listview。问题是json的加载速度相对较快,或者会根据服务器上的响应挂起一两秒钟,这可能会令人沮丧。当我第一次打开应用程序时,挂起尤其令人恼火,因为它将在黑屏上挂起,直到加载对象,然后当我在应用程序中更新列表时,它具有相同的挂起,但至少视图已加载。以下是获取json的代码: public void getJson(String selection, String url) { JSONObject json

我从服务器上的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 void getJson(字符串选择,字符串url){
JSONObject json=null;
String formattedcat=selection.toLowerCase();
ArrayList mylist=新的ArrayList();
json=json函数
.getJSONfromURL(url);
试一试{
//解析的数组标题
JSONArray category=json.getJSONArray(formattedcat);
对于(inti=0;i
适配器代码:

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

}
公共类JsonAdapter扩展了SimpleAdapter{
公共图像管理器图像管理器;
公共活动语境;
公共阵列列表;
公共字符串[]字段名;
公共int[]FieldTargetId;
公共JsonAdapter(列表c,
ArrayList mylist,
int textViewResourceId,
字符串[]字段名,
int[]FieldTargetId){
super(c、mylist、textViewResourceId、字段名、FieldTargetId);
this.context=c;
this.list=mylist;
this.fieldNames=字段名;
this.fieldTargetIds=fieldTargetIds;
this.imageManager=新的imageManager(context.getApplicationContext());
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
视图行=转换视图;
if(行==null){
LayoutInflater vi=(LayoutInflater)getSystemService(Context.LAYOUT\u INFLATER\u SERVICE);
行=vi.充气(R.布局.列表,空);
}
//super.getView(position、convertView、parent);
ImageView imgView=(ImageView)row.findViewById(R.id.doodlepic);
试一试{
字符串url=list.get(位置).get(“图像”);
setTag(url);
displayImage(url、上下文、imgView);
}捕获(例外e){
}

对于(int i=0;i以下是您要查找的内容:使用最多的向上投票来查看答案,这会让您了解如何使用进度对话框进行异步。此外,如果您完全不熟悉AsyncTask,请查看下面的一个简单线程,它将在获取数据时显示一个不确定的进度对话框,然后自动关闭一次线程已完成执行

...
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();
 ...

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

最好的方法是创建activty,启动asynctask,然后在任务的
onpostexecute
方法中设置listfragment的适配器。这样,在下载数据时,您将获得一个漂亮的加载屏幕

见:
)异步任务的onPreExecute、onPostExecute将在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;
  ....   
}
公共类YourActivity扩展了Activity{
public void getJson(字符串选择,字符串url){
新建LoadJsonTask().execute(选择,url);
}
私有类LoadJsonTask扩展了AsyncTask{
进程对话;
受保护的void onPreExecute(){
dialog=ProgressDialog.show(YourActivity.this,“title”,“message”);
}
受保护的ArrayList doInBackground(字符串…参数){
返回doGetJson(参数[0],参数[1]);
}
受保护的void onPostExecute(ArrayList mylist){
ListAdapter=new JsonAdapter(YourActivity.this、mylist、R.layout.list、,
新字符串[]{“name”,“text”,“ts”},新int[]{R.id.item_title,
R.id.item_副标题,R.id.timestamp});
setListAdapter(适配器);
dialog.dismise();
}
}
公共ArrayList doGetJson(字符串选择,字符串url){
JSONObject json=null;
String formattedcat=selection.toLowerCase();
ArrayList mylist=新的ArrayList();
json=json函数
.getJSONfromURL(url);
试一试{
//解析的数组标题
JSONArray category=json.getJSONArray(formattedcat);
对于(inti=0;i
如果要使用线程,则
    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();
               }
    }
}