适配器在片段onCreateView中工作,但不在Asynctask onPostExecute中工作

时间:2015-05-08 14:48:03

标签: android android-fragments android-asynctask

我想使用asyncTask从api获取结果并将其放在视图中。 现在代码是这样的:

public class GradeFragment extends Fragment {

private ListView lv;
private LinearLayout llLayout;
private String[] items;
ArrayAdapter<String> adapter;
TextView text;
private FragmentActivity faActivity;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    faActivity  = (FragmentActivity)super.getActivity();
    lv=(ListView)llLayout.findViewById(R.id.list_item);
    text = (TextView) llLayout.findViewById(R.id.text);

    new ReadWeatherJSONFeedTask().execute("http://api.androidhive.info/contacts/");
    //worked here
    items = new String[] { "Item 1",
            "Item 2",
            "Item 3",
            "Item 4",
            "Item 5"
    };
    adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
    lv.setAdapter(adapter);
    return llLayout; 
}

private class ReadWeatherJSONFeedTask extends AsyncTask<String, Void, String> {
    protected String doInBackground(String... urls) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        //text.setText(urls[0]);
        try {
            response = httpclient.execute(new HttpGet(urls[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                responseString = out.toString();
                out.close();

            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                text.setText("restapi failed");

                throw new IOException(statusLine.getReasonPhrase());
            }

        }
        catch (ClientProtocolException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        try {
              //do not work here
              items = new String[] { 
                  "Item 1",
                  "Item 2",
                  "Item 3",
                  "Item 4",
                  "Item 5"
            };
            lv=(ListView)llLayout.findViewById(R.id.list_item);

            adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
            lv.setAdapter(adapter);

        } catch (Exception e) {
            e.printStackTrace();
            //Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
        }
    }
}

/*    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_grade, menu);
    return true;
}*/

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

当我在onPostExecute中注释掉适配器并将其保留在onCreateView中时,它工作正常。但是当我在onCreateViw中注释掉适配器并且在onPostExecute中找到它时,列表就不显示了。任何人都知道为什么适配器工作在onCreateView但不在onPostExecute方法?如果我想在片段中的onPostExcute中显示结果,我该怎么办?

2 个答案:

答案 0 :(得分:1)

你如何尝试一个可以在post post后调用的回调接口 这是示例代码

private class ReadWeatherJSONFeedTask extends AsyncTask<String, Void, String> {
CallBack callback;

public ReadWeatherJSONFeedTask(CallBack callback){
    this.callback = callback;
}

protected String doInBackground(String... urls) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    String responseString = null;
    //text.setText(urls[0]);
    try {
        response = httpclient.execute(new HttpGet(urls[0]));
        StatusLine statusLine = response.getStatusLine();
        if(statusLine.getStatusCode() == HttpStatus.SC_OK){
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            responseString = out.toString();
            out.close();

        } else{
            //Closes the connection.
            response.getEntity().getContent().close();
            text.setText("restapi failed");

            throw new IOException(statusLine.getReasonPhrase());
        }

    }
    catch (ClientProtocolException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    return responseString;


@Override
protected void onPostExecute(String result) {
    callback.onCallBack();
}

你的新aysnc

public interface CallBack{

public void onCallBack();}

然后最后称之为

new ReadWeatherJSONFeedTask( new CallBack(){
public void onCallBack(){
    try {
          //do not work here
          items = new String[] { 
              "Item 1",
              "Item 2",
              "Item 3",
              "Item 4",
              "Item 5"
        };
        lv=(ListView)llLayout.findViewById(R.id.list_item);

        adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
        lv.setAdapter(adapter);

    } catch (Exception e) {
        e.printStackTrace();
        //Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
    }
}

})执行(&#34; http://api.androidhive.info/contacts/&#34);

答案 1 :(得分:0)

首先,您必须使用page中的新值替换旧值,然后必须SELECT user , page FROM clicks WHERE timestamp >= NOW() - INTERVAL 10 MINUTE GROUP BY user ORDER BY id DESC 到适配器。

而不是

String[] items

你必须拥有

notifyDataSetChanged()

希望这会对你有所帮助。

BTW:你的两个地方的物品都是相同的字符串数组,你怎么知道它的工作原理?