Takeshi
Takeshi

Reputation: 221

When rotation screen android, app auto load data

My app will auto load data when i run app.My problem is when my screen vertical app will load data from server, but when screen rotation horizontal, it load data again. Doing so when rotation screen app will load again data.Can you help me.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.nhabep); 
    new LoadData().execute();
}


 // Class load data
private class LoadData extends AsyncTask<Void, Void, Void> {
    private ProgressDialog progressDialog;
    private JSONArray jArray;
    private String result = null;
    private InputStream is = null;
    private StringBuilder sb = null;

    @Override
    protected void onPreExecute() {
        this.progressDialog = ProgressDialog.show(Nhabep.this, "",
                " Loading...");
    }

    @Override
    protected void onPostExecute(final Void unused) {
        this.progressDialog.dismiss();
        try {
            if (flag == false)
            {
                Toast.makeText(Nhabep.this, "Không có bàn nào được chọn!!", Toast.LENGTH_SHORT).show();
            }
            else
            {
                //Hiển thị thông tin các món ăn lên listview 
            listview = (ListView) findViewById(R.id.listView1);
            this.progressDialog.dismiss();
            listview.setAdapter(new DataAdapter(Nhabep.this, soban
                    .toArray(new String[soban.size()]), thoigian
                    .toArray(new String[thoigian.size()])));
            listview.setOnItemClickListener(new OnItemClickListener() {

                //xử lý khi chọn các item trên listview 
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    // TODO Auto-generated method stub
                    String soban2 = soban.get(position);
                    String cafesua2 = cafesua.get(position);
                    String cafeda2 = cafeda.get(position);
                    String cafeden2 = cafeden.get(position);
                    String duatuoi2 = duatuoi.get(position);
                    String nuocngot2 = nuocngot.get(position);
                    String cavienchien2 = cavienchien.get(position);
                    String goiga2 = goiga.get(position);
                    String bokho2 = bokho.get(position);
                    String bunbo2 = bunbo.get(position);
                    Intent i = new Intent(Nhabep.this, Show.class);
                    i.putExtra("soban", soban2);
                    i.putExtra("cafesua", cafesua2);
                    i.putExtra("cafeda", cafeda2);
                    i.putExtra("cafeden", cafeden2);
                    i.putExtra("duatuoi", duatuoi2);
                    i.putExtra("nuocngot", nuocngot2);
                    i.putExtra("cavienchien", cavienchien2);
                    i.putExtra("goiga", goiga2);
                    i.putExtra("bokho", bokho2);
                    i.putExtra("bunbo", bunbo2);
                    startActivity(i);
                }
            });
            Toast.makeText(Nhabep.this, "Thông tin bàn được tải thành công!!", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {

            Toast.makeText(getApplicationContext(), e.toString(),
                    Toast.LENGTH_LONG).show();
        }

    }

    //kết nối đến sererver và nhân thông tin trả về từ server 
    @Override
    protected Void doInBackground(Void... params) {
        try {

            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(
                    "http://longvansolution.tk/loadthongtin.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(is, "iso-8859-1"), 80);
            sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");
            String line = "0";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();

            //Kiểm tra thông tin nhận được từ server
            //nếu null sẽ clear các textview 
            //nếu có thông tin thì đọc thông tin theo Json
            if (result.toString().equalsIgnoreCase("null\n"))
            {
                flag = false;
                soban.clear();
                thoigian.clear();
                cafesua.clear();
                cafeda.clear();
                cafeden.clear();
                duatuoi.clear();
                nuocngot.clear();
                cavienchien.clear();
                goiga.clear();
                bokho.clear();
                bunbo.clear();

            } else
            {
                //Lấy thông tin theo Json
                jArray = new JSONArray(result);
                if (jArray != null && jArray.length() > 0)
                {
                    JSONObject json_data = null;
                    soban.clear();
                    thoigian.clear();
                    cafesua.clear();
                    cafeda.clear();
                    cafeden.clear();
                    duatuoi.clear();
                    nuocngot.clear();
                    cavienchien.clear();
                    goiga.clear();
                    bokho.clear();
                    bunbo.clear();
                    for (int i = 0; i < jArray.length(); i++) {
                        json_data = jArray.getJSONObject(i);
                        thoigian1 = json_data.getString("date");
                        soban1 = json_data.getString("ban");
                        cafesua1 = json_data.getString("cafesua");
                        cafeda1 = json_data.getString("cafeda");
                        cafeden1 = json_data.getString("cafeden");
                        duatuoi1 = json_data.getString("duatuoi");
                        nuocngot1 = json_data.getString("nuocngot");
                        cavienchien1 = json_data.getString("cavienchien");
                        goiga1 = json_data.getString("goiga");
                        bokho1 = json_data.getString("bokho");
                        bunbo1 = json_data.getString("bunbo");
                        thoigian.add(thoigian1);
                        soban.add(soban1);
                        cafesua.add(cafesua1);
                        cafeden.add(cafeden1);
                        cafeda.add(cafeda1);
                        duatuoi.add(duatuoi1);
                        nuocngot.add(nuocngot1);
                        cavienchien.add(cavienchien1);
                        goiga.add(goiga1);
                        bokho.add(bokho1);
                        bunbo.add(bunbo1);
                    }
                }
                flag = true;
            }
        } catch (Exception e) {
            // Log.e("log_tag", "Error in http connection" + e.toString());
            Toast.makeText(getApplicationContext(), e.toString(),
                    Toast.LENGTH_LONG).show();
        }

        return null;

    }
}

Upvotes: 2

Views: 2131

Answers (7)

Usman Kurd
Usman Kurd

Reputation: 7023

You can do the Following things as per your scenario 1- If you don`t want to change the orientation of your Application even if you change the orientation of your device then in manifest file set screen orientation

android:screenOrientation="portrait"

or

android:screenOrientation="landscape"

2- If you want to change your application orientation with the orientation of the device but don`t want to load the data on change orientation then in your manifest file in your activity use

android:configChanges="orientation"

3- If you want to load data at your specific interval compare the old with the new and perform your task you can use Asynk task for this

Upvotes: 0

Prateek
Prateek

Reputation: 4013

See here

This will help you and give you a thought to handle things properly. [Best practices]

Upvotes: 0

Dipak Keshariya
Dipak Keshariya

Reputation: 22291

Write below code into your Androidmanifest.xml file's Activity tag.

android:configChanges="orientation|keyboardHidden"

after changes your activity tag look like this.

<activity android:name=".Main_Activity"
    android:configChanges="orientation|keyboardHidden" >

And see below link for more information.

Activity Elements

it will solve your problem.

Upvotes: 0

Craig T
Craig T

Reputation: 2752

Rotating the screen actually does cause the App to close and reopen, which is why your code is running again. You may need to check to see how long it has been since you data was last loaded, and only load the data again if the data needs to be.

Upvotes: 0

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132992

For handling rotaion of screen in your application you should add the attribute android:configChanges inside the activity tag as:

<activity android:name=".Your_Activity"
    android:configChanges="orientation|keyboardHidden" >

and override onConfigurationChanged in code part as to avoid for executing AsyncTask again you will need to use an boolean flag if screen is rotate or not :

public class Your_Activity extends ListActivity {
    public static boolean onrotaion=true; 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(onrotaion){
        new LoadData().execute();
          }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
          //Change flag  here 
          onrotaion=false;
    }
}

Upvotes: 3

Nirav Tukadiya
Nirav Tukadiya

Reputation: 3417

        <activity   android:name=".MainActivity"
            android:label="@string/title_activity_main" 
            android:screenOrientation="portrait">
        </activity>

Set this to Your Manifest.

Upvotes: 0

Kurtis Nusbaum
Kurtis Nusbaum

Reputation: 30825

What you could do is try caching the data to disk. Then you when you fire off your task, check to see how old the data is. If it is too old then actually do the call to the server. Otherwise, just use the cached data.

Also, I would suggest you use loaders instead of AsyncTask. They're much more reliable and will, in general, make your app more stable.

Upvotes: 0

Related Questions