onSaveInstanceState和onRestoreInstanceState不还原列表视图状态

时间:2019-12-18 09:41:55

标签: android android-layout

我是Android应用程序开发的新手。并尝试使用少量代码来保留listView数据,即使屏幕方向已更改。

**

  • activity_main.xml

**

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Name"
        tools:layout_editor_absoluteX="43dp"
        tools:layout_editor_absoluteY="1060=dp" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textView"
        android:ems="10"
        android:hint="Name"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/editText"
        android:text="Add Name" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/editText"
        android:layout_toRightOf="@+id/button1"
        android:text="View Names" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/button1"/>

</RelativeLayout>

**

  • MainActivity.java

**

package com.example.providerexample;

import androidx.appcompat.app.AppCompatActivity;

import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;

import java.util.ArrayList;
import java.util.List;

import static android.widget.Toast.makeText;

public class MainActivity extends AppCompatActivity {
    String tag = getClass().getSimpleName();
    TextView textView;
    EditText editText;
    Button button1;
    Button button2;
    ListView listView;
   // SQLiteDatabase db;
    DataBaseHandler dbHandler;
    List<String> newList = new ArrayList<String>();
    ArrayAdapter listAdapter;

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

        textView = (TextView) findViewById(R.id.textView);
        editText = (EditText) findViewById(R.id.editText);
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        listView = (ListView) findViewById(R.id.listView);

       // db = new SQLiteDatabase();
        dbHandler = new DataBaseHandler(this);
        button1.setOnClickListener(new View.OnClickListener(){
            //Add the name to the local database
            public void onClick(View v1) {
                //dbHandler.onCreate(db);
                Toast.makeText(getApplicationContext(), "Entering", Toast.LENGTH_LONG).show();
                Log.v(tag,"Entering Button1 onClick");
                dbHandler.addData(getApplicationContext(),editText.getText().toString());
                Toast.makeText(getApplicationContext(), "Added", Toast.LENGTH_LONG).show();
                Log.v(tag,"Exiting Button1 onClick");
            }
        });

        button2.setOnClickListener(new View.OnClickListener(){
           //View the name from the local database
            public void onClick(View v2) {
                Log.v(tag,"Entering Button2 onClick");
                //Toast.makeText(getApplicationContext(), "View Name", Toast.LENGTH_LONG).show();
                newList = dbHandler.getNameList();
                listAdapter = new ArrayAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,newList);
                listView.setAdapter(listAdapter);
                Log.v(tag,"Exiting Button2 onClick");
            }
        });
    }
    @Override
    protected void onSaveInstanceState(Bundle outState){
        super.onSaveInstanceState(outState);
        Log.v(tag,"Entering onSaveInstanceState");
        outState.putParcelable("listView.state", listView.onSaveInstanceState());
    }
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);
        Log.v(tag,"Entering onRestoreInstanceState");
        Parcelable listViewState = savedInstanceState.getParcelable("listView.state");
        listView.onRestoreInstanceState(listViewState);
    }
}

**

  • DataBaseHandler.java

**

package com.example.providerexample;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class DataBaseHandler extends SQLiteOpenHelper {
    String tag = getClass().getSimpleName();
    //DATABASE VERSION
    private static final int DATABASE_VERSION = 1;
    //DATABASE NAME
    private static final String DATABASE_NAME = "MyDB";
    //TABLE NAME
    private static final String TABLE_NAME = "Name";
    //COLUMN NAME
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "ColName";
    String NameList;

    //Constructor
    public DataBaseHandler(Context context){
        /**
         * Create a helper object to create, open, and/or manage a database.
         * This method always returns very quickly.  The database is not actually
         * created or opened until one of {@link #getWritableDatabase} or
         * {@link #getReadableDatabase} is called.
         *
         * @param context to use for locating paths to the the database
         * @param name of the database file, or null for an in-memory database
         * @param factory to use for creating cursor objects, or null for the default
         * @param version number of the database (starting at 1); if the database is older,
         *     {@link #onUpgrade} will be used to upgrade the database; if the database is
         *     newer, {@link #onDowngrade} will be used to downgrade the database
         */
         super(context,DATABASE_NAME,null,DATABASE_VERSION);
        Log.v(tag,"Exiting DataBaseHandler");
    }
    //Create Table
    @Override
    public void onCreate(SQLiteDatabase db){
        Log.v(tag,"Entering onCreate");
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
        Log.v(tag,"Exiting onCreate");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion){
        Log.v(tag,"Entering onUpgrade");
        String CONTENT = "DROP TABLE IF EXISTS" + TABLE_NAME;
        db.execSQL(CONTENT);
        onCreate(db);
        Log.v(tag,"Exiting onUpgrade");
    }

    //Insert Data
    public void addData(Context context, String name){
        Log.v(tag,"Entering addData");
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_NAME,name);
        db.insert(TABLE_NAME,null,values);
        db.close();
        Log.v(tag,"Exiting addData");
    }

    //List the data
    public List<String> getNameList(){
        String selectQuery = "SELECT *FROM " + TABLE_NAME;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery,null);
        List<String> contentList = new ArrayList<String>();
        if(cursor.moveToFirst()){
            do {
                contentList.add(cursor.getString(0));
            } while(cursor.moveToNext());
        }
        return contentList;
    }
}

当我将屏幕方向从纵向更改为水平或反之时,listView数据会丢失。请帮忙。

0 个答案:

没有答案