0

I'm new to Android and I was trying to communicate with my localhost using php script and accessing a simple database. I have defined a task in the doInBackground() method which takes a value from the database stored on the localhost(I don't know if that part will work). I want to set the text in the textview of an activity using the result that the doInBackground Method returns.

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

    Context context;


    BackgroundWorker(Context ctx)
    {
        context = ctx;
    }

    @Override
    protected String doInBackground(String... params) {
        String group = params[0];
        String child = params[1];
        String address = "http://10.0.2.2/conn.php";

        URL url = null;
        try {
            url = new URL(address);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("group", "UTF-8") + "=" + URLEncoder.encode(group, "UTF-8") + "&"
                    + URLEncoder.encode("child", "UTF-8") + "=" + URLEncoder.encode(child, "UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
            String result = "";
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(String s) {

        super.onPostExecute(s);
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }
}

And the Activity class:

public class viewTT extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_tt);


        Button btnNextScreen = (Button) findViewById(R.id.button);
        TextView txtName = (TextView) findViewById(R.id.textView);
        TextView txtName2 = (TextView) findViewById(R.id.textView2);

        Intent i = getIntent();
        // Receiving the Data
        String group= i.getStringExtra("group");
        String child = i.getStringExtra("child");
        txtName.setText(group+" "+child);

        BackgroundWorker backgroundWorker = new BackgroundWorker(this);
         backgroundWorker.execute(group,child);



        btnNextScreen.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View arg0)
                    {
                //Starting a new Intent
                          Intent nextScreen = new Intent(getApplicationContext(), MainActivity.class);
                            startActivity(nextScreen);
                    }
         });
    }
}

I want to set txtName2.

Yazan
  • 6,074
  • 1
  • 19
  • 33
  • After `doInBackground` called which returns results and those results are then passed to `onPostExecute` where you can set the `txtName2.setText(result);` – Abid Khan Apr 20 '17 at 13:28
  • 1
    are `BackgroundWorker` and `viewTT` physically 2 different files? – Yazan Apr 20 '17 at 13:33
  • Possible duplicate of [How to update a TextView of an activity from another class](http://stackoverflow.com/questions/10996479/how-to-update-a-textview-of-an-activity-from-another-class) – Yazan Apr 20 '17 at 13:37
  • 1
    You can use eventBus Library to solve your issue. – jagteshwar751 Apr 20 '17 at 13:38

3 Answers3

2

You can use a interface to return data to your activity

Interface

    public interface AsyncResponse {
    public void onFinish(Object output);
}

SomeAsyncTask Class

public class SomeAsyncTask extends AsyncTask<String, String, String> {
private AsyncResponse asyncResponse;

public SomeAsyncTask(AsyncResponse asyncResponse) {
    this.asyncResponse = asyncResponse;

}

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

   //Do something 
    .....
   //Finally return something

   return "returnSomeString";
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    asyncResponse.onFinish(s);
}}

In your activity where you want to set view call the SomeAsyncTask class like this

    SomeAsyncTask someAsyncTask=new SomeAsyncTask(new AsyncResponse() {
        @Override
        public void onFinish(Object output) {
            String result= (String) output;
            //Finally set your views
        }
    });
    someAsyncTask.execute();
}
0

Define an interface to take result of backgroundworker and make workers constructor to take second parameter that interface.call that interface object on post execute and put your result as parameter. than use it like:

BackgroundWorker backgroundWorker = new BackgroundWorker(this, new bgWorkerListener() {
            @Override
            public void onResult(String s) {
                txtname2.settext(s);
            }
        });
        backgroundWorker.execute(group, child);
Hakan Saglam
  • 211
  • 2
  • 7
-1

Here is your string in main Thread

protected void onPostExecute(String s) {
    // s is your string 
    super.onPostExecute(s);
}

in your BackgroundWorker class add this code...

  private String textFortxtName2;

public String getTextFortxtName2() {
    return textFortxtName2;
}

public void setTextFortxtName2(String textFortxtName2) {
    this.textFortxtName2 = textFortxtName2;
}

then add this

protected void onPostExecute(String s) {
// s is your string 
textFortxtName2 = s;
super.onPostExecute(s);

}

now you can get the text frome yor main activity,,,

...
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(group,child);
txtName2.setText(backgroundWorker.getTextFortxtName2());

that's all :) if there will be any questions or bags please coment

Ara Hakobyan
  • 1,682
  • 1
  • 10
  • 21