-1

In my MainActivity.java i have set some text to a TextView, how do I get the text that I had set to the TextView

My Textview -

<TextView
android:id="@+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible" />

ASyncTask -

public class fetchdata extends AsyncTask<Void, Void, Void> {
private String data = "";

@Override
protected Void doInBackground(Void... voids) {
    try {
        URL url = new URL("https://blablabla.com/hello.json");
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        data = bufferedReader.readLine();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
   MainActivity.show.setText(this.data);
}

}

MainActivity -

private static TextView show;

...... show is static

show = findViewById(R.id.show);
String data = show.getText().toString();

but data is empty instead of me getting "this is the text I want to get"

2 Answers2

1

Considering the fact that the following two lines are together,

show = findViewById(R.id.show);
String data = show.getText().toString();

I'm gonna guess that they are in the onCreate, thereby resulting in empty data.

You'll need to wait for the AsyncTask to complete and TextView to have it's value set in onPostExecute before you try to get it in the UI thread. (You could use a callback)

Chrisvin Jem
  • 3,940
  • 1
  • 8
  • 24
0
 class fetchdata extends AsyncTask<Void, Void, String> {
        private String data = "";

        @Override
        protected String doInBackground(Void... voids) {
            try {
                URL url = new URL("https://blablabla.com/hello.json");
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
               return data = bufferedReader.readLine();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String aVoid) {
            super.onPostExecute(aVoid);
            show.setText(aVoid);
        }
    }
Ehsan Aminifar
  • 515
  • 4
  • 15
  • Yeah, your answer is correct but I have updated the question, can you help me fix this –  Aug 04 '19 at 07:27