How to return value from stream in java?

In android, I create a stream for url connection. Inside the stream, I save the response message in a line declared globally. When I access a method method, it returns null.

    public class Rate_fetch {
       String total="";
          public String  rate(String dt)
       {
    new Thread(new Runnable(){ 

         public void run(){


            try  {

             URL url = new URL(tally_ipaddr+"/prorate.jsp?plist="+sss.toString().trim());

             HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
             InputStream in = new BufferedInputStream(urlConnection.getInputStream());
             BufferedReader r = new BufferedReader(new InputStreamReader(in));
             String x = "";
             String total = "";
             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();
            }   
        }    

    }).start();

    return total;



}

When I call the method, it returns null.

 Rate_fetch rf=new Rate_fetch();
      String amt= rf.rate(prodList);
+5
source share
8 answers

That you really want to use only Thread, try this

    public class Rate_fetch {
    String total = "";
    boolean b = true;

    public String rate(String dt) {
        StringBuilder sb = new StringBuilder();
        new Thread(new Runnable() {

            public void run() {

                try {

                    URL url = new URL(tally_ipaddr + "/prorate.jsp?plist="
                            + sss.toString().trim());

                    HttpURLConnection urlConnection = (HttpURLConnection) url
                            .openConnection();
                    InputStream in = new BufferedInputStream(urlConnection
                            .getInputStream());
                    BufferedReader r = new BufferedReader(
                            new InputStreamReader(in));
                    StringBuilder sb = new StringBuilder();
                    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();

    }
}
+3
source

You get the value resultas null, because the method rateworks with the stream, so it returndoes not wait for the stream to complete.

You can use one of the following methods to solve the problem.

  • Handlers
  • Asynchronous. Task

You can also see the link for the link.

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

+2

, , . , Premsuraj, .

, AsyncTask, : OnPreExecute, doInBackground onPostExecute, , , , , .

, , , :

Rate_fetch

, :

public class Rate_fetch {

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

                URL url = new URL(tally_ipaddr+"/prorate.jsp?plist="+sss.toString().trim());

                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                BufferedReader r = new BufferedReader(new InputStreamReader(in));
                String x = "";
                String total = "";
                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;
        }

    }

:

public class YourActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.layout);

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

    private class GetRate extends AsyncTask<Void, Integer, String> {

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

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

            return rate;
        }

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

}

, .

+1

0

. Rate_fetch , . AsyncTask onPostExecute.

0

, / / . .

.

class CallerTest{
 private ResultData result; // any data that you want from thread

 public void caller() throws Exception{
   ThreadClass thread = new ThreadClass(this);
   thread.start();

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

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

 public void setResult(ResultData rd){
   this.result = rd; 
 }
}

class ThreadClass extends Thread{
    CallerTest cl;
    public ThreadClass(CallerTest cl){
       this.cl = cl;
    }
    public void run() {
     ResultData rd;
     rd = //do code to retrive result
     cl.setResult(rd);
    }

}
0

All Articles