0

This is the method which I use to get values.

 @Override
    protected Void doInBackground(String... params) {
        try {

            Intent intent = getIntent();
            String dvlaNumFin = intent.getStringExtra("dvlaNumber");

            final TextView outputView = (TextView) findViewById(R.id.showOutput);
            final URL url = new URL("https://dvlasearch.appspot.com/DvlaSearch?licencePlate="+dvlaNumFin+"&apikey=");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("GET");
            connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
            connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");

            final StringBuilder output = new StringBuilder(String.valueOf(url));

           BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = "";
            StringBuilder responseOutput = new StringBuilder();
            System.out.println("output===============" + br);
            while ((line = br.readLine()) != null) {
                responseOutput.append(line);
            }
            br.close();

            HandleJSON obj = new HandleJSON("");

            obj.readAndParseJSON(responseOutput.toString());

            output.append(System.getProperty("line.separator") + "\n" + System.getProperty("line.separator") + "Make : " + obj.getMake() + "\nModel : " + obj.getModel());
            output.append("\nSix Month Rate  : " + obj.getSixMonthRate() + "\nTwelve Month Rate : " + obj.getTwelveMonthRate() + "\nDate of First Registration : " + obj.getDateofFirstRegistrationegistration());
            output.append("\nYear of Manufacture : " + obj.getYearOfManufacture() + "\nCylinder Capacity : " + obj.getCylinderCapacity() + "\nCO2 Emmissions : " + obj.getCo2Emissions());
            output.append("\nVIN number : " + obj.getVin() + "\nTransmission type : " + obj.getTransmission());

            DVLAresult.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    outputView.setText(output);
                    progress.dismiss();

                }
            });

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

I would like to use obj.getMake() and so on, the values from JSON. But do not understand how to do it, or return it. I know should be return value, or by using final.

  • 1
    Implement onPostExecute method inside your AsyncTask class :) As name suggests this gets called once your doInBackground finishes execution. From onPostExecute call the method you want to call and pass the response that you have recieved in onPostExecute as a parameter :) Thats all :) – Sandeep Bhandari Apr 04 '16 at 13:20
  • http://stackoverflow.com/questions/9458258/return-value-from-async-task-in-android – Zahan Safallwa Apr 04 '16 at 13:20
  • 2
    Possible duplicate of [AsyncTask Android example](http://stackoverflow.com/questions/9671546/asynctask-android-example) – Dmitri Timofti Apr 04 '16 at 13:22

4 Answers4

1

Nice and simple. Make your AsyncTask return a value:

public class TestClass extends AsyncTask<Void, Void, String>{

@Override
protected String doInBackground(String... params) {
//rest of code

return output.toString();
}
}

Now all you have to do is call .get() method after calling .execute()

TestClass tc = new TestClass();
tc.execute();
String output = tc.get();

Very Very Important Note

By calling .get() right after .execute() your UI thread will be blocked until the AsyncTask is done. This is counter intuitive to the purpose of AsyncTask. One of the solutions to this problem is adding a callback interface to the AsyncTask which will be called upon finishing and call the .get() method in the implementation of that interface. For an example on how to design a callback interface see here.

Community
  • 1
  • 1
SoroushA
  • 2,043
  • 1
  • 13
  • 29
0

FOG

Simply implement onPostExecute inside your AsyncTask class :)

for example :

@Override
protected void onPostExecute(String makeValue) {
    // remember this method gets called on main thread
    letsCallFogsMethod(makeValue); //call your method and pass the make value here :)
}

Thats it buddy :) Now how come this onPostExecute is getting any value??? You have to return it from doInBackground method dude :)

like

@Override
protected String doInBackground(String... params) {
     //after all bra bla simply say
     return obj.getMake();
}

Do you notice any change in your doInBackground signature buddy?? Yeah I changed from Void to String :)

By writing String you are informing that when you are done executing doInBackground you will return a string to onPostExecute :)

So if I write as it is in the answer will it work ?? Nope. Given that you have specified Void in your doInBackground your Async task signature might look something like

private class FogsAsyncTask extends AsyncTask<bla,blah,Void> {

Can you see the last Void??? :) But now you have chnaged doInBackground isn't it so update the AsyncTask signature as well :)

private class FogsAsyncTask extends AsyncTask<bla,blah,String> {

Now it should work fine :) Happy coding buddy :) Hope my answer helped you :)

Sandeep Bhandari
  • 19,999
  • 5
  • 45
  • 78
  • new GetClass(this).execute(); using this I can execute and get result, but how do I use only single values? –  Apr 04 '16 at 13:59
  • What do you mean by that?? Sorry I din get your question properly, You wanna pass more then one value to onPostExecute?? Is that what you want??? – Sandeep Bhandari Apr 04 '16 at 14:02
  • Main Idea is to get values separately, that I get not just display full bundle of data. 1) based of this values I would like send this data to database 2) I would like to use some of this data as part of url to where user will be redirected. –  Apr 04 '16 at 14:06
  • http://www.autotrader.co.uk/search/used/cars/ **MAKE** /postcode/bh153eb/radius/1500/onesearchad/used%2Cnearlynew%2Cnew/sort/default/page/1/searchcontext/default –  Apr 04 '16 at 14:07
  • If you are looking for sending more then one value at a time like send make,model all at once here is the perfect answer for you :) http://stackoverflow.com/questions/11833978/asynctask-pass-two-or-more-values-from-doinbackground-to-onpostexecute If you see the answer u'll see that instead of sending string object he has created an object of his custom class and forwarded it to OnPostExecute thats all :) – Sandeep Bhandari Apr 04 '16 at 14:08
  • Once you recieve the data in onPostExecute and you pass it to your own method you will have the full bundle of all the data now its up to ur method to use it the way it want like add the part of the data to data base or redirect the user to a link :) do whatever you want :) – Sandeep Bhandari Apr 04 '16 at 14:09
  • As a small peice of advice :) keep your Async task clean :) Async task should only be responsible for fetching the data from server :) Parsing it and making decision of what to do with that data shouldn't be the logic of AsyncTask :) Once you hand over the data from AsyncTask to your method that method should have all the logics to deal with the data :) Still have doubts ask me :) I'll help you :) I'll be riding back to home so will respond to ur quireies only after an hour :) Happy coding :) – Sandeep Bhandari Apr 04 '16 at 14:12
  • According to your example we have value w.onlinePlayers, how I can use this value in another method? –  Apr 04 '16 at 14:23
  • Once you get the object of wrapper class in your onPostExecute call your method and pass the same object as parameter of that method :) like letscallSomething(wrapper); and in letscallSomething you can access the values as wrapper.onlinePlayers bla bla bla :) Simple as such just pass the value as parameter :) – Sandeep Bhandari Apr 04 '16 at 19:36
  • Sorry to be very rude, but if it is not hard could you show with my example? I tried but it didn't work. –  Apr 04 '16 at 21:32
  • Its fine :) happenns to everyone :) What part u din get buddy ??? I am not getting your question :| did you manage to access web response inside your onPostExecute??? Did you call the method from inside onPostExecute?? What Happened, I'll help u if can make it clear what part you are actually missing out?? – Sandeep Bhandari Apr 05 '16 at 06:41
0

You can get the output on onPostExecute method just override the method and get the output on it

shubham goyal
  • 537
  • 3
  • 3
0

AsyncTask has three (main) methods, onPreExecute, doInBackground and onPostExecute. Only doInBackGround runs on a background thread, the other two run on the UI thread. (there is also onProgressUpdate but I will skip it here)

In your case, return anything you want in doInBackground method. That return value will be the input param for onPostExecute. There you can call any other (reachable) method you want. Mind that you'd be running inside the UI thread at that time.

Aitor Viana
  • 933
  • 6
  • 15