使用Listview和OnItemClick与SQLite加载数据

时间:2016-03-29 23:43:27

标签: android sqlite listview

我在使用我的CharacterSheetDBHelper填充ListView中的数据时遇到问题。我尝试过搜索几个答案,其中一个包括使用SimpleCursorAdapter,但我还是遇到了麻烦。有人能引导我走向正确的方向吗?我想点击一个列表项,然后用存储在数据库中的数据填写表格进行编辑。

我的代码如下:

LoadCharacter类

public class LoadCharacter extends AppCompatActivity {
TextView testView;
ListView charListView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.load_character);
    CharacterDBHelper db = new CharacterDBHelper(getApplicationContext());
    charListView = (ListView) findViewById(R.id.charListView);

    //get list of names from the Database helper.
    List<String> names = new ArrayList<>(db.getNames());

    //attempting to create a listAdapter
    ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, names);
    charListView.setAdapter(adapter);
    charListView.setTextFilterEnabled(true);
    charListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override

        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent passIntent = new Intent(getApplicationContext(), CreateCharacter.class);

            //Logically onItemClick would open up a game in progress rather than the character sheet screen.
            //I was going to load character data into the Create Character class as an example.
            //This is not working right now.
            //Cursor c=  (Cursor)charListView.getItemAtPosition(position);
            //passIntent.putExtra("Characters", c.getColumn);
            startActivity(passIntent);

        }
    });

}
public boolean onCreateOptionsMenu(Menu menu){
    menu.add(0,0,0, "New Character");
    return(super.onCreateOptionsMenu(menu));
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId()==0){
        Intent intent = new Intent(this, CreateCharacter.class);
        startActivity(intent);
    }

    return super.onOptionsItemSelected(item);
   }
}

我的CharacterDBHelper类:

public class CharacterDBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "char.db";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase charDB = null;

public CharacterDBHelper(Context context) {
    super(context, DB_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    //Create database
    String CREATE_CHAR_TABLE = "CREATE TABLE IF NOT EXISTS Characters(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, " +
            "brawling TEXT NOT NULL, highflying TEXT NOT NULL, technical TEXT NOT NULL, startinghealth TEXT NOT NULL," +
            "remainingpoints TEXT NOT NULL)";
    db.execSQL(CREATE_CHAR_TABLE);

}

public List<String> getNames(){
    List<String> names = new ArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();
    //Read from database and get ALL entries by name.
    Cursor cursor = db.rawQuery("SELECT * FROM Characters", null);

    if (cursor.moveToFirst()){
        do {
            //add extracted names to array.
            names.add(cursor.getString(cursor.getColumnIndex("name")));
        }while(cursor.moveToNext());
    }
    //close cursor and database.
    cursor.close();
    db.close();

    return names;
}

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

public void insertData(String name, String brawl, String flying, String tech, String health, String points){
    SQLiteDatabase charDB = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put("name", name);
    values.put("brawling", brawl);
    values.put("highflying", flying);
    values.put("technical", tech);
    values.put("startinghealth", health);
    values.put("remainingpoints", points);

    //row insert
    charDB.insert("Characters", null, values);
    charDB.close();
}
}

1 个答案:

答案 0 :(得分:0)

我相信你看起来在使用意图附加功能时遇到了问题。以下是从onItemClickListener中添加一些游标的示例: -

    intent.putExtra("Caller", THIS_ACTIVITY + "Update");
    intent.putExtra("AisleID", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_ID_INDEX));
    intent.putExtra("AISLEID", aisleadapter.getCursor().getLong(ShopperDBHelper.AISLES_COLUMN_ID_INDEX));
    intent.putExtra("AisleName", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_NAME_INDEX));
    intent.putExtra("AisleOrder", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_ORDER_INDEX));
    intent.putExtra("AisleShopRef", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_SHOP_INDEX));
    intent.putExtra("SHOPID", aisleadapter.getCursor().getLong(ShopperDBHelper.AISLES_COLUMN_SHOP_INDEX));
    startActivity(intent);

请注意! ShopperDBHelper.AISLES_COLUMN _ ?????? _ INDEX等于列光标内的偏移量。

以下是从已启动的活动中的意图中检索的示例: -

shopid = getIntent().getLongExtra("SHOPID", -1)

注意光标应设置到适当的位置。但是,您始终可以使用cursor.moveToPosition(position)

这是一个示例CursorAdapter: -

package mjt.shopper;

import android.content.Context;
import android.database.Cursor;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;

/**
 * Created by Mike092015 on 6/02/2016.
        */
class AislesCursorAdapter extends CursorAdapter {
    public AislesCursorAdapter(Context context, Cursor cursor, int flags) {
        super(context, cursor, 0);
    }
    @Override
    public View getView(int position, View convertview, ViewGroup parent) {
        View view = super.getView(position, convertview, parent);
        Context context = view.getContext();
        if (position % 2 == 0) {
            view.setBackgroundColor(ContextCompat.getColor(context, R.color.colorlistviewroweven));
        } else {
            view.setBackgroundColor(ContextCompat.getColor(context, R.color.colorlistviewrowodd));
        }
        return view;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        TextView textviewaisleid = (TextView) view.findViewById(R.id.aisle_id_entry);
        TextView textviewaislename = (TextView) view.findViewById(R.id.aisle_name_entry);
        TextView textviewaisleorder = (TextView) view.findViewById(R.id.aisle_order_entry);
        TextView textviewaisleshopref = (TextView) view.findViewById(R.id.aisle_shopref_entry);

        textviewaisleid.setText(cursor.getString(ShopperDBHelper.AISLES_COLUMN_ID_INDEX));
        textviewaislename.setText(cursor.getString(ShopperDBHelper.AISLES_COLUMN_NAME_INDEX));
        textviewaisleorder.setText(cursor.getString(ShopperDBHelper.AISLES_COLUMN_ORDER_INDEX));
        textviewaisleshopref.setText(cursor.getString(ShopperDBHelper.AISLES_COLUMN_SHOP_INDEX));
    }
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(R.layout.activity_aisle_list_entry, parent, false);
    }
}

请注意。 bindView (使用值设置Listview的行/项/条目视图)和 newView (告诉适配器使用哪种布局)。

getView 是可选的(此处用于替代行背景)