AsyncTask结果用于Fragment

时间:2016-11-02 00:37:58

标签: java android android-studio android-asynctask

我对 AsyncTask 有疑问 我使用AsyncTask获取名称的Json列表

这是我的 AsyncTask

class GetNameAsync extends AsyncTask<String, String, JSONObject> {

    JSONParser jsonParser = new JSONParser();
    private static final String API_URL = "urlhere :-)";
    private static final String TAG_NAMES = "names";
    private ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Attempting loading...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... args) {
        try {
            HashMap<String, String> params = new HashMap<>();
            params.put("access", KEY);
            params.put("lang", LANG);

            Log.e("request", "starting");
            JSONObject names_json = jsonParser.makeHttpRequest(API_URL, "GET", params);
            return names_json;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPostExecute(JSONObject names_json) {
        super.onPostExecute(names_json);
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        String names_entry = "";
        String mAktienlisteAdapter1 = "";

        try {
            names_entry = names_json.getString(TAG_NAMES);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

这个作品很棒 但我没有得到的是我得到的结果到外面继续使用

我试过了 这在 onPostExecute

    getFinalResult(String.valueOf(names_entry));

这在我的片段中

public static String RESULT = null;
public void getFinalResult(String string) {
    RESULT = string;
}

然后RESULT为空 - , -

已经看过这里但发现什么都没有帮助我。 如果有人能帮我解决问题,我会很高兴。

修改 这是我的 Fragment.class

public class ThirdFragment extends Fragment {
public static String LANG = null;
public static String KEY = null;
public static String RESULT = null;



class GetNameAsync extends AsyncTask<String, String, JSONObject> {

    JSONParser jsonParser = new JSONParser();
    private static final String API_URL = "urlhere :-)";
    private static final String TAG_NAMES = "names";
    private ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Attempting loading...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... args) {
        try {
            HashMap<String, String> params = new HashMap<>();
            params.put("access", KEY);
            params.put("lang", LANG);

            Log.e("request", "starting");
            JSONObject names_json = jsonParser.makeHttpRequest(API_URL, "GET", params);
            return names_json;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPostExecute(JSONObject names_json) {
        super.onPostExecute(names_json);
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        String names_entry = "";
        String mAktienlisteAdapter1 = "";

        try {
            names_entry = names_json.getString(TAG_NAMES);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        getFinalResult(String.valueOf(names_entry));

    }
}

public void getFinalResult(String string) {
    RESULT = string;
}
public void setLang(String string){
    LANG = string;
}

public void setKey(String string){
    API_KEY = string;
}

public ThirdFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_third, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    FloatingActionButton fab = (FloatingActionButton) getActivity().findViewById(R.id.fab);
    fab.setVisibility(View.VISIBLE);

    GetNameAsync GetNames = new GetNameAsync();
    GetNames.execute();
    Log.e("RESULT-ASYNC", RESULT);


}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    menu.clear();
    inflater.inflate(R.menu.main1, menu);
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getItemId() == 1) {
        Toast.makeText(getActivity(), "Test 1", Toast.LENGTH_LONG).show();
        return true;
    } else if (item.getItemId() == 2) {
        Toast.makeText(getActivity(), "Test 2", Toast.LENGTH_LONG).show();
        return true;
    } else {
        return super.onOptionsItemSelected(item);
    }
}
}

2 个答案:

答案 0 :(得分:1)

问题是当您尝试记录结果时,您的异步任务尚未完成。

GetNameAsync GetNames = new GetNameAsync();
GetNames.execute();
Log.e("RESULT-ASYNC", RESULT); // At this point the task may not be complete.

onPostExecute的方法GetNameAsync正在您的GUI线程中运行,可以访问Fragment上的任何内容,例如标签的文本值等。因此,请尝试更新您的GUI(片段)在你的onPostExecute中,你使用了为names_entry获得的值

答案 1 :(得分:0)

GetNames.execute();

您正在错误的位置打印日志,这是在调用getNames之后,并且不希望调用名称以大写字母开头的对象,对象应该是Log.e("RESULT-ASYNC", RESULT);

因此,当我撰写评论时,onPostExecute的来电应该在localtime(time());