2

I'm a new Android developer and I have a question. After users login, I need to get some data from an external URL and display them on one of my activities. But I've been reading and found this:

When your activity comes back to the foreground from the stopped state, it receives a call to onRestart(). The system also calls the onStart() method, which happens every time your activity becomes visible (whether being restarted or created for the first time).

And this

Caution: Your activity will be destroyed and recreated each time the user rotates the screen. When the screen changes orientation, the system destroys and recreates the foreground activity because the screen configuration has changed and your activity might need to load alternative resources (such as the layout).

Here and here.

So, it looks like I should not get the data I need on the onCreate method. Then where? In a previous activity and saving the data in the phone memory? That doesn't sound good to me.

Thanks in advance.


edit

I'm using AsyncTask as suggested, but everytime I switch the phone orientation, onCreate method is called.

My MainActivity:

public class MainActivity extends Activity implements AsyncResponse {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ReadJSONTask jsonTask = new ReadJSONTask();
        jsonTask.delegate = this;
        jsonTask.execute("http://www.myweb.com/myscript.php");
    }

    @Override
    public void processFinish(String output) {
        Toast.makeText(getApplicationContext(), output, Toast.LENGTH_LONG).show();
    }
}

ReadJSONTask class:

public class ReadJSONTask extends AsyncTask<String, Void, String> {
    public AsyncResponse delegate = null;
    public String res;
    public Boolean finish = false;

    @Override
    protected String doInBackground(String... url) {
        String response = null;
        String adres = url[0];

        URL url_HTTPRequest = null;
        try {
            url_HTTPRequest = new URL(adres);
            response = transfer(url_HTTPRequest);

        } catch (MalformedURLException e) {
            Log.e("URL ERROR", "MalformedURLException");
        } catch (Exception e) {
            Log.e("URL ERROR", "exc");
        }

        return response;
    }

    @Override
    protected void onPostExecute(String result) {
        Log.d("mylog", "result= " + result);
        delegate.processFinish(result);
    }

    public String transfer(URL url) throws IOException {

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        // inputStream = url.openStream();
        InputStream inputStream = urlConnection.getInputStream();
        BufferedReader bin = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        String line = bin.readLine();
        StringBuffer sb = new StringBuffer();
        while (line != null) {
            sb.append(line);
            sb.append("\r\n");
            line = bin.readLine();
        }
        inputStream.close();
        return sb.toString();
    }
}

And the interface is just:

public interface AsyncResponse {
    void processFinish(String output);
}

As I said, everytime I switch the phone orientation all the async process is performed (and the Toast shows up). That's exactly what I wanted to avoid in the first place.

DandyCC
  • 353
  • 1
  • 6
  • 20

3 Answers3

2

you dont need Stop/Resume activities you can use AsyncTask class and doInBackGround method when get data from external url and show to user process Dialog for waiting

2

Never ever try to get the data from URL on Main thread. Always use AsyncTask for getting the data from URL

HassanUsman
  • 1,787
  • 1
  • 20
  • 38
  • Thank you guys. I'll do some research about AsyncTask. – DandyCC Aug 09 '15 at 11:34
  • I just edited, AsyncTask doesn't answer my original question. Please check it out. – DandyCC Aug 09 '15 at 21:05
  • No need to implement the AsyncResponse follow this example http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ – HassanUsman Aug 10 '15 at 01:53
  • Great tutorial. Thanks. I followed the tutorial but still happens the same problem with the orientation of the phone. Every time I switch the orientation all data are loaded again. – DandyCC Aug 10 '15 at 12:26
1

You can write in the same activity, but not in the main thread. Maybe AsyncTask will help.