Skip to content Skip to sidebar Skip to footer

How To Return A Value From Thread In Java?

In android i am creating thread for url connection.Inside the thread i store the response message in a string which is globally declared.When I access the method method it returns

Solution 1:

It you really want to use Thread only, try this

publicclassRate_fetch {
    Stringtotal="";
    booleanb=true;

    public String rate(String dt) {
        StringBuildersb=newStringBuilder();
        newThread(newRunnable() {

            publicvoidrun() {

                try {

                    URLurl=newURL(tally_ipaddr + "/prorate.jsp?plist="
                            + sss.toString().trim());

                    HttpURLConnectionurlConnection= (HttpURLConnection) url
                            .openConnection();
                    InputStreamin=newBufferedInputStream(urlConnection
                            .getInputStream());
                    BufferedReaderr=newBufferedReader(
                            newInputStreamReader(in));
                    StringBuildersb=newStringBuilder();
                    String s;
                    while (true) {
                        s = r.readLine();
                        if (s == null || s.length() == 0)
                            break;
                        sb.append(s);
                    }
                    b = true;
                } catch (Exception e) {
                    b = true;
                }
            }

        }).start();
        while (b) {

        }
        total = sb.toString();
        return sb.toString();

    }
}

Solution 2:

You are getting the value of result as null because the method rate is running a thread so the return is not waiting to finish the thread.

You can use one of the following technique to resolve the issue

  • Handlers
  • Async. Task

Also you can look at the link for the reference.

http://mobileorchard.com/android-app-developmentthreading-part-1-handlers/

Solution 3:

You are missing the whole point of using a thread, because we use them to do expensive or potentially long operation in a separate thread in order to not block the UI thread. Therefore, you can not start a thread and expect to get the result instantly, as Premsuraj, it returns before the thread has finished.

As others suggested, a cleaner way to do this would be to use an AsyncTask, it encapsulates the process in three main stages: OnPreExecute, doInBackground and onPostExecute, they names are self-explanatory, the first do any initialization you might need, the second actually do the async work and the third is used to deal with the result of the entire operation.

Here's one quick example, of course it can be improved but should help you to understand it:

Rate_fetch

Your same class but without threading:

publicclassRate_fetch {

       public String rate(String dt)
       {
            String total="";
            try  {

                URLurl=newURL(tally_ipaddr+"/prorate.jsp?plist="+sss.toString().trim());

                HttpURLConnectionurlConnection= (HttpURLConnection) url.openConnection();
                InputStreamin=newBufferedInputStream(urlConnection.getInputStream());
                BufferedReaderr=newBufferedReader(newInputStreamReader(in));
                Stringx="";
                Stringtotal="";
                x = r.readLine();
                int i=0;

                while(x.length()>1)
                {
                    total=total+x.toString().trim();
                    i++;
                    x = r.readLine();
                }
            }
            catch(Exception e){
                return e.toString();
            };

            return total;
        }

    }

An example activity:

publicclassYourActivityextendsActivity {

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.layout);

        GetRate asyncRate = newGetRate();
        asyncRate.execute(); // starting the task, can be done wherever you need, for example a Button click event
    }

    privateclassGetRateextendsAsyncTask<Void, Integer, String> {

        @OverrideprotectedStringdoInBackground(Void... params) {

            Rate_fetch fetch = newRate_fetch();
            string rate = fetch.rate();

            return rate;
        }

        @OverrideprotectedvoidonPostExecute(String rate) {                     
            // Do whatever you need with the string, you can update your UI from here
        }
    }

}

Hope it helps.

Solution 4:

possibly you can pass reference of main/current thread/class to the thread. and thread will store its result in that referenced object.

Below is a simple example.

classCallerTest{
 private ResultData result; // any data that you want from threadpublicvoidcaller() throws Exception{
   ThreadClass thread = newThreadClass(this);
   thread.start();

   //wait for thread to finish
   thread.join();

   //now you have data in >> this.result
 }

 publicvoidsetResult(ResultData rd){
   this.result = rd; 
 }
}

classThreadClass extends Thread{
    CallerTest cl;
    publicThreadClass(CallerTest cl){
       this.cl = cl;
    }
    publicvoidrun(){
     ResultData rd;
     rd = //do code to retrive result
     cl.setResult(rd);
    }

}

Solution 5:

Just declare a class variable and passe the object in your thread

Post a Comment for "How To Return A Value From Thread In Java?"