2

当我运行应用程序时,我的应用程序将自动加载数据。我的问题是当我的屏幕垂直应用程序将从服务器加载数据时,但是当屏幕旋转水平时,它会再次加载数据。这样做时旋转屏幕应用程序将再次加载数据。你能帮帮我吗?

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;

    }
}
4

7 回答 7

3

为了在您的应用程序中处理屏幕旋转,您应该android:configChanges在活动标签内添加以下属性:

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

并在代码部分覆盖onConfigurationChanged以避免再次执行 AsyncTask 如果屏幕是否旋转,您将需要使用布尔标志:

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;
    }
}
于 2012-12-07T04:58:35.970 回答
0

您可以根据您的场景 1 执行以下操作 - 如果您不想更改应用程序的方向,即使您更改了设备的方向,那么在清单文件中设置屏幕方向

安卓:screenOrientation="人像"

或者

安卓:screenOrientation="风景"

2-如果你想用设备的方向改变你的应用程序方向,但不想在改变方向时加载数据,那么在你的活动清单文件中使用

android:configChanges="方向"

3-如果您想以特定的时间间隔加载数据,将旧的与新的进行比较并执行您的任务,您可以为此使用 Asynk 任务

于 2012-12-07T06:11:42.173 回答
0

将以下代码写入您的 Androidmanifest.xml 文件的 Activity 标记。

android:configChanges="orientation|keyboardHidden"

更改后您的活动标签如下所示。

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

有关更多信息,请参见下面的链接。

活动元素

它会解决你的问题。

于 2012-12-07T05:04:46.880 回答
0

您可以做的是尝试将数据缓存到磁盘。然后,当您启动任务时,请检查数据的年龄。如果它太旧,那么实际上调用服务器。否则,只需使用缓存的数据。

另外,我建议您使用加载器而不是 AsyncTask。它们更加可靠,并且通常会使您的应用程序更加稳定。

于 2012-12-07T04:57:07.723 回答
0
        <activity   android:name=".MainActivity"
            android:label="@string/title_activity_main" 
            android:screenOrientation="portrait">
        </activity>

将此设置为您的清单。

于 2012-12-07T04:58:30.877 回答
0

旋转屏幕确实会导致应用程序关闭并重新打开,这就是您的代码再次运行的原因。您可能需要检查自上次加载数据以来已经过了多长时间,并且只有在需要数据时才再次加载数据。

于 2012-12-07T04:59:02.303 回答
0

看这里

这将帮助您,并让您想到正确处理事情。[最佳实践]

于 2012-12-07T05:12:45.580 回答