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.

有帮助吗?

解决方案

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.

其他提示

The three types used by an asynchronous task are the following:

The first, Params, the type of the parameters sent to the task upon execution. The second, Progress, the type of the progress units published during the background computation. The third, Result, the type of the result of the background computation.

If you need to pass additional data to your AsyncTask, simply create a method which receives that data in your AsyncTask and call it within the main UI. For example:

public void setMyHandler(Handler h) { myhandler = h; }

You'll be able to find more info on the AsyncTask help page, here.

You can create Constructor in your AsyncTask class and can fetch the data into it.

The parameters are the following AsyncTask <TypeOfVarArgParams , ProgressValue , ResultValue> .

TypeOfVarArgParams is passed into the doInBackground() method as input, ProgressValue is used for progress information and ResultValue must be returned from doInBackground() method and is passed to onPostExecute() as a parameter.

How ever you can find this tutorial very helpful for learning this topic. Here is the tutorial Android Background Processing with Handlers and AsyncTask and Loaders - Tutorial

You can define a class contain all your necessary data, and use that class as parameter to AsyncTask. Or if AsyncTask parameter annoying you, you can use runOnUiThread and thread:

class Login implements Runnable{
    public Login(parameters...){    
    }
    @Override
    public void run() {
            //Login
            runOnUiThread(new LoginResult(params...));
    }
}

class LoginResult implements Runnable{
    public Login(parameters...){    
    }
    @Override
    public void run() {
    }
}

....

new Thread(new Login()).start();

Quite simple way to avoid NetworkOnMainThreadException

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
        .permitAll().build();
StrictMode.setThreadPolicy(policy);

put these lines into your onCreate(Bundle savedInstanceState) method of the Activity

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top