I have a problem with the following issue:
I have build an Android app which saves data into a SQL database (SQLite). I managed so the current date, time and the category is saved down and shown in a different menu. Somehow I am not able to get the value saved down and shown in the other layout. The data should come from an EditText: android:id="#+id/edit_betrag
The SQL column is defined like: public static final String BUDGET_BETRAG = "betrag";
and then should be shown in textView_betrag in the class BudgetRechnerAdapter respectively the other layout.
Can you please help me with this issue? Thanks a lot!!!
public class BudgetRechnerOpenHandler extends SQLiteOpenHelper {
private static final String TAG = BudgetRechnerOpenHandler.class
.getSimpleName();
// Name und Version der Datenbank
private static final String DATABASE_NAME = "budgetrechner.db";
private static final int DATABASE_VERSION = 1;
// Name und Attribute der Tabelle "Budget"
public static final String _ID = "_id";
public static final String TABELLE_NAME_BUDGET = "budget";
public static final String BUDGET_ZEIT = "zeitStempel";
public static final String BUDGET_AUSGABENART = "ausgabenArt";
public static final String BUDGET_BETRAG = "betrag";
// Konstanten für die Stimmungen
public static final int BUDGET_ESSEN = 1;
public static final int BUDGET_GETRAENK = 2;
public static final int BUDGET_SONSTIGES = 3;
// Tabelle Budget anlegen
private static final String TABELLE_BUDGET_ERSTELLEN = "CREATE TABLE "
+ TABELLE_NAME_BUDGET + " (" + _ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + BUDGET_ZEIT + " INTEGER, "
+ BUDGET_BETRAG + " INTEGER," + BUDGET_AUSGABENART + " INTEGER);";
// Tabelle Budget löschen
private static final String TABELLE_BUDGET_DROP = "DROP TABLE IF EXISTS "
+ TABELLE_NAME_BUDGET;
BudgetRechnerOpenHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABELLE_BUDGET_ERSTELLEN);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrade der Datenbank von Version " + oldVersion + " zu "
+ newVersion + "; alle Daten werden gelöscht");
db.execSQL(TABELLE_BUDGET_DROP);
onCreate(db);
}
public void insert(int art, String beschreibung, long zeit) {
long rowId = -1;
try {
// Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
// die zu speichernden Werte
ContentValues wert = new ContentValues();
wert.put(BUDGET_AUSGABENART, art);
wert.put(BUDGET_BETRAG, beschreibung);
wert.put(BUDGET_ZEIT, zeit);
// in die Tabelle Budget einfügen
rowId = db.insert(TABELLE_NAME_BUDGET, null, wert);
} catch (SQLiteException e) {
Log.e(TAG, "insert()", e);
} finally {
Log.d(TAG, "insert(): rowId=" + rowId);
}
}
public Cursor query() {
// ggf. Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
return db.query(TABELLE_NAME_BUDGET, null, null, null, null, null,
BUDGET_ZEIT + " DESC"
);
}
public void update(long id, int ausgabe_art_zahl) {
// ggf. Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(BUDGET_AUSGABENART, ausgabe_art_zahl);
int numUpdated = db.update(TABELLE_NAME_BUDGET, values, _ID + " = ?",
new String[] { Long.toString(id) });
Log.d(TAG, "update(): id=" + id + " -> " + numUpdated);
}
public void delete(long id) {
// ggf. Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
int numDeleted = db.delete(TABELLE_NAME_BUDGET, _ID + " = ?",
new String[] { Long.toString(id) });
Log.d(TAG, "delete(): id=" + id + " -> " + numDeleted);
}
}
public class BudgetRechnerAdapter extends CursorAdapter {
private final Date datum;
private static final DateFormat DF_DATE = SimpleDateFormat
.getDateInstance(DateFormat.MEDIUM);
private static final DateFormat DF_TIME = SimpleDateFormat
.getTimeInstance(DateFormat.MEDIUM);
private Integer betrag;
private static final Integer DF_BETRAG = R.id.edit_betrag;
private LayoutInflater inflator;
private int ciAusgabenArt, ciZeit, ciBetrag;
public BudgetRechnerAdapter(Context context, Cursor c) {
super(context, c);
datum = new Date();
betrag = null;
inflator = LayoutInflater.from(context);
ciAusgabenArt = c.getColumnIndex(BudgetRechnerOpenHandler.BUDGET_AUSGABENART);
ciZeit = c.getColumnIndex(BudgetRechnerOpenHandler.BUDGET_ZEIT);
ciBetrag = c.getColumnIndex(BudgetRechnerOpenHandler.BUDGET_BETRAG);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ImageView image = (ImageView) view.findViewById(R.id.icon);
int art = cursor.getInt(ciAusgabenArt);
TextView textView_art = (TextView) view.findViewById(R.id.text3);
if (art == BudgetRechnerOpenHandler.BUDGET_ESSEN) {
image.setImageResource(R.drawable.bild_essen);
textView_art.setText("Essen");
} else if (art == BudgetRechnerOpenHandler.BUDGET_GETRAENK) {
image.setImageResource(R.drawable.bild_getraenk);
textView_art.setText("Getränk");
} else {
image.setImageResource(R.drawable.bild_sonstiges);
textView_art.setText("Sonstiges");
}
TextView textView_Datum = (TextView) view.findViewById(R.id.text1);
TextView textView_Zeit = (TextView) view.findViewById(R.id.text2);
TextView textView_betrag = (TextView) view.findViewById(R.id.text4);
long zeitStempel = cursor.getLong(ciZeit);
datum.setTime(zeitStempel);
textView_Datum.setText(DF_DATE.format(datum));
textView_Zeit.setText(DF_TIME.format(datum));
textView_betrag.setText(DF_BETRAG.toString());
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflator.inflate(R.layout.verlauf, null);
}
}
Related
I'm using fragment to create tabs, and I'm trying to insert information from the fragment to my database.
So I've 3 RadioGroup and I'm adding to the database the 'Checked' radio button that the user has marked, and I'm not able to add into the database the data because the following error:
Attempt to invoke virtual method
'android.database.sqlite.SQLiteDatabase
android.content.Context.openOrCreateDatabase(java.lang.String, int,
android.database.sqlite.SQLiteDatabase$CursorFactory,
android.database.DatabaseErrorHandler)' on a null object reference
There are DatabaseHandler functions (which works) that I use such as
db.checkSetting() - Check if the database table is empty, if empty return false, if not return true.
db.updateSetting() - Update the data inside the table.
db.addSetting() - Create new table with new data.
public class DatabaseHandler extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "database.db";
//table name
private static final String TABLE_DETAILS = "details";
private static final String TABLE_FOOD = "food";
private static final String TABLE_OLDDETAILS = "oldDetails";
private static final String TABLE_SETTING = "setting";
//Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_HEIGHT = "height";
private static final String KEY_WEIGHT = "weight";
private static final String KEY_CALORIES = "calories";
private static final String KEY_DATE = "date";
private static final String KEY_LEVEL = "level";
private static final String KEY_DURATION = "duration";
private static final String KEY_DAYS = "days";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_DETAILS_TABLE = "CREATE TABLE " + TABLE_DETAILS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_HEIGHT + " REAL," + KEY_WEIGHT + " REAL " + ")";
String CREATE_FOOD_TABLE = "CREATE TABLE " + TABLE_FOOD + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_CALORIES + " INTEGER " + ")";
String CREATE_OLDDETAILS_TABLE = "CREATE TABLE " + TABLE_OLDDETAILS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_DATE + " TEXT," + KEY_HEIGHT + " REAL," + KEY_WEIGHT + " REAL " + ")";
String CREATE_SETTING_TABLE = "CREATE TABLE " + TABLE_SETTING + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_LEVEL + " INTEGER," + KEY_DURATION + " INTEGER," + KEY_DAYS + " INTEGER " + ")";
db.execSQL(CREATE_OLDDETAILS_TABLE);
db.execSQL(CREATE_DETAILS_TABLE);
db.execSQL(CREATE_FOOD_TABLE);
db.execSQL(CREATE_SETTING_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DETAILS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_OLDDETAILS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FOOD);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SETTING);
// Create tables again
onCreate(db);
}
public boolean addSetting(int level, int duration, int days) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, 1);
values.put(KEY_LEVEL, level);
values.put(KEY_DURATION, duration);
values.put(KEY_DAYS, days);
// Inserting Row
long result = db.insert(TABLE_SETTING, null, values);
if(result == -1){
return false;
}
else{
return true;
}
}
public boolean checkSetting(){
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_SETTING;
Cursor cursor = db.rawQuery(selectQuery, null);
Boolean rowExists;
if (cursor.moveToFirst())
{
// DO SOMETHING WITH CURSOR
rowExists = true;
} else
{
// I AM EMPTY
rowExists = false;
}
return rowExists;
}
public setting getSetting() {
String selectQuery = "SELECT * FROM " + TABLE_SETTING;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null)
cursor.moveToFirst();
setting set = new setting(cursor.getInt(1), cursor.getInt(2), cursor.getInt(3));
return set;
}
public int updateSetting(setting set) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_LEVEL, set.getLevel());
values.put(KEY_DURATION, set.getDuration());
values.put(KEY_DAYS, set.getDays());
Log.d("UPDATE: ", "updated all");
// updating row
return db.update(TABLE_SETTING, values, KEY_ID + " = ?", new String[] { String.valueOf(1) });
}
Fragment:
public class PageFragment extends Fragment {
DatabaseHandler db = new DatabaseHandler(getActivity()); //DATABASE
private int group1;
private int group2;
private int group3;
public static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_training, container, false);
ViewStub stub = (ViewStub) view.findViewById(R.id.stub);
if(mPage == 1) { // mPage represents the ID of the tab/page/fragment that in use.
stub.setLayoutResource(R.layout.fragment_trainingone); // Sets resource for each fragment
View inflated = stub.inflate();
return inflated;
}
else{
stub.setLayoutResource(R.layout.fragment_trainingtwo);
View inflated = stub.inflate();
RadioGroup rg1 = (RadioGroup) inflated.findViewById(R.id.group1);
RadioGroup rg2 = (RadioGroup) inflated.findViewById(R.id.group2);
RadioGroup rg3 = (RadioGroup) inflated.findViewById(R.id.group3);
Button update = (Button) inflated.findViewById(R.id.update);
rg1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio1:
group1 = 1;
break;
case R.id.radio2:
group1 = 2;
break;
case R.id.radio3:
group1 = 3;
break;
}
}
});
rg2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio11:
group2 = 1;
break;
case R.id.radio22:
group2 = 2;
break;
case R.id.radio33:
group2 = 3;
break;
}
}
});
rg3.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio111:
group3 = 1;
break;
case R.id.radio222:
group3 = 2;
break;
case R.id.radio333:
group3 = 3;
break;
}
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(android.view.View v) {
setting set = new setting(group1, group2, group3);
if (db.checkSetting()) {
db.updateSetting(set);
} else {
db.addSetting(group1, group2, group3);
}
}
});
return inflated;
}
}
}
How can I insert data into database within fragment and avoiding NullPointerException?
You're calling
DatabaseHandler db = new DatabaseHandler(getActivity());
before the Activity is even attached to the Fragment. Initialise it in the onCreate(), or onAttach() method, so getActivity() doesn't return null.
Attempt to invoke virtual method
'android.database.sqlite.SQLiteDatabase
android.content.Context.openOrCreateDatabase(java.lang.String, int,
android.database.sqlite.SQLiteDatabase$CursorFactory,
android.database.DatabaseErrorHandler)' on a null object reference
According to Exception You Have to open database before querying from it follow the below linked post
public void openDataBase() throws SQLException
{
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
SQLite database status on app uninstall
What is the reason for the empty ListView? Actually, I have filled the database with dates, but the ListView is empty, especially the activity is empty. The activity is empty when the ListView is create with the arrayAdapter, but the app chrashes when it is create with the the cursor Adapter.
I wrote an app which uses a ListView to list a part of my SQLite dates.
But I can't see the ListView. The app starts without an error, but the Activity is empty. I can't see my error. I hope, someone else can see the error.
<?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="fill_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
tools:context="com.example.katjarummler.hundeschule_petra_bennemann.
GruppeAuslesenActivity"
android:focusableInTouchMode="true"
android:weightSum="1">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:visibility="visible"
/>
</LinearLayout>
public class GruppeAuslesenActivity extends AppCompatActivity {
public static final String LOG_TAG =
GruppeAuslesenActivity.class.getSimpleName();
ListView mKundenListView;
private HundeschuleMemoDataSource dataSource = new
HundeschuleMemoDataSource(this);
private GoogleApiClient client;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gruppeauslesen);
initializeHundeschuleKundenListView();
HundeschuleMemoDataSource dataSource = new
HundeschuleMemoDataSource(this);
client = new
GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void initializeHundeschuleKundenListView() {
List<HundeschuleMemoKunden> listForInitialization = new
ArrayList<HundeschuleMemoKunden>();
mKundenListView = (ListView) findViewById(R.id.list);
// Erstellen des ArrayAdapters für unseren ListView
ArrayAdapter<HundeschuleMemoKunden>
hundeschuleMemoKundenArrayAdapter = new
ArrayAdapter<HundeschuleMemoKunden>(
this,
android.R.layout.simple_list_item_multiple_choice,
listForInitialization) {
// Wird immer dann aufgerufen, wenn der übergeordnete ListView
die Zeile neu zeichnen muss
#NonNull
public View getView(int position, View convertView, #NonNull
ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view;
HundeschuleMemoKunden memo = (HundeschuleMemoKunden)
mKundenListView.getItemAtPosition(position);
// Hier prüfen, ob Eintrag abgehakt ist. Falls ja, Text
durchstreichen
if (memo.isChecked()) {
textView.setPaintFlags(textView.getPaintFlags() |
Paint.STRIKE_THRU_TEXT_FLAG);
textView.setTextColor(Color.rgb(175, 175, 175));
} else {
textView.setPaintFlags(textView.getPaintFlags() &
(~Paint.STRIKE_THRU_TEXT_FLAG));
textView.setTextColor(Color.DKGRAY);
}
return view;
}
};
mKundenListView.setAdapter(hundeschuleMemoKundenArrayAdapter);
mKundenListView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
HundeschuleMemoKunden memo = (HundeschuleMemoKunden)
mKundenListView.getItemAtPosition(position);
// Hier den checked-Wert des Memo-Objekts umkehren, bspw.
von true auf false
// Dann ListView neu zeichnen mit showAllListEntries()
HundeschuleMemoKunden updatedHundeschuleMemoKunden =
dataSource.updateHundeschuleMemoKunden(memo.getId(), memo.getgName(),
memo.getkName(),
memo.getkTelefon(), memo.gethName(),
memo.getbeginn(), (!memo.isChecked()));
Log.d(LOG_TAG, "Checked-Status von Eintrag: " +
updatedHundeschuleMemoKunden.toString() + " ist: " +
updatedHundeschuleMemoKunden.isChecked());
showAllListEntries();
}
});
}
private void showAllListEntries() {
List<HundeschuleMemoKunden> hundeschuleMemoGruppenList =
dataSource.getAllGruppen();
ArrayAdapter<HundeschuleMemoKunden> adapter =
(ArrayAdapter<HundeschuleMemoKunden>) mKundenListView.getAdapter();
adapter.clear();
adapter.addAll(hundeschuleMemoGruppenList);
adapter.notifyDataSetChanged();
}
protected void onResume() {
super.onResume();
Log.d(LOG_TAG, "Die Datenquelle wird geöffnet.");
dataSource.open();
Log.d(LOG_TAG, "Folgende Einträge sind in der Datenbank
enthalten:");
showAllListEntries();
}
protected void onPause() {
super.onPause();
Log.d(LOG_TAG, "Die Datenquelle wird geschlossen.");
dataSource.close();
}
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("GruppeAuslesen Page") // TODO: Define a title for
the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
}
public class HundeschuleMemoDataSource {
private static final String LOG_TAG =
HundeschuleMemoDataSource.class.getSimpleName();
private SQLiteDatabase database;
private HundeschuleMemoDBHelper dbHelper;
private String[] columns = {
HundeschuleMemoDBHelper.COLUMN_ID,
HundeschuleMemoDBHelper.COLUMN_KName,
HundeschuleMemoDBHelper.COLUMN_GNAME,
HundeschuleMemoDBHelper.COLUMN_KTELEFON,
HundeschuleMemoDBHelper.COLUMN_HUND,
HundeschuleMemoDBHelper.COLUMN_BEGINN,
HundeschuleMemoDBHelper.COLUMN_CHECKED,
};
public HundeschuleMemoDataSource(Context context) {
Log.d(LOG_TAG, "Unsere DataSource erzeugt jetzt den dbHelper. ");
dbHelper = new HundeschuleMemoDBHelper(context, "gruppe",
TABLE_KUNDEN_LIST);
}
public void open() {
Log.d(LOG_TAG, "Eine Referenz auf die Datenbank wird jetzt
angefragt.");
database = dbHelper.getWritableDatabase();
Log.d(LOG_TAG, "Datenbankreferenz erhalten. Pfad zur Datenbank: " +
database.getPath());
}
public void close() {
dbHelper.close();
Log.d(LOG_TAG, "Datenbank mit Hilfe des DBHelpers geschlossen.");
}
public HundeschuleMemoKunden createHundeschuleMemoKunden(String kName,
String gName, String kTelefon, String hName,
String beginn)
{
ContentValues values = new ContentValues();
values.put(COLUMN_KName, kName);
values.put(COLUMN_GNAME, gName);
values.put(HundeschuleMemoDBHelper.COLUMN_KTELEFON, kTelefon);
values.put(COLUMN_HUND, hName);
values.put(HundeschuleMemoDBHelper.COLUMN_BEGINN, beginn);
long insertId = database.insert(TABLE_KUNDEN_LIST, null, values);
Cursor cursor = database.query(TABLE_KUNDEN_LIST,
columns, HundeschuleMemoDBHelper.COLUMN_ID + "=" +
insertId,
null, null, null, null);
cursor.moveToFirst();
HundeschuleMemoKunden hundeschuleMemoKunden =
cursorToHundeschuleMemoKunden(cursor);
cursor.close();
return hundeschuleMemoKunden;
}
public HundeschuleMemoKunden createHundeschuleMemoGruppen(String gName,
String kName, String hName) {
ContentValues values = new ContentValues();
values.put(COLUMN_GNAME, gName);
values.put(COLUMN_KName, kName);
values.put(COLUMN_HUND, hName);
long insertId = database.insert(TABLE_KUNDEN_LIST, null, values);
Cursor cursor = database.query(TABLE_KUNDEN_LIST,
columns, HundeschuleMemoDBHelper.COLUMN_ID + "=" +
insertId,
null, null, null, null);
cursor.moveToFirst();
HundeschuleMemoKunden hundeschuleMemoGruppen =
cursorToHundeschuleMemoKunden(cursor);
cursor.close();
return hundeschuleMemoGruppen;
}
public void deleteHundeschuleMemoKunden(HundeschuleMemoKunden
hundeschuleMemoKunden) {
long id = hundeschuleMemoKunden.getId();
database.delete(TABLE_KUNDEN_LIST,
HundeschuleMemoDBHelper.COLUMN_ID + "=" + id,
null);
Log.d(LOG_TAG, "Eintrag gelöscht! ID: " + id + " Inhalt: " +
hundeschuleMemoKunden.toString());
}
public HundeschuleMemoKunden updateHundeschuleMemoKunden(long id,
String newkName, String newgName, String newkTelefon, String newHund,
String
newBeginn, boolean newChecked) {
int intValueChecked = (newChecked) ? 1 : 0;
ContentValues values = new ContentValues();
values.put(COLUMN_KName, newkName);
values.put(COLUMN_GNAME, newgName);
values.put(HundeschuleMemoDBHelper.COLUMN_KTELEFON, newkTelefon);
values.put(COLUMN_HUND, newHund);
values.put(HundeschuleMemoDBHelper.COLUMN_BEGINN, newBeginn);
values.put(HundeschuleMemoDBHelper.COLUMN_CHECKED,
intValueChecked);
database.update(TABLE_KUNDEN_LIST,
values,
HundeschuleMemoDBHelper.COLUMN_ID + "=" + id,
null);
Cursor cursor = database.query(TABLE_KUNDEN_LIST,
columns, HundeschuleMemoDBHelper.COLUMN_ID + "=" + id,
null, null, null, null);
cursor.moveToFirst();
HundeschuleMemoKunden hundeschuleMemoKunden =
cursorToHundeschuleMemoKunden(cursor);
cursor.close();
return hundeschuleMemoKunden;
}
private HundeschuleMemoKunden cursorToHundeschuleMemoKunden(Cursor
cursor) {
int idIndex =
cursor.getColumnIndex(HundeschuleMemoDBHelper.COLUMN_ID);
int idKName = cursor.getColumnIndex(COLUMN_KName);
int idGName = cursor.getColumnIndex(COLUMN_GNAME);
int idKTelefon =
cursor.getColumnIndex(HundeschuleMemoDBHelper.COLUMN_KTELEFON);
int idHund = cursor.getColumnIndex(COLUMN_HUND);
int idBeginn =
cursor.getColumnIndex(HundeschuleMemoDBHelper.COLUMN_BEGINN);
int idChecked =
cursor.getColumnIndex(HundeschuleMemoDBHelper.COLUMN_CHECKED);
String kName = cursor.getString(idKName);
String gName = cursor.getString(idGName);
String kTelefon = cursor.getString(idKTelefon);
String Hund = cursor.getString(idHund);
String beginn = cursor.getString(idBeginn);
long id = cursor.getLong(idIndex);
int intValueChecked = cursor.getInt(idChecked);
boolean isChecked = (intValueChecked != 0);
HundeschuleMemoKunden hundeschuleMemoKunden = new
HundeschuleMemoKunden(kName, gName, kTelefon, Hund,
beginn);
return hundeschuleMemoKunden;
}
public List<HundeschuleMemoKunden> getAllHundeschuleMemos() {
List<HundeschuleMemoKunden> hundeschuleMemoKundenList = new
ArrayList<>();
Cursor cursor = database.query(TABLE_KUNDEN_LIST,
columns, null, null, null, null, null);
cursor.moveToFirst();
HundeschuleMemoKunden hundeschuleMemoKunden;
while (!cursor.isAfterLast()) {
hundeschuleMemoKunden = cursorToHundeschuleMemoKunden(cursor);
hundeschuleMemoKundenList.add(hundeschuleMemoKunden);
Log.d(LOG_TAG, "ID: " + hundeschuleMemoKunden.getId() + ",
Inhalt: " + hundeschuleMemoKunden.toString());
cursor.moveToNext();
}
cursor.close();
return hundeschuleMemoKundenList;
}
public List<HundeschuleMemoKunden> getAllGruppen() {
List<HundeschuleMemoKunden> gruppenList = new ArrayList<>();
SQLiteDatabase database = dbHelper.getWritableDatabase();
String selectQuery = "SELECT " +
HundeschuleMemoDBHelper.COLUMN_ID + " , " +
HundeschuleMemoDBHelper.COLUMN_GNAME + " , " +
HundeschuleMemoDBHelper.COLUMN_KName + " , " +
HundeschuleMemoDBHelper.COLUMN_HUND + " , " +
HundeschuleMemoDBHelper.COLUMN_CHECKED +
" FROM " + HundeschuleMemoDBHelper.TABLE_KUNDEN_LIST + "
ORDER BY 2 ASC ";
Cursor cursor = database.rawQuery(selectQuery, null);
cursor.moveToFirst();
cursor.close();
database.close();
return gruppenList;
}
}
public class HundeschuleMemoDBHelper extends SQLiteOpenHelper {
private static final String LOG_TAG =
HundeschuleMemoDBHelper.class.getSimpleName();
public static final String DB_NAME = "Kunden_list.db";
public static final int DB_VERSION = 7;
public static final String TABLE_KUNDEN_LIST = "Kunden_list";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_KName = "Name";
public static final String COLUMN_GNAME = "Gruppe";
public static final String COLUMN_KTELEFON = "Telefon";
public static final String COLUMN_HUND = "Hund";
public static final String COLUMN_BEGINN = "Beginn";
public static final String COLUMN_CHECKED = "checked";
public static final String SQL_CREATE = "CREATE TABLE " +
TABLE_KUNDEN_LIST +
"(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_KName + " TEXT NOT NULL, " +
COLUMN_GNAME + " TEXT NOT NULL, " +
COLUMN_KTELEFON + " TEXT NOT NULL, " +
COLUMN_HUND + " TEXT NOT NULL, " +
COLUMN_BEGINN + " TEXT NOT NULL, " +
COLUMN_CHECKED + " BOOLEAN NOT NULL DEFAULT 0);";
public static final String SQL_DROP = "DROP TABLE IF EXISTS " +
TABLE_KUNDEN_LIST;
public HundeschuleMemoDBHelper(Context context, String gruppe, String
sql) {
super(context, DB_NAME, null, DB_VERSION);
Log.d(LOG_TAG, "DBHelper hat die Datenbank: " + getDatabaseName() +
" erzeugt.");
}
//Die onCreate-Methode wird nur aufgerufen, falls die Datenbank noch
nicht existiert
public void onCreate(SQLiteDatabase db) {
try{
Log.d(LOG_TAG, "Die Tabelle wird mit SQL-Befehl: " + SQL_CREATE
+ " angelegt.");
db.execSQL(SQL_CREATE);
}
catch(Exception ex){
Log.e(LOG_TAG, "Fehler beim Anlegen der Tabelle: " +
ex.getMessage());
}
}
// Die onUpgrade-Methode wird aufgerufen, sobald die neue
Versionsnummer höher
// als die alte Versionsnummer ist und somit ein Upgrade notwendig wird
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
Log.d(LOG_TAG, "Die Tabelle mit Versionsnummer " + oldVersion + "
wird entfernt.");
db.execSQL(SQL_DROP);
onCreate(db);
}
}
public class HundeschuleMemoKunden {
private String kName;
private String gName;
private String kTelefon;
private String hName;
private String beginn;
private long id;
private boolean checked;
public HundeschuleMemoKunden(String kName, String gName, String
kTelefon, String hName,
String beginn){
this.id=id;
this.kName=kName;
this.gName=gName;
this.kTelefon=kTelefon;
this.hName=hName;
this.beginn=beginn;
this.checked = checked;
}
public String getkName(){
return kName;
}
public void setkName(String kName){
this.kName = kName;
}
public String getgName(){return gName;}
public void setgName(String gName){
this.gName = gName;
}
public String getkTelefon(){
return kTelefon;
}
public void setkTelefon(String kTelefon){this.kTelefon = kTelefon;}
public String gethName(){
return hName;
}
public void sethName(String hName){
this.hName = hName;
}
public String getbeginn(){
return beginn;
}
public void setbeginn(String beginn){
this.beginn = beginn;
}
public long getId(){return id;}
public void setId(long id){
this.id = id;
}
public boolean isChecked(){return checked;}
public void setChecked(boolean checked){this.checked = checked;}
public String toString(){
String output = kName + " " + gName + " " + kTelefon + " " + hName
+ " " + beginn;
return output;
}
}
android:layout_height="wrap_content"
You need match parent
And if you're using a database, try to use CursorAdapter instead of ArrayAdapter and ensure that dataSource.getAllGruppen() actually returns something
Also, you have two instances of HundeschuleMemoDataSource dataSource. Remove the declaration from the field since the Context is not yet initialized
private HundeschuleMemoDataSource dataSource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gruppeauslesen);
dataSource = new HundeschuleMemoDataSource(this);
initializeHundeschuleKundenListView();
And if you did use a CursorAdapter, here's your corrected method
public Cursor getAllGruppen() {
String selectQuery = "SELECT " +
HundeschuleMemoDBHelper.COLUMN_ID + " , " +
HundeschuleMemoDBHelper.COLUMN_GNAME + " , " +
HundeschuleMemoDBHelper.COLUMN_KName + " , " +
HundeschuleMemoDBHelper.COLUMN_HUND + " , " +
HundeschuleMemoDBHelper.COLUMN_CHECKED +
" FROM " + HundeschuleMemoDBHelper.TABLE_KUNDEN_LIST +
" ORDER BY 2 ASC ";
return dbHelper.getReadableDatabase().rawQuery(selectQuery, null);
}
I am generating an events dynamically. These events data I am storing in sqlite database. Now I want to retrieve data of the clicked event. I tried to retrieve data but always getting 0th id data.
Generating events function :
private void createEvent(LayoutInflater inflater, ViewGroup dayplanView, int fromMinutes, int toMinutes, String title) {
final View eventView = inflater.inflate(R.layout.event_view, dayplanView, false);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) eventView.getLayoutParams();
RelativeLayout container = (RelativeLayout) eventView.findViewById(R.id.container);
TextView tvTitle = (TextView) eventView.findViewById(R.id.textViewTitle);
if (tvTitle.getParent() != null)
((ViewGroup) tvTitle.getParent()).removeView(tvTitle);
tvTitle.setText(title);
int distance = (toMinutes - fromMinutes);
layoutParams.topMargin = dpToPixels(fromMinutes + 9);
layoutParams.height = dpToPixels(distance);
eventView.setLayoutParams(layoutParams);
dayplanView.addView(eventView);
container.addView(tvTitle);
eventView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getActivity(),AddEventActivity.class);
startActivity(i);
}
});
}
This is my attempt to get data:
db = new EventTableHelper(getApplication());
eventData = new EventData();
if(editMode)//true
{
eventData = events.get(id);
Toast.makeText(getApplicationContext(),String.valueOf(id),Toast.LENGTH_LONG).show();
title.setText(eventData.getTitle());
eventTitle = title.getText().toString();
db.updateEvent(eventData);
Toast.makeText(getApplicationContext(),"Edit mode",Toast.LENGTH_LONG).show();
Log.i("Log","save mode");
}
I have EventTableHelper in that i have created functions to get event,update and delete events.
public class EventTableHelper extends SQLiteOpenHelper {
private static final String TABLE = "event";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_FROM_DATE = "datefrom";
private static final String KEY_TO_DATE = "dateto";
private static final String KEY_LOCATION = "location";
private static final String KEY_DAY_OF_WEEK = "dayofweek";
public EventTableHelper(Context context) {
super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
public void createTable(SQLiteDatabase db){
String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE+ "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_TITLE + " TEXT,"
+ KEY_FROM_DATE + " DATE,"
+ KEY_TO_DATE + " DATE,"
+ KEY_DAY_OF_WEEK + " TEXT "
+ KEY_LOCATION + " TEXT" + ")";
db.execSQL(CREATE_EVENTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
// createTable(db);
// onCreate(db);
}
public void addEvent(EventData event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE,event.getTitle());
values.put(KEY_FROM_DATE, event.getFromDate());
values.put(KEY_TO_DATE,event.getToDate());
values.put(KEY_DAY_OF_WEEK,event.getDayOfWeek());
values.put(KEY_LOCATION,event.getLocation());
db.insert(TABLE, null, values);
db.close();
}
EventData getEvent(int id) {
SQLiteDatabase db = this.getReadableDatabase();
EventData eventData = new EventData();
Cursor cursor = db.query(TABLE, new String[]{KEY_ID,
KEY_TITLE, KEY_FROM_DATE, KEY_TO_DATE,KEY_DAY_OF_WEEK, KEY_LOCATION}, KEY_ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if( cursor != null && cursor.moveToFirst() ) {
eventData = new EventData(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4), cursor.getString(5));
}
return eventData;
}
public List<EventData> getAllEvents() {
List<EventData> conList = new ArrayList<EventData>();
String selectQuery = "SELECT * FROM " + TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
EventData event = new EventData();
event.setId(Integer.parseInt(cursor.getString(0)));
event.setTitle(cursor.getString(1));
event.setFromDate(cursor.getString(2));
event.setToDate(cursor.getString(3));
event.setLocation(cursor.getString(4));
conList.add(event);
} while (cursor.moveToNext());
}
return conList;
}
}
I want to show data and update data if changes made.
Whats going wrong?
I have SQLite database file (which I did not create in this program, and it has its tables and datas), I open it in my android program, but when I write SELECT statement program can not find tables and I get error:
Error: no such table: Person
This is code:
public class SQLiteAdapter {
private DbDatabaseHelper databaseHelper;
private static String dbfile = "/data/data/com.example.searchpersons/databases/";
private static String DB_NAME = "Person.db";
static String myPath = dbfile + DB_NAME;
private static SQLiteDatabase database;
private static final int DATABASE_VERSION = 3;
private static String table = "Person";
private static Context myContext;
public SQLiteAdapter(Context ctx) {
SQLiteAdapter.myContext = ctx;
databaseHelper = new DbDatabaseHelper(SQLiteAdapter.myContext);
}
public static class DbDatabaseHelper extends SQLiteOpenHelper {
public DbDatabaseHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
dbfile = "/data/data/" + context.getPackageName() + "/databases/";
myPath = dbfile + DB_NAME;
//this.myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public SQLiteDatabase open() {
try {
database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
Log.v("db log", "database exist open");
} catch (SQLiteException e) {
Log.v("db log", "database does't exist");
}
if (database != null && database.isOpen())
return database;
else {
database = databaseHelper.getReadableDatabase();
Log.v("db log", "database exist helper");
}
return database;
}
public Cursor onSelect(String firstname, String lastname) {
Log.v("db log", "database exist select");
Cursor c = database.rawQuery("SELECT * FROM " + table + " where Firstname='" + firstname + "' And Lastname='" + lastname + "'", null);
c.moveToFirst();
return c;
}
public void close() {
if (database != null && database.isOpen()) {
database.close();
}
}
}
And this is button click function:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button btn1 = (Button) rootView.findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText t = (EditText) rootView.findViewById(R.id.editText1);
String name = t.getText().toString();
EditText tt = (EditText) rootView.findViewById(R.id.editText2);
String lastname = tt.getText().toString();
if (name.length() == 0 || lastname.length() == 0) {
Toast.makeText(rootView.getContext(), "Please fill both box", Toast.LENGTH_LONG).show();
} else {
GridView gridview = (GridView) rootView.findViewById(R.id.gridView1);
List < String > li = new ArrayList < String > ();
ArrayAdapter < String > adapter = new ArrayAdapter < String > (rootView.getContext(), android.R.layout.simple_gallery_item, li);
try {
SQLiteAdapter s = new SQLiteAdapter(rootView.getContext());
s.open();
Cursor c = s.onSelect(name, lastname);
if (c != null) {
if (c.moveToFirst()) {
do {
String id = c.getString(c.getColumnIndex("ID"));
String name1 = c.getString(c.getColumnIndex("Firstname"));
String lastname1 = c.getString(c.getColumnIndex("Lastname"));
String personal = c.getString(c.getColumnIndex("PersonalID"));
li.add(id);
li.add(name1);
li.add(lastname1);
li.add(personal);
gridview.setAdapter(adapter);
} while (c.moveToNext());
}
} else {
Toast.makeText(rootView.getContext(), "There is no data", Toast.LENGTH_LONG).show();
}
c.close();
s.close();
} catch (Exception e) {
Toast.makeText(rootView.getContext(), "Error : " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
});
return rootView;
}
I check database in SQLite Database Browser, everything is normal (There are tables and data), but program still can not find them.
I added sqlitemanager to eclipse and it can not see tables too:
There is only one table android_metadata and there are no my tables.
Can anyone help me?
I thought about it for about a week, the answer is very simple. I resolved the problem so:
from sqlitemanager
I added database from that button.
And now everything works fine ;)
In oncreate you have to create your db. I am sending you my db class.
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 DbAdapter extends SQLiteOpenHelper {
private static DbAdapter mDbHelper;
public static final String DATABASE_NAME = "demoDb";
public static final String TABLE_Coin= "coin_table";
public static final String TABLE_Inbox= "inbox";
public static final String TABLE_Feature= "feature";
public static final String TABLE_Time= "time";
public static final String TABLE_Deduct_money= "deduct_time";
public static final String TABLE_Unread_message= "unread_message";
public static final String COLUMN_Email= "email";
public static final String COLUMN_Appearence= "appearence";
public static final String COLUMN_Drivability= "drivability";
public static final String COLUMN_Fuel= "fuel";
public static final String COLUMN_Insurance= "insurance";
public static final String COLUMN_Wow= "wow";
public static final String COLUMN_CurrentValue= "current_value";
public static final String COLUMN_coin = "name";
public static final String COLUMN_seenTime = "seen";
public static final String COLUMN_number_of_times = "number_of_times";
public static final String COLUMN_name = "name";
public static final String COLUMN_type = "type";
public static final String COLUMN_text = "text";
public static final String COLUMN_image = "image";
public static final String COLUMN_created_time = "created_time";
public static final String COLUMN_unread = "unread";
// ****************************************
private static final int DATABASE_VERSION = 1;
private final String DATABASE_CREATE_BOOKMARK = "CREATE TABLE "
+ TABLE_Coin + "(" + COLUMN_coin
+ " Varchar,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK1 = "CREATE TABLE "
+ TABLE_Feature + "(" + COLUMN_Appearence
+ " Integer,"+COLUMN_Email +" Varchar ,"+COLUMN_name +" Varchar ,"+COLUMN_Drivability +" Integer ,"+COLUMN_Wow +" Integer,"+COLUMN_CurrentValue +" Integer,"+COLUMN_Fuel +" Integer,"+COLUMN_Insurance +" Integer, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK2 = "CREATE TABLE "
+ TABLE_Time + "(" + COLUMN_Email +" Varchar ,"+COLUMN_seenTime +" Integer,"+COLUMN_number_of_times +" Integer, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK3 = "CREATE TABLE "
+ TABLE_Deduct_money + "(" + COLUMN_seenTime
+ " Varchar,"+ COLUMN_number_of_times
+ " Integer,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK4 = "CREATE TABLE "
+ TABLE_Inbox + "(" + COLUMN_created_time
+ " DATETIME,"+ COLUMN_image
+ " Varchar,"
+ COLUMN_type
+ " Varchar,"+ COLUMN_name
+ " Varchar,"+ COLUMN_text
+ " Varchar,"+COLUMN_Email +" Varchar)";
private final String DATABASE_CREATE_BOOKMARK5 = "CREATE TABLE "
+ TABLE_Unread_message + "(" + COLUMN_unread
+ " Varchar,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private DbAdapter(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static synchronized DbAdapter getInstance(Context context) {
if (mDbHelper == null) {
mDbHelper = new DbAdapter(context);
}
return mDbHelper;
}
/**
* Tries to insert data into table
*
* #param contentValues
* #param tablename
* #throws SQLException
* on insert error
*/
public void insertQuery(ContentValues contentValues, String tablename)
throws SQLException {
try {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.insert(tablename, null, contentValues);
// writableDatabase.insertWithOnConflict(tablename, null,
// contentValues,SQLiteDatabase.CONFLICT_REPLACE);
} catch (Exception e) {
e.printStackTrace();
}
}
// public void insertReplaceQuery(ContentValues contentValues, String tablename)
// throws SQLException {
//
// try {
// final SQLiteDatabase writableDatabase = getWritableDatabase();
// writableDatabase.insertOrThrow(tablename, null, contentValues);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// /**
// * Update record by ID with contentValues
// *
// * #param id
// * #param contentValues
// * #param tableName
// * #param whereclause
// * #param whereargs
// */
public void updateQuery(ContentValues contentValues, String tableName,
String whereclause, String[] whereargs) {
try {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.update(tableName, contentValues, whereclause,
whereargs);
} catch (Exception e) {
e.printStackTrace();
}
}
public Cursor fetchQuery(String query) {
final SQLiteDatabase readableDatabase = getReadableDatabase();
final Cursor cursor = readableDatabase.rawQuery(query, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public Cursor fetchQuery(String query, String[] selectionArgs) {
final SQLiteDatabase readableDatabase = getReadableDatabase();
final Cursor cursor = readableDatabase.rawQuery(query, selectionArgs);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public void delete(String table) {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.delete(table, null, null);
}
public void delete(String table, String whereClause, String[] selectionArgs) {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.delete(table, whereClause, selectionArgs);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE_BOOKMARK);
db.execSQL(DATABASE_CREATE_BOOKMARK1);
db.execSQL(DATABASE_CREATE_BOOKMARK2);
db.execSQL(DATABASE_CREATE_BOOKMARK3);
db.execSQL(DATABASE_CREATE_BOOKMARK4);
db.execSQL(DATABASE_CREATE_BOOKMARK5);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Coin);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Feature);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Time);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Deduct_money);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Inbox);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Unread_message);
onCreate(db);
}
}
You are messing up the paths.
Please clean up every definition or reference to dbfile and myPath.You are initializing them in the definition with some values (probably copy-pasted), then giving them new different values in the DbDatabaseHelper constructor. And the helper will not use these paths, it will just create the database in the default directory.
Then after this, in the open method you are calling SQLiteDatabase.openDatabase with your intended paths. Use instead getReadableDatabase and getWritableDatabase from the Helper.
I am using SQLite in Android eclipse, however it gives me a java.lang.nullpointerexception in the function createEntry. I tried using Questoid SQLite manager to view the database file and it does show up with the table created. Where's the bug?
public class Transact {
public static final String KEY_ROWID = "_id";
public static final String KEY_TAG = "saved_tag";
private static final String DATABASE_NAME = "MyDatabaseName";
private static final String DATABASE_TABLE = "tagsTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TAG + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public Transact(Context c ){
ourContext = c;
}
public Transact open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String tagword) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_TAG, tagword);
return ourDatabase.insert(DATABASE_TABLE, "", cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID, KEY_TAG};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iTag = c.getColumnIndex(KEY_TAG);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iTag) + "\n";
}
return null;
}
}
Code for the add button from Main.java class:
case R.id.addDB:
boolean doneAdd = true;
try{
String tag = textTag.getText().toString();
Transact entry = new Transact(Main.this);
entry.open();
entry.createEntry(tag);
entry.close();
}catch(Exception e){
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Error");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
doneAdd = false;
}finally{
if(doneAdd){
Dialog d = new Dialog(this);
d.setTitle("Addition done");
TextView tv = new TextView(this);
tv.setText("Success");
d.setContentView(tv);
d.show();
}
}
break;
You are using ourDatabase variable without initializing it. So not only insert you will get nullpointerexception everywhere where you are using ourDatabase variable
you can use something like following in constructor.
SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_NAME,
Context.MODE_PRIVATE, null);
used this code in sq light java file
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 {
Cursor cursor;
public static final String MYDATABASE_NAME = "MY_DATABASE";
public static final String MYDATABASE_TABLE = "MY_TABLE";
public static final int MYDATABASE_VERSION = 2;
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";
public static final String KEY_CONTENT4 = "Content4";
public static final String KEY_CONTENT5 = "Content5";
public static final String KEY_CONTENT6 = "Content6";
public static final String KEY_CONTENT7 = "Content7";
public static final String KEY_CONTENT8 = "Content8";
public static final String KEY_CONTENT9 = "Content9";
public static final String KEY_CONTENT10 = "Content10";
public static final String KEY_CONTENT11 = "Content11";
public static final String KEY_CONTENT12 = "Content12";
// create table MY_DATABASE (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, " + KEY_CONTENT4
+ " text not null, " + KEY_CONTENT5 + " text not null, "
+ KEY_CONTENT6 + " text not null, " + KEY_CONTENT7
+ " text not null, " + KEY_CONTENT8 + " text not null, "
+ KEY_CONTENT9 + " text not null, " + KEY_CONTENT10
+ " text not null, " + KEY_CONTENT11 + " blob not null, "
+ KEY_CONTENT12 + " long 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 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("PRAGMA foreign_keys=ON");
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}