如何在旋转屏幕或按下后退按钮时保存ListView的内容

时间:2015-09-21 17:38:47

标签: android listview android-listview android-arrayadapter savestate

我是java的新手,我可以使用一些帮助。在以下程序中,当我旋转屏幕时,ListView消失。当我单击返回时,然后将应用程序拉回我的两个TextView并清除我的ListView。我读了一些,并从我收集它的内容,因为活动基本上重新启动这些操作。在这些情况下,我寻找一种保存信息的好方法,但我尝试过的任何工作都没有。任何帮助将不胜感激。如果我的代码很乱,我道歉,就像我说我是初学者一样。我试图使用onSavedInstanceState()方法,但我不能让它工作。我意识到这可能是我犯的一些愚蠢的错误,但我已经在这里呆了几个小时,我无法弄清楚我做错了什么。提前谢谢。

package dev.rogueinteractive.barcodescannershoppingcartii;

import android.app.Activity;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements OnClickListener {

public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putStringArrayList("myKey", (ArrayList<String>) productReport);
}


    private static final String USER_AGENT = "Mozilla/5.0";
    private static  String GET_URL ;
    private ArrayAdapter<String> listAdapter ;
    List<String> productReport = new ArrayList<String>();

public void sendGET() throws IOException  {
        URL obj = new URL(GET_URL);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", USER_AGENT);
        int responseCode = con.getResponseCode();
        System.out.println("GET Response Code :: " + responseCode);
        if (responseCode == HttpURLConnection.HTTP_OK) { // success
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // print result
            fullResponse = response.toString();
            String[]responseArray = fullResponse.split("\"");
            String price = new String(responseArray[30]);
            price = new StringBuffer(price).insert(1, " ").toString();
            price = new StringBuffer(price).insert(2, "$").toString();
            responseArray[30] = price;
            List<String> modifiedArray = new ArrayList<String>();
            modifiedArray.add(responseArray[27]);
            modifiedArray.add("\n");
            modifiedArray.add("\n");
            modifiedArray.add(responseArray[28]);
            modifiedArray.add(responseArray[29]);
            modifiedArray.add(responseArray[30]);

            modifiedResponse = modifiedArray.toString();
            modifiedResponse= modifiedResponse.replaceAll(",", "");
            modifiedResponse = modifiedResponse.replaceAll("[\\[\\]]", "");
            productReport.add(modifiedResponse);
        } else {
            responseTXT.setText("GET request not worked");
        }
    }
    public String modifiedResponse;
    public String fullResponse;
    public String scanContent;
    private Button scanBtn;
    private TextView formatTxt, contentTxt, responseTXT;
    public ListView mainListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState != null) {
            List<String> productReport = savedInstanceState.getStringArrayList("myKey");
            if (productReport != null) {
                listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, productReport);
            }
        }
        setContentView(R.layout.activity_main);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        mainListView = (ListView) findViewById( R.id.mainListView );
        scanBtn = (Button) findViewById(R.id.scan_button);
        formatTxt = (TextView) findViewById(R.id.scan_format);
        contentTxt = (TextView) findViewById(R.id.scan_content);
        responseTXT = (TextView) findViewById(R.id.response);
        scanBtn.setOnClickListener(this);
    }

    public void onClick(View v) {
        if (v.getId() == R.id.scan_button) {
            IntentIntegrator scanIntegrator = new IntentIntegrator(this);
            scanIntegrator.initiateScan();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
        if (scanningResult.getFormatName() != null) {
            this.scanContent = scanningResult.getContents();
            String scanFormat = scanningResult.getFormatName();
            formatTxt.setText("FORMAT: " + scanFormat);
            contentTxt.setText("CONTENT: " + scanContent);
            GET_URL="http://api.walmartlabs.com/v1/search?query="+scanContent+"&format=json&apiKey=5sk5b7u25b4qawku5zsm289z";
            try {
                sendGET();
            } catch (IOException e) {
                e.printStackTrace();
            }
            listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, productReport);
            mainListView.setAdapter( listAdapter );
        } else if (scanningResult==null){
            Toast toast = Toast.makeText(getApplicationContext(),
                    "No scan data received!", Toast.LENGTH_SHORT);
            toast.show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

主要活动

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button android:id="@+id/scan_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:text="@string/scan" />
<TextView
    android:id="@+id/scan_format"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textIsSelectable="true"
    android:layout_centerHorizontal="true"
    android:layout_below="@id/scan_button" />
<TextView
    android:id="@+id/scan_content"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textIsSelectable="true"
    android:layout_centerHorizontal="true"
    android:layout_below="@id/scan_format" />

<ListView android:id="@+id/mainListView"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:layout_below="@id/scan_content"/>

<TextView
    android:id="@+id/response"
    android:maxLines = "10000"
    android:scrollbars = "vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textIsSelectable="true"
    android:layout_centerHorizontal="true"
    android:layout_below="@id/scan_content" />
</RelativeLayout>

行布局

<?xml version="1.0" encoding="utf-8"?>


<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rowTextView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>

1 个答案:

答案 0 :(得分:1)

我认为你错过了两件事。

首先,您没有设置mainListView适配器来接收您在onSaveInstanceState上保存的列表。请注意,如果savedInstanceState不为null,则您在onCreate方法上获取myList,但listView未接收您正在创建的新适配器。我建议在onCreate方法上添加:

...
//current code
scanBtn.setOnClickListener(this);
//New Code to be added
mainListView.setAdapter( listAdapter );

其次,如果savedInstanceState不为null,则您需要创建一个新的productReport列表以接收您在轮换之前保存的列表,但是您在其他位置使用listReport列表。您应该添加从此列表中保存的捆绑包中收到的所有商品,甚至可以重新创建产品列表。

//Current code    
if (savedInstanceState != null) {
            List<String> productReport = savedInstanceState.getStringArrayList("myKey");
            if (productReport != null) {
                listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, productReport);
            }
        }
//Replaced code
if (savedInstanceState != null) {
        productReport = savedInstanceState.getStringArrayList("myKey");
        if (productReport != null) {
            listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, productReport);
        }
    }

另一件事:我不认为你对你获得数据的网站返回的json 100%肯定。检索数据并试图获得类似

之类的东西并不是一个好主意
String price = response[30];

因为您可以轻松获得数组越界异常。 检查GSON库,也许你可以创建一个模型类来保存结果,比如

new Gson().fromJson(//your response string goes here, //your model class goes here)

最后,按下后​​退按钮时无法保持状态,除非您将其设置为静态或再次检索数据。