DandyCC
DandyCC

Reputation: 361

Stop/Resume activities and onCreate in Android

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.

Upvotes: 2

Views: 512

Answers (3)

HassanUsman
HassanUsman

Reputation: 1973

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

Upvotes: 2

sajad mohammadi
sajad mohammadi

Reputation: 70

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

Upvotes: 2

Richard Lo
Richard Lo

Reputation: 9

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

Upvotes: 1

Related Questions