我是SQLite的新手,我有这个代码,它显示了textview中从数据库中检索数据的点,如果我点击按钮,它应该检索数据,添加一些整数并将其附加到数据库。但是,每当我运行应用程序时,应用程序都会崩溃。
这是我的mainActivity
import android.widget.TextView;
public class MainActivity extends Activity {
DatabaseHelper mydb;
private static TextView txt_stars;
@
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new DatabaseHelper(this);
onButtonClickListener();
txt_stars = (TextView) findViewById(R.id.txtStars);
//I already clean my code here
}
public void onButtonClickListener {
button_next = (Button) findViewById(R.id.btnNext);
button_next.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setMessage("You have earned 50 stars");
alert.setCancelable(false);
alert.setPositiveButton("next", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//retrieve data, add 50, append data and return to main with a textview of 50 stars. How do I do this?
}
});
AlertDialog alertDialog = alert.create();
alertDialog.show();
}
}
);
}
}
这是我的DatabaseHelper.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "star.db";
public static final String TABLE_NAME = "stars_table";
public static final String COL1 = "stars";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table" + TABLE_NAME + "(" + COL1 + ")");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
onCreate(db);
}
public boolean insertData(Integer stars) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL1, stars);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select stars from" + TABLE_NAME, null);
return res;
}
}
非常感谢!
答案 0 :(得分:1)
你的代码getAllData()是错误的......按照格式
更改它public ArrayList<Model> getAllData() {
cartList.clear();//your arraylist
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from stars_table", null);
if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
do {
Model item = new Model();//your object
item.status = cursor.getString(cursor.getColumnIndex("stars")); //your variable
cartList.add(item);
} while (cursor.moveToNext());
}
}
cursor.close();
db.close();
return cartList;
}