0

I have a Question about AsyncTask I Use a AsyncTask for get a Json list of Names

Here my 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();
        }
    }
}

This Works great But what I did not get is what I get the result to the outside to continue to use

i have try this in onPostExecute

    getFinalResult(String.valueOf(names_entry));

and this in my Fragment

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

Then is the RESULT empty -,-

Have already looked here but found nothing which helps me. Would be glad if someone can help me with my problem.

Edit Here myFragment.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 Answers2

1

The issue is your async task is not yet completed when you try to log the RESULT.

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

The method onPostExecute of your GetNameAsync is running in your GUI thread and can access anything on your Fragment , for example text value of a label etc. So try to update your GUI (Fragment) from within your onPostExecute with the value you got for names_entry

gipsy
  • 3,859
  • 1
  • 13
  • 21
  • You can access any ui elements on your Fragment layout by calling findViewById from onPostExecute. Then you can update that gui element using the values you have in names_entry – gipsy Nov 02 '16 at 02:39
  • i will use this _names_entry_ for create a menu in onCreateOptionsMenu and for this i need this outside from the async – Jesse Lukas Nov 02 '16 at 02:44
0
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)); // Here the value has been updated and you can Call you next business depends on the results

}
}

You are printing the log can in a wrong place, which is after calling GetNames.execute(); and it is not preferrable to call the object with a name starts with Capital letter , Object should be getNames

So the call of Log.e("RESULT-ASYNC", RESULT); should be in onPostExecute when I wrote my comment.

Omar HossamEldin
  • 3,033
  • 1
  • 25
  • 51