i got nullPointerException when trying to fetch some data from database with rawQuery.
Here's an error:
03-11 18:09:01.522: E/AndroidRuntime(2057): Uncaught handler: thread
main exiting due to uncaught exception 03-11 18:09:01.532:
E/AndroidRuntime(2057): java.lang.NullPointerException 03-11
18:09:01.532: E/AndroidRuntime(2057): at
com.math.scan.FormulaModel.setFormulaList(FormulaModel.java:27)
Look at my code:
DbHelper
package com.math.scan;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DbHelper extends SQLiteOpenHelper{
public static final String TABLE_NAME = "formulas";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_UNKNOWN = "unknown";
public static final String COLUMN_FORMULA = "formula";
public static final String COLUMN_CTG = "ctg";
private static final String DB_NAME = "formulas.db";
private static int DB_VERSION = 1;
private static final String DB_CREATE = "CREATE TABLE "+TABLE_NAME+
"("+COLUMN_ID+" integer primary key autoincrement,"
+COLUMN_UNKNOWN+" text not null,"
+COLUMN_FORMULA+" text not null,"
+COLUMN_CTG+" text not null );";
public Context mCtx;
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.mCtx = context;
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DB_CREATE);
// reading formulas
AssetManager asset = mCtx.getAssets();
try {
InputStream input = asset.open("formulas");
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
String content = new String(buffer);
Scanner scan = new Scanner(content);
String current;
String[] f = new String[2];
String[] formula = new String[2];
while(scan.hasNextLine()) {
current = scan.nextLine();
// get category
f = current.split("!!");
formula = f[1].split(" = ");
database.execSQL("INSERT INTO `formulas` VALUES (NULL, '"+formula[0]+"', '"+formula[1]+"', '"+f[0]+"');");
Log.d("DB", "INSERT INTO `formulas` VALUES (NULL, '"+formula[0]+"', '"+formula[1]+"', '"+f[0]+"');");
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DbHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
FormulaModel
package com.math.scan;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class FormulaModel {
private SQLiteDatabase database;
private DbHelper dbHelper;
public FormulaModel(Context context) {
dbHelper = new DbHelper(context);
}
public void open() throws SQLException {
dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public void setFormulaList(String ctg) {
open();
// app stops working here
Cursor cursor = database.rawQuery("SELECT unknown, formula FROM formulas WHERE ctg = '"+ctg+"'", null);
int results = cursor.getCount();
cursor.moveToFirst();
Global.FormuleResult = new String[results];
Global.FormuleTable = new String[results];
for(int i = 0; i < results; i++) {
Global.FormuleTable[i] = cursor.getString(1);
Global.FormuleResult[i] = cursor.getString(0);
}
close();
}
}
This is activity, where I call setFormulaList() method in FormulaModel class.
package com.math.scan;
import net.sourceforge.jeval.EvaluationException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ProblemActivity extends Activity {
private EditText prob;
private Button solve;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.problem);
// text field
prob = (EditText) findViewById(R.id.problem);
// confirm btn
solve = (Button) findViewById(R.id.solve);
// check if confirm button was pressed
solve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get text from the field
String problem = prob.getText().toString();
// check if expression is not empty
if(problem.length() == 0) {
// string is empty!
Toast.makeText(ProblemActivity.this, getString(R.string.empty_field), Toast.LENGTH_SHORT).show();
} else {
FormulaModel f = new FormulaModel(ProblemActivity.this);
f.setFormulaList("mech");
pears.doMagic(problem);
try {
String str = Global.eval.getVariableValue(Global.UNKNOWN);
TextView answ = (TextView) findViewById(R.id.answer);
answ.setText(getString(R.string.prob_answ) + str);
} catch (EvaluationException e) {
Toast.makeText(ProblemActivity.this, getString(R.string.prob_error), Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
I can't figure out what is wrong here.
Any ideas?
You have to set your database variable in open():
database = dbHelper.getWritableDatabase();
Related
Hi i am doing an andorid studio project, when I am adding my data the application and then trying to view the data im getting an Error saying "Error, Nothing Found". I made up a SQLite Database and hope someone can help me find the error.
package ie.wit.andrew.drivingschool;
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 = "Driver.db";
public static final String TABLE_NAME = "driver_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "DATE OF BIRTH";
public static final String COL_4 = "LOGBOOK NUMBER"; //Making up my
//database of the
//information I will
//be entering into my
//application
public static final String COL_5 = "LESSON NUMBER";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1); //when this constructor is
//called your Database has been
//created
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY
AUTOINCREMENT,NAME TEXT,DATE OF BIRTH TEXT, LOGBOOK NUMBER TEXT, LESSON
NUMBER INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String dateofbirth, String
logbooknumber, String lessonnumber) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,dateofbirth);
contentValues.put(COL_4,logbooknumber);
contentValues.put(COL_5,lessonnumber);
long result = db.insert(TABLE_NAME,null,contentValues); //This method
//returns -1
if (result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+ TABLE_NAME,null);
return res;
}
}
package ie.wit.andrew.drivingschool;
import android.database.Cursor;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class DrivingSchool extends AppCompatActivity {
DatabaseHelper myDb;
EditText editName,editDateofBirth,editLogbookNumber,editLessonNumber;
Button btnAddData;
Button btnviewAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_driving_school);
myDb = new DatabaseHelper(this);
editName = (EditText)findViewById(R.id.editText_name);
editDateofBirth = (EditText)findViewById(R.id.editText_dateofbirth);
editLogbookNumber = (EditText)findViewById(R.id.editText_logbooknumber);
editLessonNumber = (EditText)findViewById(R.id.editText_lessonNumber);
btnAddData = (Button)findViewById(R.id.button_add);
btnviewAll = (Button)findViewById(R.id.button_viewAll);
AddData();
viewAll();
}
public void AddData() {
btnAddData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted =
myDb.insertData(editName.getText().toString(),
editDateofBirth.getText().toString(),
editLogbookNumber.getText().toString(),
editLessonNumber.getText().toString());
if(isInserted = true)
Toast.makeText(DrivingSchool.this,"Data
Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(DrivingSchool.this,"Data not
Inserted", Toast.LENGTH_LONG).show();
}
}
);
}
public void viewAll() {
btnviewAll.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v){
Cursor res = myDb.getAllData();
if(res.getCount() == 0) {
//Show Message
showMessage("Error", "Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while(res.moveToNext()) {
buffer.append("ID : "+ res.getString(0)+"\n");
buffer.append("NAME : "+ res.getString(1)+"\n");
buffer.append("DATE OF BIRTH : "+
res.getString(2)+"\n");
buffer.append("LOGBOOK NUMBER : "+
res.getString(3)+"\n\n");;
}
//showdata
showMessage("Data",buffer.toString());
}
}
);
}
public void showMessage(String title,String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}
Try removing space from your column name's
you are providing wrong column name that's why your database is not creating, please check this link for complete guide for creating and using database in Android application
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
Below is my database that I have already created and it works fine, it can save the data to the database,I am really new to this android project and need guidance on how to display all data that was saved inside the listview.
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class BmiDatabase {
private data helper;
private SQLiteDatabase help;
private Context context;
public BmiDatabase(Context context){
helper = new data(context);
help = helper.getWritableDatabase();
this.context=context;
}
public long insertData(String bmi, String status, String weight){
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(data.NAME, bmi);
contentValues.put(data._STATUS, status);
contentValues.put(data.WEIGHT, weight);
long id = db.insert(data.DATABASE_TABLE, null, contentValues);
db.close();
return id;
}
public String getAllData(){
SQLiteDatabase db = helper.getWritableDatabase();
String[] columns = {data.UID, data.NAME, data._STATUS, data.WEIGHT};
Cursor cursor = db.query(data.DATABASE_TABLE, columns, null, null, null, null, null);
StringBuffer buffer = new StringBuffer();
while (cursor.moveToNext())
{
// int index1 = cursor.getColumnIndex(data.UID);
// int cid = cursor.getInt(index1);
int cid = cursor.getInt(0);
String bmi = cursor.getString(1);
String status = cursor.getString(2);
String weight = cursor.getString(3);
buffer.append(cid +" "+bmi+" kg "+status+" "+weight+ "\n");
}
return buffer.toString();
}
public static class data extends SQLiteOpenHelper{
private Context context;
private static final String DATABASE_NAME = "bmidatabase";
private static final String DATABASE_TABLE = "bmitable";
private static final int DB_VERSION = 7;
public static final String UID = "_id";
public static final String NAME = "Bmi";
public static final String _STATUS = "Status";
public static final String WEIGHT = "Weight";
private static final String DROP_TABLE= "DROP TABLE IF EXISTS "+DATABASE_TABLE;
private static final String CREATE_TABLE = "CREATE TABLE "+DATABASE_TABLE+" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT ," +
" "+NAME+" VARCHAR(255)," +
" "+_STATUS+" VARCHAR(255)," +
""+WEIGHT+" VARCHAR(255));";
public data(Context context){
super(context, DATABASE_NAME, null, DB_VERSION);
this.context=context;
}
public void getAllData(){
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(CREATE_TABLE);
Message.message(context,"Database Created");
}
catch (SQLException e){
Message.message(context, "Failed" +e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try{
Message.message(context, "DATABASE DELETED");
db.execSQL(DROP_TABLE);
onCreate(db);
}
catch(SQLException e){
Message.message(context, "SQL FAILED");
}
}
}
}
Below is the code for my mainactivity, it shows that I can display it using a toast, but I have no idea how to call the method to populate the list view with those data.
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
//private static DataHelper DataHelper;
//DataHelper helper = new DataHelper(this);
private static BmiDatabase data;
private EditText weightinputid;
private EditText heightinputid;
private Button buttonBMI, save, detail;
private TextView BMIStatus;
private TextView BMIfinal;
private double weight =0.0;
private double height =0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setupDB();
// setDB();
initializeApp();
}
private void initializeApp(){
weightinputid = (EditText) findViewById(R.id.weightid);
heightinputid = (EditText) findViewById(R.id.heightid);
buttonBMI = (Button) findViewById(R.id.buttonBMI);
BMIfinal= (TextView) findViewById(R.id.BMIfinal);
BMIStatus = (TextView) findViewById(R.id.BMIstatus);
save = (Button) findViewById(R.id.button);
detail = (Button)findViewById(R.id.button1);
data = new BmiDatabase(this);
}
public void calculateBMI (View v){
String status;
weight= Double.parseDouble(weightinputid.getText().toString());
height= Double.parseDouble(heightinputid.getText().toString());
double bmi = weight/(height/100*height/100);
String result = String.format("%.2f", bmi);
Log.d("MainActivity", result);
BMIfinal.setText(result, TextView.BufferType.NORMAL);
if(bmi < 16){
status = "Seriously Underweight";
}
else if(bmi >=16.0 && bmi < 18.0){
status = "Underweight";
}
else if(bmi >=18.0 && bmi <24.0){
status = "Normal";
}
else{
status = "Obese";
}
BMIStatus.setText(status);
}
public void save(View v){
String bmi = BMIfinal.getText().toString();
String status = BMIStatus.getText().toString();
String weight = weightinputid.getText().toString();
long id = data.insertData(weight, bmi, status);
if(id<0)
{
Message.message(this, "");
}
else
{
Message.message(this, "");
}
}
public void detail(View v){
String d = data.getAllData();
Message.message(this, d);
}
}
I would like my android app to display the contents of a text file onto a virtual table when the user clicks the "List All" button. I am using an example from the developer.android website on creating a virtual table. The programme is unable to run at the moment. Below is the code I am working with and a sample of the text file.Kindly let me know where I may have gone wrong. Many thanks.
CEMMainActivity.java
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.os.Build;
import android.provider.ContactsContract;
public class CEMMainActivity extends ActionBarActivity {
protected static final String FTS_TABLE_CREATE = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cemmain);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
}
.add(R.id.container, new PlaceholderFragment()).commit();
}
//Action once Find button is clicked
Button findequip = (Button)findViewById(R.id.findequip);
findequip.setOnClickListener(new OnClickListener() {
public void onClick(View f) {
public void onCreate(SQLiteDatabase list) {
SQLiteDatabase mDatabase = list;
mDatabase.execSQL(FTS_TABLE_CREATE);
loadEquipmentList();
}
}
});
fragment_cemmain.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="clinical.equipment.monitor.CEMMainActivity$PlaceholderFragment" >
.......
<Button
android:id="#+id/listallequip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/cleartext"
android:layout_toRightOf="#+id/equipid"
android:onClick="listallequip"
android:text="#string/listallequip" />
</RelativeLayout>
DatabaseOpenHelper.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.content.Context;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import android.util.Log;
public class DatabaseOpenHelper {
private static final String TAG = "ListAllEquipment";
//The columns to be included in table
public static final String COL_TYPE = "EQUIPMENT TYPE";
public static final String COL_ID = "ID";
public static final String COL_LOCATION = "LOCATION";
public static final String COL_STATUS = "STATUS";
public static final String COL_TIME = "TIME";
private static final String DATABASE_NAME = "EQUIPMENT LIST";
private static final String FTS_VIRTUAL_TABLE = "FTS";
private static final int DATABASE_VERSION = 1;
private final DatabaseOpenHelper mDatabaseOpenHelper;
public DatabaseOpenHelper(Context context) {
// TODO Auto-generated constructor stub
}
public void Listalldatabase (Context context) {
mDatabaseOpenHelper = new DatabaseOpenHelper(context);
private static class DatabaseOpenHelper extends SQLiteOpenHelper {
private final Context mHelperContext;
private SQLiteDatabase mDatabase;
private static final String FTS_TABLE_CREATE =
"CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE +
" USING fts3 (" +
COL_TYPE + ", " +
COL_ID + ", " + COL_LOCATION + ", " + COL_STATUS +", " + COL_TIME + ")";
DatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mHelperContext = context;
}
// populate the virtual table
private void loadEquipmentList() {
new Thread(new Runnable() {
public void run() {
try {
loadType();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
}
private void loadType() throws IOException {
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.info_sample);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, "-");
if (strings.length < 5) continue;
long list = addItem(strings[0].trim(), strings[1].trim(), strings[2].trim(), strings[3].trim(), strings[4].trim());
if (list < 0) {
Log.e(TAG, "unable to add word: " + strings[0].trim());
}
}
} finally {
reader.close();
}
public long addItem (String type; String id; String location; String status; String time) {
ContentValues initialValues = new ContentValues();
initialValues.put(COL_TYPE, type);
initialValues.put(COL_ID, id);
initialValues.put(COL_LOCATION, location);
initialValues.put(COL_STATUS, status);
initialValues.put(COL_TIME, time);
return mDatabase.insert(FTS_VIRTUAL_TABLE, null, initialValues);
}
}
}
#Override
public void onUpgrade(SQLiteDatabase list, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
list.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
onCreate(list);
}
}
}
info_sample.txt
Equipment Type Equipment ID Location Status Time
Infusion Pump 1234 2 On 12:00
Hoist 3645 1 Off 13:00
Bed 2563 3 Occupied 14:00
Change this..
setContentView(R.layout.activity_cemmain);
to
setContentView(R.layout.fragment_cemmain);
because Button is in fragment_cemmain.xml so setContentView should refer fragment_cemmain.xml
and remove
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
I was researching on how to add tables in an sqlite database for more information but I can't have a grip on how it was truly done.
I have this code:
package com.example.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class SQLiteAdapter {
public static final String MYDATABASE_NAME = "SCORING";
public static final String MYDATABASE_TABLE = "SCORING_TABLE";
public static final String MYDATABASE_TABLE1 = "Assessment";
public static final int MYDATABASE_VERSION = 3;
public static final String KEY_ID = "_id";
public static final String KEY_CONTENT1 = "Content1";
public static final String KEY_CONTENT2 = "Content2";
public static final String KEY_CONTENT3 = "Content3";
//create table SCORING (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
"create table " + MYDATABASE_TABLE + " ("
+ KEY_ID + " integer primary key autoincrement, "
+ KEY_CONTENT1 + " text not null, "
+ KEY_CONTENT2 + " text not null, "
+ KEY_CONTENT3 + "text not null);";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c){
context = c;
}
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close(){
sqLiteHelper.close();
}
public long insert(String content1, String content2, String content3){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_CONTENT1, content1);
contentValues.put(KEY_CONTENT2, content2);
contentValues.put(KEY_CONTENT3, content3);
return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
}
public int deleteAll(){
return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
}
public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, KEY_CONTENT1, KEY_CONTENT2, KEY_CONTENT3};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// If you need to add a column
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE SCORING_TABLE ADD COLUMN Content4 TEXT");
}
}
}
}
and for the second one I'm having a hard time inputting data to the second table
package com.example.database;
import com.example.database.R;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class AndroidSQLite extends Activity {
EditText inputContent2;
TextView textView1, textView2;
Button buttonAdd, buttonDeleteAll;
private SQLiteAdapter mySQLiteAdapter;
ListView listContent;
SimpleCursorAdapter cursorAdapter;
Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView1 = (TextView)findViewById(R.id.textView1);
textView2 = (TextView)findViewById(R.id.textView2);
inputContent2 = (EditText)findViewById(R.id.content2);
buttonAdd = (Button)findViewById(R.id.add);
buttonDeleteAll = (Button)findViewById(R.id.deleteall);
listContent = (ListView)findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.queueAll();
String[] from = new String[]{SQLiteAdapter.KEY_ID, SQLiteAdapter.KEY_CONTENT1, SQLiteAdapter.KEY_CONTENT2, SQLiteAdapter.KEY_CONTENT3};
int[] to = new int[]{R.id.id, R.id.text1, R.id.text2, R.id.text3};
cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
buttonAdd.setOnClickListener(buttonAddOnClickListener);
buttonDeleteAll.setOnClickListener(buttonDeleteAllOnClickListener);
}
Button.OnClickListener buttonAddOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int a=Integer.parseInt(textView1.getText().toString());
int b=a+2;
String s1 = String.valueOf(b);
textView1.setText(s1);
Toast.makeText(getApplicationContext(), "Wrong",
Toast.LENGTH_SHORT).show();
String data1 = textView1.getText().toString();
String data2 = inputContent2.getText().toString();
String data3 = textView2.getText().toString();
mySQLiteAdapter.insert(data1, data2, data3);
updateList();
}
};
Button.OnClickListener buttonDeleteAllOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mySQLiteAdapter.deleteAll();
updateList();
}
};
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mySQLiteAdapter.close();
}
private void updateList(){
cursor.requery();
}
}
I personally found using ContentProviders to be a clearer and easier to maintain way to manage multiple tables.
There is a nice article here that explains ContentProviders and other ways of dealing with android database/
http://www.vogella.com/articles/AndroidSQLite/article.html#tutorialusecp
Can somebody help me I wrote this app, but it doesn't work and I don't find the solution.
1st error:
java.lang.illegalstateexception could not read row 0 col 1 from cursor window. Make sure the cursor is initialized correctly before accessing data from it
2nd error:
android.database.sqlite.SQLite Exception: near "=": syntax error (code 1): while compiling: SELECT ZAHL1 FROM Verlauf WHERE ID =
package com.example.to_doliste2;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivityT extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_t);
datasource = new VerlaufDataSource(this);
}
private VerlaufDataSource datasource;
List<Entry> AufgabenListe = new ArrayList<Entry>();
public void VerlaufKlick(View view)
{
try
{
String zahl1;
EditText Feld1 = (EditText)findViewById(R.id.editText1);
if (Feld1.getText().toString().length() == 0)
{
return;
}
zahl1 = (Feld1.getText().toString());
Feld1.setText(String.valueOf(zahl1));
try
{
datasource.open();
datasource.createEntry(zahl1);
datasource.close();
}
catch (Exception ex)
{
Toast.makeText(this,ex.toString(),Toast.LENGTH_LONG).show();
}
AufgabenListe.clear();
try
{
datasource.open();
AufgabenListe = datasource.getAllEntries();
datasource.close();
}
catch (Exception ex)
{
Toast.makeText(this,ex.toString(),Toast.LENGTH_LONG).show();
}
ArrayAdapter<Entry> adapterVerlauf = new ArrayAdapter<Entry>(MainActivityT.this, android.R.layout.simple_list_item_1, AufgabenListe);
ListView lVerlauf = (ListView)findViewById(R.id.listView1);
lVerlauf.setAdapter(adapterVerlauf);
}
catch (Exception ex)
{
Toast.makeText(this,ex.toString(),Toast.LENGTH_LONG).show();
}
}
}
package com.example.to_doliste2;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class MySQLHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "verlaufAufgaben.db";
public static final int DATABASE_VERSION = 1;
private static final String TABLE_CREATE_VERLAUF = ""
+"create table VERLAUF ("
+" ID integer primary key, "
+" Zahl1 int) ";
public MySQLHelper(Context context)
{
super (context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database)
{
database.execSQL(TABLE_CREATE_VERLAUF);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(MySQLHelper.class.getName(),
"Upgrading database from version " + oldVersion + "to "
+ newVersion + ", which all destroy all old data");
db.execSQL("DROP TABLE IF EXISTS SCANITEM");
onCreate(db);
}
}
package com.example.to_doliste2;
public class Entry {
private int zahl1;
public int getZahl1()
{
return zahl1;
}
public void setZahl1(int zahl1)
{
this.zahl1 = zahl1;
}
#Override
public String toString()
{
return String.format("%d", zahl1);
}
}
package com.example.to_doliste2;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class VerlaufDataSource {
private SQLiteDatabase database;
private MySQLHelper dbHelper;
private String[] allColumns = {"ZAHL1"};
public VerlaufDataSource(Context context)
{
dbHelper = new MySQLHelper(context);
}
public void open() throws SQLException
{
database = dbHelper.getWritableDatabase();
}
public void close()
{
dbHelper.close();
}
public Entry createEntry(String zahl1)
{
ContentValues values = new ContentValues();
values.put("ZAHL1", zahl1);
long insertId = database.insert("Verlauf", null, values);
Cursor cursor = database.query("Verlauf", allColumns, "ID = " + insertId, null, null, null, null);
cursor.moveToFirst();
return cursorToEntry(cursor);
}
protected List<Entry> getAllEntries()
{
List<Entry> EntriesList = new ArrayList<Entry>();
EntriesList = new ArrayList<Entry>();
Cursor cursor = database.query("Verlauf", allColumns, "ID =" , null, null, null, null, null);
cursor.moveToFirst();
if(cursor.getCount() == 0) return EntriesList;
while (cursor.isAfterLast()==false)
{
Entry entry = cursorToEntry(cursor);
EntriesList.add(entry);
cursor.moveToNext();
}
cursor.close();
return EntriesList;
}
private Entry cursorToEntry(Cursor cursor)
{
Entry entry = new Entry();
entry.setZahl1(cursor.getInt(1));
return entry;
}
}
if you are retrieving all columns from database then change your query as:
Cursor cursor = database.query("Verlauf",
allColumns, null, null, null, null, null);
First, change the cursor.getInt(1) inside VerlaufDataSource.cursorToEntry(Cursor) to cursor.getInt(0), because the count starts from 0, and you have queried for only one column (allColumns == { "ZAHL1" }).
Secondly, as ρяσѕρєя K mentioned above, "ID =" is not a correct WHERE-clause in VerlaufDataSource.getAllEntries(). Change it to null if you want all the columns.