AsyncTask和listActivity

时间:2012-08-20 20:58:13

标签: android android-listview android-asynctask

我已经做了这个简单的应用程序,在这个应用程序中,当我点击开始按钮时我想查看Listview中的数据,但它不起作用。你能救我吗?

mainActivity.java

public class MainActivity extends ListActivity {
public ArrayList<Map<String, String>> list= new ArrayList<Map<String, String>>();
public ListAdapter adapter;
public ProgressDialog progressDialog; 

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button buttonAggiorna = (Button) findViewById(R.id.buttonStart);
    buttonAggiorna.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {

        String[] from = { "name", "purpose" };
        int[] to = { android.R.id.text1, android.R.id.text2 };      
 adapter = new SimpleAdapter(MainActivity.this,     list,android.R.layout.simple_list_item_2, from, to);       

  progressDialog = ProgressDialog.show(MainActivity.this, "Getting data", "Loading...");
            taskBack t=new taskBack();
             t.execute();               
        }

    });// fine onClickListner


    Button buttonAllarm = (Button) findViewById(R.id.buttonAllarm);
    buttonAllarm.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {            
                AppLog.logString("list size:"+list.size()); 

        }
});


}

 private class taskBack 
 extends    AsyncTask<Void, Void, ArrayList<Map<String, String>>> {

    @Override
    protected ArrayList<Map<String, String>> doInBackground(Void... arg0) {
    ArrayList<Map<String, String>> l = new ArrayList<Map<String, String>>();
    l = startEla();
    return l;
    }

    protected void onPostExecute(ArrayList<Map<String, String>> result) {
        AppLog.logString("Parte onPostExecute");
        list=result;
        setListAdapter(adapter);    
        progressDialog.dismiss();

    }

    private ArrayList<Map<String, String>> startEla() {
    ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
        list.add(putData("android","mobile"));
        list.add(putData("Windows7", "Windows7"));
        list.add(putData("iPhone", "iPhone"));
        return list;

    }

    private Map<String, String> putData(String name, String purpose) {
        HashMap<String, String> item = new HashMap<String, String>();
        item.put("name", name);
        item.put("purpose", purpose);
        return item;

    }
}
}

在此链接中,您可以看到xml文件enter link description here

最好的注册  甲

3 个答案:

答案 0 :(得分:2)

将这两行移动到ListActivity ...

的主体
String[] from = { "name", "purpose" };
int[] to = { android.R.id.text1, android.R.id.text2 };      

onClick(...) ...

中的onCreate(...)侦听器中删除以下行
adapter = new SimpleAdapter(MainActivity.this, list, android.R.layout.simple_list_item_2, from, to);

...并将其放在onPostExecute(...)的{​​{1}}方法中,如下所示......

AsyncTask

答案 1 :(得分:1)

您的代码存在一些问题。首先,您将SimpleAdapter与Async任务结合使用。通常情况下,如果您要完成执行异步任务的工作,您可能会在初始化后将数据添加到列表中...如果您是那么你将不得不切换到ArrayAdapter。我已经调整了你的代码以适应它。

您还需要将XML中的ListView ID设置为android:id =“@ android:id / list”

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.message.BasicNameValuePair;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TwoLineListItem;

public class MainActivity extends ListActivity {
public ArrayList<BasicNameValuePair> list= new ArrayList<BasicNameValuePair>();
public ArrayAdapter<BasicNameValuePair> adapter;
public ProgressDialog progressDialog; 
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //You should init your Adapter during onCreate or onStart, not on the onClick 
    String[] from = { "name", "purpose" };
    int[] to = { android.R.id.text1, android.R.id.text2 };   
    adapter = new ArrayAdapter<BasicNameValuePair>(this,android.R.layout.simple_list_item_2, list){       
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        TwoLineListItem row;
        if(convertView == null){
            LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = (TwoLineListItem)inflater.inflate(android.R.layout.simple_list_item_2, null);
        }else{
            row = (TwoLineListItem)convertView;
        }
        BasicNameValuePair data = list.get(position);
        row.getText1().setText(data.getName());
        row.getText2().setText(data.getValue());

        return row;
        }
    };
    setListAdapter(adapter);
    Button buttonAggiorna = (Button) findViewById(R.id.buttonStart);
    buttonAggiorna.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {

            taskBack t=new taskBack();
             t.execute();               
        }

    });// fine onClickListner


    Button buttonAllarm = (Button) findViewById(R.id.buttonAllarm);
    buttonAllarm.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {            
        }
});


}

 private class taskBack extends    AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... arg0) {

       // Commented out the below since you initlize the array list in startEla
        //ArrayList<Map<String, String>> l = new ArrayList<Map<String, String>>();
       startEla();
       return (Void)null;
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
        //Moved the progress dialog show to the onPreExecute
         progressDialog = ProgressDialog.show(MainActivity.this, "Getting data", "Loading...");
    }

    @Override
    protected void onPostExecute(Void result) {
        //AppLog.logString("Parte onPostExecute");
        //On dynamic adapters (Array adapters mainly) you need to notify them once the data set has changed
        MainActivity.this.adapter.notifyDataSetChanged();
        progressDialog.dismiss();

    }

    private void startEla() {
        list.add(new BasicNameValuePair("android", "mobile"));
        list.add(new BasicNameValuePair("Windows7", "Windows7"));
        list.add(new BasicNameValuePair("iPhone", "iPhone"));
    }

}

答案 2 :(得分:1)

检查一下: http://www.dailygeek.de/using-asynctask-to-update-a-listactivity/

不要忘记在onPostExecute()

中调用adapter.notifyDataSetChanged()