保存我的recyclerviews和cardviews的状态

时间:2018-09-30 09:33:34

标签: android android-recyclerview recycler-adapter

我要保存recyclerview的状态(当用户按下fab按钮时,它的内部动态包含卡片视图)

a)用户关闭应用,然后重新打开 和 b)当用户从活动转到主屏幕时,然后返回活动

我想要这样,以便将卡视图和用户输入到微调器中的值保存在这些实例上。

我该如何实现?意向?共享首选项?

create.java 这是具有cardviews n种内容的活动。我的mainactivity代码是主屏幕上有3个按钮的地方,其中一个进入该create.java屏幕

public class create extends AppCompatActivity {



    //a list to store all the products
    List<Product> productList;

    //the recyclerview
    RecyclerView recyclerView;


    Product mProduct;
    private Map<String, String> numberItemValues = new HashMap<>();
    private Map<Integer, Integer> mSpinnerSelectedItem = new HashMap<Integer, Integer>();


   // RelativeLayout relativeLayout;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create);
        findViewById(R.id.relativeLayout).requestFocus();



        findViewById(R.id.relativeLayout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager imm = (InputMethodManager) view.getContext()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        });


        //opens csv
        InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
         CSVFile csvFile = new CSVFile(inputStream);

       final List<String>  mSpinnerItems = csvFile.read();


        //getting the recyclerview from xml
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        //initializing the productlist
        productList = new ArrayList<>();
        productList.add(new Product(mSpinnerItems, "Test Edit Text",false, "Text String 2"));




        final ProductAdapter  adapter = new ProductAdapter(this, productList, numberItemValues);


        //TODO FAB BUTTON
        FloatingActionButton floatingActionButton =
             findViewById(R.id.fab);


        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                productList.add(mProduct);
                if(adapter != null)
                    adapter.notifyDataSetChanged();


                //Handle the empty adapter here

            }
        });









        //setting adapter to recyclerview
        recyclerView.setAdapter(adapter);









    }



    private class CSVFile {
        InputStream inputStream;

        public CSVFile(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        public List<String> read() {
            List<String> resultList = new ArrayList<String>();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            try {
                String line;
                while ((line = reader.readLine()) != null) {
                    String[] row = line.split(",");
                    //TODO I edited this part so that you'd add the values in our new hash map variable

                    numberItemValues.put(row[1], row[0]);

                    resultList.add(row[1]);
                }
            } catch (IOException e) {
                Log.e("Main", e.getMessage());
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    Log.e("Main", e.getMessage());
                }
            }
            return resultList;
        }
    }



}

ProductAdapter

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {

    private Map<Integer, Integer> mSpinnerSelectedItem = new HashMap<Integer, Integer>();

    private Map<String, String> numberItemValues = new HashMap<>();





   // private SearchableSpinner spinner;

    //we are storing all the products in a list
    private List<Product> productList;

    private Activity create;


    //TODO CODE FOR CSV FILE


    /*InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
    CSVFile csvFile = new CSVFile(inputStream);
    final List<String>  mSpinnerItems = csvFile.read();*/


    InputStream inputStream = null;
    List<String>  mSpinnerItems = null;
    CSVFile csvFile = null;


    //TODO END OF CODE FOR CSV FILE

    public ProductAdapter(Activity activity) {
        create = activity;

    }


    //getting the context and product list with constructor
    /*public ProductAdapter(Activity activity, List<Product> productList) {
        // this.mCtx = mCtx;

       *//* inputStream = create.getResources().openRawResource(R.raw.shopitems);
        csvFile = new CSVFile(inputStream);
        mSpinnerItems = csvFile.read();*//*

        create = activity;
        this.productList = productList;
    }*/


    public ProductAdapter(Activity activity, List<Product> productList, Map<String, String> numberList) {
        numberItemValues = numberList;
        create = activity;
        this.productList = productList;
    }

    @Override
    public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //inflating and returning our view holder
        LayoutInflater inflater = LayoutInflater.from(create);
        View view = inflater.inflate(R.layout.layout_products, null);
        return new ProductViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ProductViewHolder holder, final int position) {


        // //getting the product of the specified position




        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(create, R.layout.item_spinner_layout,
                Product.getSpinnerItemsList());
        spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        holder.spinner.setAdapter(spinnerArrayAdapter);

        holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int mPosition, long id) {
                mSpinnerSelectedItem.put(position, mPosition);


                TextView mTextView = view.findViewById(R.id.mSpinnerText);


                //TODO CODE FOR GETTING AISLE NUMBER AND PUTTING IT IN THE TEXTVIEW
                /*String currentItem = mSpinnerItems.get(position);
                String aisleNumber = numberItemValues.get(currentItem);
                holder.textView5.setText(aisleNumber);

*/




                //String currentItem = holder.spinner.getSelectedItem().toString();
                String currentItem = holder.spinner.getItemAtPosition(mPosition).toString();

                Set<String> set = numberItemValues.keySet(); for(String key : set) {String value = numberItemValues.get(key); Log.e("DATA ", "key = " + key + " value = " + value); }





                //String currentItem = holder.spinner.getItemAtPosition(mPosition).toString();
                String aisleNumber = numberItemValues.get(currentItem);
                holder.textView5.setText(aisleNumber);

                Log.e("SELECTION TEST", " Selected map item = " + aisleNumber );


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        //binding the data with the viewholder views
        if (mSpinnerSelectedItem.containsKey(position)) {
            holder.spinner.setSelection(mSpinnerSelectedItem.get(position));
        }


        holder.getView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(create);


                // set title
                alertDialogBuilder.setTitle("Delete Item");

                // set dialog message
                alertDialogBuilder
                        .setMessage("Are you sure you want to delete this item?")
                        .setCancelable(false)
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // if this button is clicked, close
                                // current activity


                                holder.checkBox.setChecked(false);
                                holder.spinner.setSelection(0);



                                productList.remove(holder.getAdapterPosition());
                                notifyItemRemoved(holder.getAdapterPosition());

                                Toast.makeText(create, "Item removed.", Toast.LENGTH_LONG).show();


                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // if this button is clicked, just close
                                // the dialog box and do nothing
                                dialog.cancel();
                            }
                        });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();

            }
        });





    }


    @Override
    public int getItemCount() {
        return productList.size();
    }


    class ProductViewHolder extends RecyclerView.ViewHolder {

        SearchableSpinner spinner;
        EditText editText;
        TextView textView5;
        CheckBox checkBox;
        LinearLayout linearLayout;
        View rootView;


        public ProductViewHolder(View itemView) {
            super(itemView);

            spinner = itemView.findViewById(R.id.spinner);
            editText = itemView.findViewById(R.id.editText);
            textView5 = itemView.findViewById(R.id.textView5);
            checkBox = itemView.findViewById(R.id.checkBox);
            rootView = itemView.findViewById(R.id.linearLayout);


            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    // makes the set disappear when checkbox is ticked.
                    if(isChecked){

                        checkBox.setChecked(false);
                        spinner.setSelection(0);

                        productList.remove(getAdapterPosition());
                        notifyItemRemoved(getAdapterPosition());



                        Toast.makeText(create, "Done!", Toast.LENGTH_LONG).show();
                    }

                }
            });



        }

        public View getView() {
            return rootView;
        }

    }

    //TODO CODE FOR CSV FILE
    private class CSVFile {
        InputStream inputStream;

        public CSVFile(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        public List<String> read() {
            List<String> resultList = new ArrayList<String>();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            try {
                String line;
                while ((line = reader.readLine()) != null) {
                    String[] row = line.split(",");

                    numberItemValues.put(row[1], row[0]);

                    resultList.add(row[1]);
                }
            } catch (IOException e) {
                Log.e("Main", e.getMessage());
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    Log.e("Main", e.getMessage());
                }
            }
            return resultList;
        }
    }


}

Product.Java

public class Product {

    private static String editText;
    private static Boolean checkBox;
    private static String textView5;

    public static List<String> spinnerItemsList = new ArrayList<String>();

    public Product(List spinner, String editText, Boolean checkBox, String textView5) {

        this.editText = editText;
        this.spinnerItemsList = spinner;
        this.checkBox = checkBox;
        this.textView5 = textView5;
    }
    public static String getEdittext () {
        return editText;
    }

    public static boolean getCheckbox () {
        return checkBox;
    }

    public static String getTextview () {
        return textView5;
    }
    public static List<String> getSpinnerItemsList () {
        return spinnerItemsList;
    }
}

Spinner的MyListAdapter代码

public class MyListAdapter extends ArrayAdapter<String> {
    int groupid;
    List<String> items;
    Context context;
    String path;





    public MyListAdapter(Context context, int vg, int id, List<String> items) {
        super(context, vg, id, items);
        this.context = context;
        groupid = vg;
        this.items = items;

    }

    static class ViewHolder {
        public TextView textid;
        public TextView textname;

    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        {

            View rowView = convertView;
            if (rowView == null) {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                rowView = inflater.inflate(groupid, parent, false);
                ViewHolder viewHolder = new ViewHolder();
                viewHolder.textid = (TextView) rowView.findViewById(R.id.txtid);
                viewHolder.textname = (TextView) rowView.findViewById(R.id.txtname);
                rowView.setTag(viewHolder);
            }
            // Fill data in the drop down.
            ViewHolder holder = (ViewHolder) rowView.getTag();
            String row = items.get(position);
            //holder.textid.setText(row[0]); //prints aisle number, dont need

            holder.textname.setText(row);



            return rowView;
        }

    }

}

2 个答案:

答案 0 :(得分:2)

您应该将数据保存在sharedPreferencesdatabase中,并且每次打开活动时,都要从存储的列表中读取数据。

要存储在数据库中,您将需要一个这样的数据库帮助程序类

public class DataBase_CITY extends SQLiteOpenHelper {
// The Android's default system path of your application database.
private static String DB_PATH = "";
public static String TABLE;
private static String DB_NAME;
private static String[] FIELD_NAMES;
private static String[] FIELD_TYPES;

private SQLiteDatabase myDataBase;

private final Context myContext;

/**
 * Constructor Takes and keeps a reference of the passed context in order to
 * access to the application assets and resources.
 *
 * @param context
 */
public DataBase_CITY(Context context, String dataBaseName, String tableName, 
   String[] fieldNames, String[] fieldTypes) {

    super(context, dataBaseName, null, 1);
    DB_NAME = dataBaseName;
    TABLE = tableName;
    FIELD_NAMES = fieldNames;
    FIELD_TYPES = fieldTypes;

    this.myContext = context;

    System.err.println(context.getApplicationInfo().dataDir);

    DB_PATH = context.getApplicationInfo().dataDir + File.separator
            + "databases" + File.separator;

    System.out.println(DB_PATH);
}

/**
 * Creates a empty database on the system and rewrites it with your own
 * database.
 */
public void createDataBase() throws IOException {

    boolean dbExist = checkDataBase();

    if (dbExist) {
        // do nothing - database already exist
        // Toast.makeText(myContext, "already exist",
        // Toast.LENGTH_LONG).show();
    } else {

        // By calling this method and empty database will be created into
        // the default system path
        // of your application so we are gonna be able to overwrite that
        // database with our database.
        this.getReadableDatabase();

        try {

            copyDataBase();

        } catch (IOException e) {

            // throw new Error("Error copying database");

        }
    }

}

/**
 * Check if the database already exist to avoid re-copying the file each
 * time you open the application.
 *
 * @return true if it exists, false if it doesn't
 */
private boolean checkDataBase() {

    SQLiteDatabase checkDB = null;

    try {
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        // Toast.makeText(myContext, "already exist",
        // Toast.LENGTH_LONG).show();
    } catch (SQLiteException e) {

        // database does't exist yet.
        // Toast.makeText(myContext, "not already exist",
        // Toast.LENGTH_LONG).show();
    }

    if (checkDB != null) {

        checkDB.close();

    }

    return checkDB != null ? true : false;
}

/**
 * Copies your database from your local assets-folder to the just created
 * empty database in the system folder, from where it can be accessed and
 * handled. This is done by transfering bytestream.
 */
private void copyDataBase() throws IOException {

    // Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    // Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    // transfer bytes from the Input file to the output file
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }

    // Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

}

public void openDataBase() throws SQLException {

    // Open the database
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null,
            SQLiteDatabase.OPEN_READONLY);

}

@Override
public synchronized void close() {

    if (myDataBase != null)
        myDataBase.close();

    super.close();

}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("Create table " + TABLE + " (UserID INTEGER PRIMARY KEY AUTOINCREMENT, "
            + FIELD_NAMES[0] + " " + FIELD_TYPES[0] + ", "
            + FIELD_NAMES[1] + " " + FIELD_TYPES[1] + ", "
            + FIELD_NAMES[2] + " " + FIELD_TYPES[2] + ")");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE);
    onCreate(db);
}

public void updateDB(String[] arguments) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(FIELD_NAMES[0], Integer.parseInt(arguments[0]));
    values.put(FIELD_NAMES[1], arguments[1]);
    values.put(FIELD_NAMES[2], Integer.parseInt(arguments[2]));

    db.insert(TABLE, null, values);
    db.close();
    }

}

要在其中存储数据,您需要使用以下方法

private static void updateCityTable(String TableName, int id, String name, int 
province_id) {
    DataBase_CITY helper = new DataBase_CITY(G.CONTEXT,
            "CITY_DATABASE", TableName, G.CityTableFields, G.CityTableFieldTypes);
    try {
        helper.updateDB(new String[]{
                String.valueOf(id),
                name,
                String.valueOf(province_id)});

    } catch (Exception e) {
        e.printStackTrace();
    }

}

您可以像这样从数据库中读取

private String cityDataBaseChecker(String TableName, String column, String columnName, String amount) {
    DataBase_PROVINCE helper = new DataBase_PROVINCE(G.CONTEXT,
            "CITY_DATABASE", TableName, G.CityTableFields, G.CityTableFieldTypes);
    try {
        helper.createDataBase();
    } catch (IOException ioe) {
        throw new Error("Unable to create database");
    }

    SQLiteDatabase sqld = helper.getWritableDatabase();

    Cursor cursor = sqld.rawQuery("select * from " + TableName + " where " + columnName + "=\"" + amount + "\" order by " + column, null);
    String title = null;
    if (cursor.moveToFirst()) {
        do {
            title = cursor.getString(cursor.getColumnIndex(column));
            System.out.println("city =" + title);
        } while (cursor.moveToNext());
    }
    sqld.close();
    return title;
}

您可以定义字段名称和类型

public static String[] CityTableFields = new String[]{"id", "name", "province_id"};
public static String[] CityTableFieldTypes = new String[]{"INT", "TEXT", "INT"};

答案 1 :(得分:0)

我不会深入,但是基本上您需要保持状态。 https://developer.android.com/guide/topics/data/data-storage

您有很多选择,当然,并非所有选择都很棒。 根据您的上下文和需求选择所需的内容。阅读!

在选择了如何存储回收者内容的当前状态(即存储当前填充的数据)之后,您可以继续查找活动生命周期的正确位置以存储该内容。数据。

对我来说,最好的地方是 onStart(如果保存则恢复数据)<-> onStop(如果需要保存则保存数据)。 https://developer.android.com/guide/components/activities/activity-lifecycle

此外,您可能需要当前的索引位置以及许多可能会出现在应用程序和特殊情况中的详细信息,因此您需要对此进行研究并找到最佳的方法自己 >。编写代码并进行实验,这就是您学习的方式。

总结一下:

1st。找到一种根据需要有效存储数据的方法,研究如何在Android中有效保存数据。

第二。当用户点击手机并随机执行操作时,找到合适的位置保存您的数据。我的意思是,完全了解活动的生命周期,然后您将知道该做什么和在哪里做。

3rd。最后,当您从存储中取出数据时,填充它,然后滚动到用户最后一次访问的索引。 How to programmatically scroll to the bottom of a Recycler View?(当然,这意味着您必须在此之前存储它,找到一种获取当前索引的方法,以此类推,研究和编写代码,成为一名开发人员)

这是有关此的一些信息,但是正如我所说,您需要进行研究并找到适合您的情况。

现在开始工作。