I'm new to Android development and I'm trying to create a database and inserting element in it through a function putData()
.
The app is running without any error, but it is not showing any element, just a black Activity.
I don't know what is going wrong, please Help
DBHelper class
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "food.db";
public static final String TABLE_NAME = "food_calorie";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "CALORIE";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,CALORIE INTEGER)");
putData();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public void putData(){
insertData("Apple", 168);
insertData("Mango", 194);
}
public void insertData(String name, int calorie){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues CV=new ContentValues();
CV.put(COL_2,name);
CV.put(COL_3,calorie);
db.insert(TABLE_NAME,null,CV);
db.close();
}
public String printDB(){
String dbString="";
SQLiteDatabase db=this.getWritableDatabase();
String query="SELECT * FROM " + TABLE_NAME + " WHERE 1";
Cursor c= db.rawQuery(query,null);
//Move to the first row in your result
c.moveToFirst();
while(!c.isAfterLast()){
if(c.getString(c.getColumnIndex("TABLE_NAME"))!=null){
dbString+= c.getString(c.getColumnIndex("TABLE_NAME"));
dbString += "\n";
}
}
db.close();;
return dbString;
}
}
MinActivity Class
public class MainActivity extends AppCompatActivity {
DBHelper MyDb;
TextView showDBText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showDBText=(TextView) findViewById(R.id.showDB);
MyDb = new DBHelper(this);
printDatabase();
}
// Buckys Video 54
public void printDatabase(){
//printDB is a function in DBHelper
String dbString = MyDb.printDB();
showDBText.setText(dbString);
}
}
XML file
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/showDB"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="4dp" />
</ScrollView>
Aucun commentaire:
Enregistrer un commentaire