如何更新listview调用Asynctask来调用webservice

时间:2013-04-12 00:14:45

标签: android

我知道有这个问题,但是,我无法理解它对我有用,我认为它可能有点不同,我有一个Web服务来获取数据,我有一个listView in我的活动。我想更新这个列表视图。

我一直在尝试使用Handler,但是,它不能正常工作,不过,我很欣赏其他选项。我真的不知道,如果我应该从我的AsyncTask类直接访问列表或我如何更新。

更新: 所以,我没有在我的AsyncTask中使用嵌套类,在这种方式上可能会更容易,但我不想这样做,因为我在我的代码的更多地方使用这个类。我想知道如何访问活动并使用我的数据加载我的ListView从WS获取的内容。我想使用Handler来做这件事是个坏主意。

我的活动课程是:

public class GameOnlineListActivity extends Activity {


private static final String TAG = "GameOnlineListActivity";


// List view
private ListView lv;

// Listview Adapter
ArrayAdapter<String> adapter;

// Search EditText
EditText inputSearch;

// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;

// List with datas
String users[];

// Handler on the main (UI) thread that will receive messages from the 
// second thread and update the progress.
final Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        // Get the current value of the variable total from the message data
        // and update the progress bar.         
        users = msg.getData().getStringArray("users");
        adapter.notifyDataSetChanged();
        }

};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game_online_list);
    users = new String[0];
    callWebService();
    // Listview Data

    lv = (ListView) findViewById(R.id.list_view);
    inputSearch = (EditText) findViewById(R.id.inputSearch);



    // Adding items to listview

    adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, users);
    lv.setAdapter(adapter);

我的webservice是一个很长的代码,因为我使用同一个类来调用几个webservices,

 public class WebServiceTask extends AsyncTask<String, Integer, String> {


private static final String TAG = "WebServiceTask";

// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 3000;

// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 5000;

private int taskType;
private Context context = null;
private Activity activity = null;
private Handler handler;

private String processMessage = "Processing...";

private List<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;


public WebServiceTask(int taskType, Activity context, String processMessage, Handler h)     {

    this.taskType = taskType;
    this.activity = context;
    this.context = context;
    this.processMessage = processMessage;
    this.handler = h;

.....

private void handleResponse(String response) {
    try {


   ......

        case ConstantsTrivial.GET_USERS:

            respJSONArray = new JSONArray(response);
            listUsers = new ArrayList<Usuario>();

            for(int i=0; i<respJSONArray.length(); i++)
            {               
                JSONObject obj = respJSONArray.getJSONObject(i);                
                id = obj.getInt(ConstantsTrivial.USER_ID);
                userName = obj.getString(ConstantsTrivial.USER_NAME);
                keyId = obj.getString(ConstantsTrivial.USER_KEY_ID);
                usu = new Usuario(id, userName, keyId);

                listUsers.add(usu);

                String[] names = new String[listUsers.size()];
                int z = 0;                  
                for (Usuario u : listUsers){
                    names[z] = u.getUserName(); 
                    z++;
                }


                Message msg = handler.obtainMessage();
                Bundle b = new Bundle();
                b.putStringArray("users", names);            
                msg.setData(b);
                handler.sendMessage(msg);


            }
            Log.d(TAG,"Lista recuperada de Usuarios por webservice:" + listUsers);
            break;
        }

   } catch (Exception e) {
       Log.e(TAG, e.getLocalizedMessage(), e);
   }

 }

@Override
protected void onPostExecute(String response) {

    handleResponse(response);

    //pDlg.dismiss();

}

我有一个解决方案,但我不是很喜欢它,而且我不想这样做......它真的很乱......这段代码真的依赖于那个Activity,我正在寻找没有太多依赖的东西,因为正如我所说的,WebServicesTask是一个可以从任何地方调用的类。 :(

  case ConstantsTrivial.GET_USERS:

            respJSONArray = new JSONArray(response);
            listUsers = new ArrayList<Usuario>();
            String[] names = null;

            for(int i=0; i<respJSONArray.length(); i++)
            {               
                JSONObject obj = respJSONArray.getJSONObject(i);                
                id = obj.getInt(ConstantsTrivial.USER_ID);
                userName = obj.getString(ConstantsTrivial.USER_NAME);
                keyId = obj.getString(ConstantsTrivial.USER_KEY_ID);
                usu = new Usuario(id, userName, keyId);

                listUsers.add(usu);

                names = new String[listUsers.size()];
                int z = 0;                  
                for (Usuario u : listUsers){
                    names[z] = u.getUserName(); 
                    z++;
                }


            }
            Log.d(TAG,"Lista recuperada de Usuarios por webservice:" + listUsers);
            //NEW CODE, UPDATE!!!!
            ((GameOnlineListActivity)activity).adapter = new ArrayAdapter<String>(activity, R.layout.list_item, R.id.product_name, names);               
            ((GameOnlineListActivity)activity).lv.setAdapter(((GameOnlineListActivity)activity).adapter);
            ((GameOnlineListActivity)activity).adapter.notifyDataSetChanged();

            break;

        }

1 个答案:

答案 0 :(得分:0)

只需谷歌“android listadapter asynctask”。你会发现很多例子,例如this one,它与你的任务非常相似。