Search code examples
androidandroid-asynctasknetworkonmainthread

AsyncTask to avoid NetworkOnMainThread


How can i send different Type Arguments to the AsyncTask.

I am developing Login System in android using J Son/php. I got NetworkOnMainThread Exception and i was suggested to implement AsyncTask in my code. I need to send URL in string and List. How can i send this to the functions?? These values are sending from other class.

public class JSONParser extends AsyncTask<String,Void,JSONObject>

I don't know whether i am correct or not. Hoping response.

here is my modification done

private String url;
private List<NameValuePair> params;
@Override
protected JSONObject doInBackground(String... args) {

    return getJsonFromURL(url,params);
}

void callJson(String url,List<NameValuePair> params){
   this.url=url;
    this.params=params;
}

I am calling AsyncTask like this way:

jsonParser=new JSONParser();
    jsonParser.setter(LoginUrl, username,password);
    try {
        jsonObject= jsonParser.execute("").get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

    return jsonObject;

Now am getting this error.

2843-2858/? E/JSON Parser﹕ Error parsing data org.json.JSONException: Value loginRegistration of type java.lang.String cannot be converted to JSONObject
    01-07 10:04:09.808    2843-2843/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
        Process: artha.ordermaking.KOT, PID: 2843
        java.lang.NullPointerException
                at 

    ex.WelcomeActivity$PlaceholderFragment.loginProcess(WelcomeActivity.java:84)
                    at ex.WelcomeActivity$PlaceholderFragment$1.onClick(WelcomeActivity.java:118)

Note that I have changed my code submitted above.


Solution

  • You should invoke your async task with execute() and not by directly calling the doInBackground() method on it in the UI thread, as evidenced by the stacktrace:

    at artha.ordermaking.KOT.library.JSONParser.doInBackground(JSONParser.java:36)
    at artha.ordermaking.KOT.library.UserFunctions.loginUser(UserFunctions.java:37)
    

    From comments:

    jsonObject=jsonParser.execute(); Its not working. I need to get JSONObject. execute() is returning AsyncTask Object.

    That would not be an async task if you waited for its completion.

    Instead, do all processing in doInBackground() and update your UI in onPostExecute() which has access to the doInBackground() result. This update can also involve calling a callback method in your UI code.

    In your updated question:

    jsonObject= jsonParser.execute("").get();
    

    get() is the wrong solution. It blocks the current thread (UI thread) until the async task completes. So you're back where you started from: preventing a network operation to block the UI thread.