使用从SharePreferences获取的数据填充列表

时间:2018-12-05 20:43:10

标签: android sqlite spinner

我需要您的帮助。 我想用另一个类的数据填充微调器。 当我单击按钮btn_add时,它将数据添加到我的数据库中。同时,我将“字符串质量”存储到sharedPreferences中。我要填写的列表在MainActivity类中,而按钮在AddActivity类中。

 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 ::::

 public class AddActivity extends AppCompatActivity {

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_activity);

 btn_add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try{
                    sqLiteHelper = new SQLiteHelper(AddActivity.this, "Plant.sqlite", null, 1);
                    sqLiteHelper.insertData(
                            edt_quality.getText().toString().trim(),
                            edt_name.getText().toString().trim()
                    );
                    //////////////////SharedPreferences
                    SharedPreferences pref = getApplicationContext().getSharedPreferences("TheQualities", 0);

                    SharedPreferences.Editor editor = pref.edit();

                    editor.putString("quality", edt_quality.getText().toString().trim());
                    editor.apply();

                    //reset
                    resetFields(),
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

}

在下面的课程中,我想填写我的列表。 1.问题:将数据发送到数据库后,必须在质量显示在列表中之前重新启动程序。我想在将数据发送到数据库的同时更新列表。 2.问题:以前的质量总是被新质量代替,我想填写清单并保持清单中的最老的品质。

  import java.io.IOException;
  import java.util.ArrayList;
  import java.util.List;
  ::::

  public class MainActivity extends Activity {


 Spinner spinner;

 public static SQLiteHelper sqLiteHelper;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sqLiteHelper = new SQLiteHelper(this, "item.sqlite", null, 1);

    // Get reference of widgets from XML layout
    spinner = (Spinner) findViewById(R.id.spinnerX);

    // Initializing an ArrayAdapter
    final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
            this, android.R.layout.simple_spinner_item, fillList()) {
    };                                                                                               spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(spinnerArrayAdapter);
    }
};

//RETRIEVING PREFERENCES
public String getQuality() {
SharedPreferences prefs = getSharedPreferences("TheQualities", 0);
return prefs.getString("quality", "choice");
}

public List<String> fillList() {
    List<String> list = new ArrayList<>();

    if(!list.contains(getQuality())) {
        list.add(getQuality());
    }
    return list;
}

}

NB:运行该应用程序时没有错误。 请问有人知道我该怎么做吗?

2 个答案:

答案 0 :(得分:0)

如果您的流程是从MainActivity转到AddActivity,添加质量然后返回,则Spinner不会神奇地刷新。

如果是这种情况,则需要刷新Spinner的源,然后告诉适配器数据已更改。您可以使用适配器的 notifyDatasetChanged 方法来完成后者。

对于变化的列表(旋转列表,列表视图),使用列表非常有限。 ArrayList更具适应性。

假设以上内容,那么以下是基于您的代码的有效示例。

  • 注释数据库访问代码已被注释掉。
  • 为模拟调用AddActivity,已向MainActivity添加了一个按钮。
  • 模拟退货/完成

代码

AddActivity(基本上是为了返回而添加的按钮)

public class AddActivity extends AppCompatActivity {

    EditText edt_quality;
    Button btn_add, btn_done;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_activity);
        edt_quality = this.findViewById(R.id.edt_quality);
        btn_add = this.findViewById(R.id.add_button);
        btn_done = this.findViewById(R.id.done_button);


        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    /*
                }
                    sqLiteHelper = new SQLiteHelper(AddActivity.this, "Plant.sqlite", null, 1);
                    sqLiteHelper.insertData(
                            edt_quality.getText().toString().trim(),
                            edt_name.getText().toString().trim()
                    );
                    */
                    //////////////////SharedPreferences
                    SharedPreferences pref = getApplicationContext().getSharedPreferences("TheQualities", 0);

                    SharedPreferences.Editor editor = pref.edit();

                    editor.putString("quality", edt_quality.getText().toString().trim());
                    editor.apply();

                    //reset
                    //resetFields()
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        btn_done.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }
}

MainActivity(请参阅评论)

public class MainActivity extends Activity {

    // Define class variables/objects
    Spinner spinner;
    Button btn_add;
    ArrayAdapter<String> mSpinnerArrayAdapter;
    ArrayList<String> mFillList; //<<<<<<<<<< changed from List<String>

    //public static SQLiteHelper sqLiteHelper;

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

        /**
         * Added button to initiate AddActivity
         */
        btn_add = this.findViewById(R.id.add_button);
        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(MainActivity.this,AddActivity.class);
                startActivity(i);
            }
        });
        //sqLiteHelper = new SQLiteHelper(this, "item.sqlite", null, 1);

        // Get reference of widgets from XML layout
        spinner = (Spinner) findViewById(R.id.spinnerX);
        fillList(); //<<<<<<<<<< Fill the list for the spinner (will initially be empty)
        // Initializing an ArrayAdapter
        mSpinnerArrayAdapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_spinner_item, mFillList) {
        };
        mSpinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(mSpinnerArrayAdapter);
    }

    /**
     * ADDED as this is called when activity is resumed, so rebuild the Spinner's list
     */
    @Override
    protected void onResume() {
        super.onResume();
        fillList();
    }

    public String getQuality() {
        SharedPreferences prefs = getSharedPreferences("TheQualities", 0);
        return prefs.getString("quality", "choice");
    }

    /**
     * Changed to do a little more depending upon status of the list and adapter
     */
    public void fillList() {
        // Initialise arraylist if not already initalised
        if (mFillList == null) {
            mFillList = new ArrayList<>();
        }
        // clear all elements from the arraylist
        mFillList.clear();
        // add the element (only ever 1)
        if(!mFillList.contains(getQuality())) {
            mFillList.add(getQuality());
        }
        // If the Adapter has been initialised then notify that the data has changed
        if (mSpinnerArrayAdapter != null) {
            mSpinnerArrayAdapter.notifyDataSetChanged();
        }
    }
}

结果

应用启动时(安装后第一次)

enter image description here

  • 微调中没有。

在MainActivity上单击添加按钮

enter image description here

    然后在编辑文本中输入
  • 非常好,单击 ADD ,然后单击 DONE :-

主要活动已恢复

enter image description here

  • ,您会看到非常好现在可以在微调器中选择。

  • 请注意,因为目前只有一种选择,最好从数据库中获取列表。

答案 1 :(得分:0)

根据建议,这是一个快速汇总的示例,仅使用表格。这还将根据所选类别选择项目。

请注意,为了演示起见,添加了1个初始类别(“我的第一类别”)和一个使用“我的第一类别”的项目。该项目被命名为“我的第一项”。

列出后,该项目的类别也会显示。

它不便于添加项目。但是,它确实有助于添加类别(请注意,从微调器中选择一个添加项,将不会在列表中显示任何内容,但是重新选择“我的第一类”将列出该项目)。

SQLiteHelper.java

public class SQLiteHelper extends SQLiteOpenHelper {

    public static final String DBNAME = "mydatabase";
    public static final int DBVERSION = 1;

    public static final String TABLE_ITEM = "item";
    public static final String TABLE_CATEGORY = "category";

    public static final String COLUMN_ITEM_ID = BaseColumns._ID;
    public static final String COLUMN_ITEM_NAME = "itemname";
    public static final String COLUMN_ITEM_CATEGORYREF = "category_reference";

    public static final String COLUMN_CATEGORY_ID = BaseColumns._ID;
    public static final String COLUMN_CATEGORY_NAME = "category";

    SQLiteDatabase mDB;

    public SQLiteHelper(Context context) {
        super(context, DBNAME, null, DBVERSION);
        mDB = this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String crt_item_table = "CREATE TABLE IF NOT EXISTS " + TABLE_ITEM + "(" +
                COLUMN_ITEM_ID + " INTEGER PRIMARY KEY, " +
                COLUMN_ITEM_NAME + " TEXT, " +
                COLUMN_ITEM_CATEGORYREF + " INTEGER" +
                ")";
        db.execSQL(crt_item_table);

        String crt_category_table = "CREATE TABLE IF NOT EXISTS " + TABLE_CATEGORY + "(" +
                COLUMN_CATEGORY_ID + " INTEGER PRIMARY KEY," +
                COLUMN_CATEGORY_NAME + " TEXT" +
                ")";
        db.execSQL(crt_category_table);
        mDB = db;
        // ADD AN INITIAL CATEGORY AND THEN AN ITEM USING THAT CATEGORY
        addCateory("My FIRST CATEGORY");
        addItem("My First Item",1);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }

    public long addCateory(String category) {
        ContentValues cv = new ContentValues();
        cv.put(COLUMN_CATEGORY_NAME,category);
        return mDB.insert(TABLE_CATEGORY,null,cv);
    }

    public long addItem(String name, long category_reference) {
        ContentValues cv = new ContentValues();
        cv.put(COLUMN_ITEM_NAME,name);
        cv.put(COLUMN_ITEM_CATEGORYREF,category_reference);
        return mDB.insert(TABLE_ITEM,null,cv);
    }

    public Cursor getAllCategories() {
        return mDB.query(TABLE_CATEGORY,null,null,null,null,null, COLUMN_CATEGORY_NAME + " ASC");
    }

    public Cursor getAllItemsWithCategoryName(long category_id) {
        String table = TABLE_ITEM +
                " JOIN " + TABLE_CATEGORY + " ON " + TABLE_ITEM + "." + COLUMN_ITEM_CATEGORYREF + " = " + TABLE_CATEGORY + "." + COLUMN_CATEGORY_ID;
        String[] columns = new String[]{
                TABLE_ITEM + "." + COLUMN_ITEM_ID,
                COLUMN_ITEM_NAME,
                COLUMN_CATEGORY_NAME
        };
        String whereclause;
        String[] whereargs;
        if (category_id < 1) {
            whereclause = null;
            whereargs = null;
        } else {
            whereclause = COLUMN_ITEM_CATEGORYREF + "=?";
            whereargs = new String[]{String.valueOf(category_id)};
        }
        return mDB.query(table,columns,whereclause,whereargs,null,null,COLUMN_ITEM_NAME + " ASC");
    }
}
  • 请注意, getAllItemsWithCategoryName 方法中各项的查询有效SELECT item._id, itemname, category FROM item JOIN category ON item._id = category._id WHERE category_reference = ? ORDER BY itemname ASC
    • ?将是所选的类别ID(category._id)
    • 请注意,如果所选的类别ID为0,则将省略WHERE子句。

MainActivity.java

public class MainActivity extends Activity {

    // Define class variables/objects
    Spinner mCategorySpinner;
    long mCurrentSelectedcategory = 0;
    ListView mItemList;
    Button btn_add;
    Cursor mCategories, mItems;
    SQLiteHelper mDBHlpr;

    CursorAdapter mCategorySpinnerAdapter;
    CursorAdapter mItemListViewAdapter;

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

        /**
         * Added button to initiate AddActivity
         */
        btn_add = this.findViewById(R.id.add_button);
        mCategorySpinner = (Spinner) this.findViewById(R.id.spinnerX);
        mItemList = (ListView) this.findViewById(R.id.item_listview);
        mDBHlpr = new SQLiteHelper(this);
        setupOrRefreshUI();

        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(MainActivity.this,AddActivity.class);
                startActivity(i);
            }
        });
    }

    private void setupOrRefreshUI() {

        //Category Spinner
        mCategories = mDBHlpr.getAllCategories();
        if (mCategorySpinnerAdapter == null) {
            mCategorySpinnerAdapter = new SimpleCursorAdapter(
                    this,
                    android.R.layout.simple_spinner_dropdown_item,
                    mCategories,
                    new String[]{
                            SQLiteHelper.COLUMN_CATEGORY_NAME
                    },
                    new int[]{
                            android.R.id.text1
                    },
                    0
            );
            ((SimpleCursorAdapter) mCategorySpinnerAdapter).setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            mCategorySpinner.setAdapter(mCategorySpinnerAdapter);
            mCategorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    mCurrentSelectedcategory = l;
                    setupOrRefreshUI();
                }

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

                }
            });
        } else {
            mCategorySpinnerAdapter.swapCursor(mCategories);
        }

        //Item ListView
        mItems = mDBHlpr.getAllItemsWithCategoryName(mCurrentSelectedcategory);
        if (mItemListViewAdapter == null) {
            mItemListViewAdapter = new SimpleCursorAdapter(
                    this,
                    android.R.layout.simple_list_item_2,
                    mItems,
                    new String[]{
                            SQLiteHelper.COLUMN_ITEM_NAME,
                            SQLiteHelper.COLUMN_CATEGORY_NAME
                    },
                    new int[]{
                            android.R.id.text1,
                            android.R.id.text2
                    },
                    0
            );
            mItemList.setAdapter(mItemListViewAdapter);
            mItemList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    //<<<<<<<<<<<<<<<< handle clicking an item here
                }
            });
        } else {
            mItemListViewAdapter.swapCursor(mItems);
        }
    }

    /**
     * ADDED as this is called when activity is resumed, so rebuild the Spinner's list
     */
    @Override
    protected void onResume() {
        super.onResume();
        setupOrRefreshUI();
    }
}

AddActivity.java

public class AddActivity extends AppCompatActivity {

    EditText edt_quality;
    Button btn_add, btn_done;
    SQLiteHelper mDBHlpr;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        edt_quality = this.findViewById(R.id.edt_quality);
        btn_add = this.findViewById(R.id.add_button);
        btn_done = this.findViewById(R.id.done_button);
        mDBHlpr = new SQLiteHelper(this);


        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newcategory = edt_quality.getText().toString();
                if (newcategory.length() > 0) {
                    mDBHlpr.addCateory(newcategory);
                }
            }
        });

        btn_done.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }
}

activity_main.xml

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"/>

    <Button
        android:id="@+id/add_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ADD NEW CATEGORY"/>

    <Spinner
        android:id="@+id/spinnerX"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </Spinner>

    <ListView
        android:id="@+id/item_listview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </ListView>

</LinearLayout>

activity_add.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".AddActivity">

    <EditText
        android:id="@+id/edt_quality"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/add_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SAVE CATEGORY"/>
    <Button
        android:id="@+id/done_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DONE ADDING CATEGORIES"
        />
</LinearLayout>

注意以上是一个有效的示例,仅作为示例说明如何解决众多问题。

相关问题