The error occurs when the app starts.
Tried to define:
queryBuilder.setTables(Constants.NOTES_TABLE);
but that gives an error saying
android.database.sqlite.SQLiteException: no such column:
The complete error:
Caused by: java.lang.IllegalStateException: Invalid tables
at android.database.sqlite.SQLiteDatabase.findEditTable(SQLiteDatabase.java:973)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:400)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:294)
at com.hackathon.hackmsit.data.NoteContentProvider.query(NoteContentProvider.java:70)
at android.content.ContentProvider.query(ContentProvider.java:1000)
at android.content.ContentProvider$Transport.query(ContentProvider.java:214)
at android.content.ContentResolver.query(ContentResolver.java:478)
at android.content.ContentResolver.query(ContentResolver.java:422)
at com.hackathon.hackmsit.data.NoteManager.getAllNotes(NoteManager.java:60)
at com.hackathon.hackmsit.fragments.NoteListFragment.setupList(NoteListFragment.java:98)
at com.hackathon.hackmsit.fragments.NoteListFragment.onCreateView(NoteListFragment.java:54)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1026)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1207)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1572)
at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:330)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:511)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1236)
at android.app.Activity.performStart(Activity.java:6057)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1319)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5287)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:114)
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
private com.mikepenz.materialdrawer.Drawer result = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
DatabaseHelper databaseHelper = new DatabaseHelper(this);
databaseHelper.getWritableDatabase();
result = new DrawerBuilder()
.withActivity(this)
.withToolbar(mToolbar)
.withActionBarDrawerToggle(true)
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.title_home).withIcon(FontAwesome.Icon.faw_home).withIdentifier(1),
//new PrimaryDrawerItem().withName(R.string.title_editor).withIcon(FontAwesome.Icon.faw_edit).withIdentifier(2),
new PrimaryDrawerItem().withName(R.string.title_settings).withIcon(FontAwesome.Icon.faw_list).withIdentifier(2)
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int i, IDrawerItem drawerItem) {
if (drawerItem != null && drawerItem instanceof Nameable){
String name = ((Nameable)drawerItem).getName().getText(MainActivity.this);
mToolbar.setTitle(name);
}
if (drawerItem != null){
int selectedScreen = drawerItem.getIdentifier();
switch (selectedScreen){
case 1:
//go to List of Notes
openFragment(new NoteListFragment(), "Notes");
break;
/*case 2:
//go the editor screen
startActivity(new Intent(MainActivity.this, NoteEditorActivity.class));*/
case 2:
//go to settings screen, yet to be added
//this will be your home work
Toast.makeText(MainActivity.this, "Settings Clicked", Toast.LENGTH_SHORT).show();
break;
}
}
return false;
}
})
.withOnDrawerListener(new Drawer.OnDrawerListener() {
#Override
public void onDrawerOpened(View view) {
KeyboardUtil.hideKeyboard(MainActivity.this);
}
#Override
public void onDrawerClosed(View view) {
}
#Override
public void onDrawerSlide(View view, float v) {
}
})
.withFireOnInitialOnClick(true)
.withSavedInstance(savedInstanceState)
.build();
if (savedInstanceState == null){
result.setSelection(1);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void openFragment(final Fragment fragment, String title){
getSupportFragmentManager()
.beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.replace(R.id.container, fragment)
.addToBackStack(null)
.commit();
getSupportActionBar().setTitle(title);
}
}
NoteContentProvider.java:
public class NoteContentProvider extends ContentProvider {
private DatabaseHelper dbHelper;
private static final String BASE_PATH_NOTE = "notes";
private static final String AUTHORITY = "com.hackathon.hackmsit.data.provider";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH_NOTE);
private static final int NOTE = 100;
private static final int NOTES = 101;
private static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
static {
URI_MATCHER.addURI(AUTHORITY, BASE_PATH_NOTE, NOTES);
URI_MATCHER.addURI(AUTHORITY, BASE_PATH_NOTE + "/#", NOTE);
}
private SQLiteDatabase db;
private void checkColumns(String[] projection) {
if (projection != null) {
HashSet<String> request = new HashSet<>(Arrays.asList(projection));
HashSet<String> available = new HashSet<>(Arrays.asList(Constants.COLUMNS));
if (!available.containsAll(request)) {
throw new IllegalArgumentException("Unknown columns in projection");
}
}
}
#Override
public boolean onCreate() {
dbHelper = new DatabaseHelper(getContext());
db = dbHelper.getWritableDatabase();
return (db == null)? false:true;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
//queryBuilder.setTables(Constants.NOTES_TABLE);
checkColumns(projection);
int type = URI_MATCHER.match(uri);
switch (type){
case NOTE:
//there is not to do if the query is for the table
break;
case NOTES:
queryBuilder.appendWhere(Constants.COLUMN_ID + " = " + uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
#Override
public String getType(Uri uri) {
return null;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
int type = URI_MATCHER.match(uri);
SQLiteDatabase db = dbHelper.getWritableDatabase();
Long id;
switch (type){
case NOTES:
id = db.insert(Constants.NOTES_TABLE, null, values);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return Uri.parse(BASE_PATH_NOTE + "/" + id);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int type = URI_MATCHER.match(uri);
SQLiteDatabase db = dbHelper.getWritableDatabase();
int affectedRows;
switch (type) {
case NOTES:
affectedRows = db.delete(Constants.NOTES_TABLE, selection, selectionArgs);
break;
case NOTE:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
affectedRows = db.delete(Constants.NOTES_TABLE, Constants.COLUMN_ID + "=" + id, null);
} else {
affectedRows = db.delete(Constants.NOTES_TABLE, Constants.COLUMN_ID + "=" + id + " and " + selection, selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return affectedRows;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int type = URI_MATCHER.match(uri);
SQLiteDatabase db = dbHelper.getWritableDatabase();
int affectedRows;
switch (type) {
case NOTES:
affectedRows = db.update(Constants.NOTES_TABLE, values, selection, selectionArgs);
break;
case NOTE:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
affectedRows = db.update(Constants.NOTES_TABLE, values, Constants.COLUMN_ID + "=" + id, null);
} else {
affectedRows = db.update(Constants.NOTES_TABLE, values, Constants.COLUMN_ID + "=" + id + " and " + selection, selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return affectedRows;
}
}
DatabaseHelper.java:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "notes.db";
private static final int DATABASE_VERSION = 3;
private static final String CREATE_TABLE_NOTE = "create table "
+ Constants.NOTES_TABLE
+ "("
+ Constants.COLUMN_ID + " integer primary key autoincrement, "
+ Constants.COLUMN_TITLE + " text not null, "
+ Constants.COLUMN_CONTENT + " text not null, "
+ Constants.COLUMN_MODIFIED_TIME + " integer not null, "
+ Constants.COLUMN_CREATED_TIME + " integer not null " + ");";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_NOTE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Constants.NOTES_TABLE);
onCreate(db);
}
}
Manifest entry:
<provider
android:name=".data.NoteContentProvider"
android:authorities="com.hackathon.hackmsit.data.provider"
android:exported="false" />
Edit:
Constants.java:
public class Constants {
public static final String NOTES_TABLE = "notes";
public static final String COLUMN_ID = "_id";
//public final static String COLUMN_NAME = "name";
public static final String COLUMN_TITLE = "title";
public static final String COLUMN_CONTENT = "content";
public static final String COLUMN_MODIFIED_TIME = "modified_time";
public static final String COLUMN_CREATED_TIME = "created_time";
public static final String[] COLUMNS = {
Constants.COLUMN_ID,
Constants.COLUMN_TITLE,
Constants.COLUMN_CONTENT,
Constants.COLUMN_MODIFIED_TIME,
Constants.COLUMN_CREATED_TIME
};
}
Any help is appreciated.
android.database.sqlite.SQLiteException: no such column:
At First Modify your CREATE TABLE Statement
String CREATE_TABLE_NOTE = "CREATE TABLE " + Constants.NOTES_TABLE + "("
+ Constants.COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ Constants.COLUMN_TITLE + " TEXT Default 'Unknown', "
+ Constants.COLUMN_CONTENT + " TEXT Default 'Unknown', "
+ Constants.COLUMN_MODIFIED_TIME + " INTEGER, "
+ Constants.COLUMN_CREATED_TIME + " INTEGER )";
Then Un-install old App & Run Again .
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
I am trying to code my own content provider for users. When I try to verify if the user exists,when the DBHelper tries to create the database, it throws a null exception.
Here is the content provider:
public class MyUserProvider extends ContentProvider {
private UserDBHelper db;
private static final int USERS = 10;
private static final int USER_ID = 20;
private static final String AUTHORITY =
"net.ifo420.ritc.agenda.userprovider";
private static final String BASE_PATH = "users";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/" + BASE_PATH);
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/users";
public static final String CONTENT_ITEM_TYPE =
ContentResolver.CURSOR_ITEM_BASE_TYPE + "/user";
private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
uriMatcher.addURI(AUTHORITY, BASE_PATH, USERS);
uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", USER_ID);
}
public MyUserProvider() {
}
#Override
public boolean onCreate() {
db = new UserDBHelper(getContext());
return false;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
checkColumns(projection);
queryBuilder.setTables(UserTable.TABLE);
int uriType = uriMatcher.match(uri);
switch (uriType) {
case USERS:
break;
case USER_ID:
queryBuilder.appendWhere(UserTable.COLUMN_ID + " = " + uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Uknown uri " + uri);
}
SQLiteDatabase db1 = db.getReadableDatabase();
Cursor cursor = queryBuilder.query(db1, projection, selection, selectionArgs,
null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
#Override
public String getType(Uri uri) {
return null;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
int uriType = uriMatcher.match(uri);
SQLiteDatabase database = db.getReadableDatabase();
long id = 0;
switch (uriType) {
case USERS:
id = database.insert(UserTable.TABLE, null, values);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return Uri.parse(BASE_PATH + "/" + id);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int uriType = uriMatcher.match(uri);
SQLiteDatabase sqLiteDatabase = db.getReadableDatabase();
int rowsDeleted = 0;
switch (uriType) {
case USERS:
rowsDeleted = sqLiteDatabase.delete(UserTable.TABLE, selection,
selectionArgs);
break;
case USER_ID:
String id = uri.getLastPathSegment();
if(TextUtils.isEmpty(selection)) {
rowsDeleted = sqLiteDatabase.delete(UserTable.TABLE,
UserTable.COLUMN_ID + " = " + id, null);
} else {
rowsDeleted = sqLiteDatabase.delete(UserTable.TABLE,
UserTable.COLUMN_ID + " = " + id + " and " +
selection, selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsDeleted;
}
#Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int uriType = uriMatcher.match(uri);
SQLiteDatabase sqLiteDatabase = db.getReadableDatabase();
int rowsUpdated = 0;
switch (uriType) {
case USERS:
rowsUpdated = sqLiteDatabase.update(UserTable.TABLE,
values,
selection,
selectionArgs);
break;
case USER_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsUpdated = sqLiteDatabase.update(UserTable.TABLE,
values,
UserTable.COLUMN_ID + "=" + id,
null);
} else {
rowsUpdated = sqLiteDatabase.update(UserTable.TABLE,
values,
UserTable.COLUMN_ID + "=" + id
+ " and "
+ selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}
private void checkColumns(String[] projection) {
String[] available = {UserTable.COLUMN_USERNAME, UserTable.COLUMN_PASSWORD,
UserTable.COLUMN_ID};
if (projection != null) {
HashSet<String> requestedColumns =
new HashSet<String>(Arrays.asList(projection));
HashSet<String> availableColumns =
new HashSet<String>(Arrays.asList(available));
if (!availableColumns.containsAll(requestedColumns)) {
throw new IllegalArgumentException("Unknown columns in projection");
}
}
}
Here is my DBHelper
public class UserDBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "agenda.db";
private static final int DB_VERSION = 1;
public UserDBHelper (Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
UserTable.onCreate(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
UserTable.onUpgrade(db, oldVersion, newVersion);
}
Here is the sample code I am using to verify if the user exists (sorry a bit is in french):
public void onClick(View view) {
switch (view.getId()) {
case R.id.boutonLogin:
if (userExists()) {
Toast.makeText(this, "L'utilisateur existe.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "L'utilisateur n'existe pas.", Toast.LENGTH_SHORT).show();
}
}
private boolean userExists() {
String username = nomUtilisateur.getText().toString();
String password = motPasse.getText().toString();
Cursor users = userProvider.query(MyUserProvider.CONTENT_URI,
null,
" WHERE username = " + nomUtilisateur.getText().toString() +
" AND password = " + motPasse.getText().toString(), null, null);
if (users.getCount() != 0) {
return true;
} else {
return false;
}
Here is what the logcat gives me:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase net.info420.ritc.agendacegep.UserDBHelper.getReadableDatabase()' on a null object reference
at net.info420.ritc.agendacegep.MyUserProvider.query(MyUserProvider.java:70)
at net.info420.ritc.agendacegep.LoginActivity.utilisateurExiste(LoginActivity.java:69)
at net.info420.ritc.agendacegep.LoginActivity.onClick(LoginActivity.java:57)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22260)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
You can't directly instantiate and call a ContentProvider- you have to go through a content resolver. Otherwise it doesn't go through the provider's lifecycle and onCreate isn't called.
Well, I got my own answer. Yes I couldn't instantiate my ContentProvider, but it was not only that. I changed my code and realised that I only did not really undertand the selection and selectionArgs parameters in the query.
So it went from:
private boolean userExists() {
String username = nomUtilisateur.getText().toString();
String password = motPasse.getText().toString();
Cursor users = userProvider.query(MyUserProvider.CONTENT_URI,
null,
" WHERE username = " + nomUtilisateur.getText().toString() +
" AND password = " + motPasse.getText().toString(), null, null);
if (users.getCount() != 0) {
return true;
} else {
return false;
}
}
To :
private boolean userExists() {
String username = nomUtilisateur.getText().toString();
String password = motPasse.getText().toString();
String[] selection = {username, password};
Cursor users = getApplicationContext().getContentResolver().query
(Agenda.UserEntry.CONTENT_URI,
null,
"username = ? AND password = ?", selection, null);
if (users.getCount() != 0) {
return true;
} else {
return false;
}
}
So, the cursor was null because I did not make a correct query and that is why my database was not created: because i did not need it at the end in my code.
I'm creating a Calorie App for my class project. I attempted to implement a database to store the information of the calories added by the user which would be displayed in a listview. The user will input the calories in the add_entry fragment and be displayed on the fragment_home page in the listview.
Problem: I'm not sure if I'm adding the information correctly to the database using the Entry Add Fragment in order to display the info in the listview. this is my first time working with Android Studio/App.
Problem 2:
For Some Reason when I click on imagebutton on my homefragment app crashes and
it doesnt go to the add_entry fragment
logcat:
04-06 00:33:41.213 30567-30567/com.example.treycoco.calorietracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.treycoco.calorietracker, PID: 30567
java.lang.IllegalStateException: Could not find method Click(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatImageButton with id 'AddItems'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:325)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5697)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
FragmentHome.java
public class FragmentHome extends Fragment implements
View.OnClickListener {
public static final String ARG_SECTION_NUMBER = "section_number";
public static final String ARG_ID = "_id";
private TextView label;
private int sectionNumber = 0;
private Calendar fragmentDate;
ListView listview;
ImageButton AddEntrybtn;
CalorieDatabase calorieDB;
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
public FragmentHome() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_home, container,
false);
label= (TextView) myView.findViewById(R.id.section_label);
AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);
return myView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle username = getActivity().getIntent().getExtras();
String username1 = username.getString("Username");
TextView userMain= (TextView) getView().findViewById(R.id.User);
userMain.setText(username1);
openDataBase();
}
private void openDataBase (){
calorieDB= new CalorieDatabase(getActivity());
calorieDB.open();
}
private void closeDataBase(){
calorieDB.close();
};
private void populateLVFromDB(){
Cursor cursor = calorieDB.getAllRows();
String[] fromFieldNames = new String[]
{CalorieDatabase.KEY_NAME, CalorieDatabase.KEY_CalorieValue};
int[] toViewIDs = new int[]
{R.id.foodEditText, R.id.caloriesEditText, };
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
getActivity(),
R.layout.row_item,
cursor,
fromFieldNames,
toViewIDs
);
listview = (ListView) getActivity().findViewById(R.id.listView);
listview.setAdapter(myCursorAdapter);
}
#Override
public void onResume() {
super.onResume();
// set label to selected date. Get date from Bundle.
int dayOffset = sectionNumber - FragmentHomeDayViewPager.pagerPageToday;
fragmentDate = Calendar.getInstance();
fragmentDate.add(Calendar.DATE, dayOffset);
SimpleDateFormat sdf = new SimpleDateFormat(appMain.dateFormat);
String labelText = sdf.format(fragmentDate.getTime());
switch (dayOffset) {
case 0:
labelText += " (Today)";
break;
case 1:
labelText += " (Tomorrow)";
break;
case -1:
labelText += " (Yesterday)";
break;
}
label.setText(labelText);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
startActivity( new Intent(getContext(),MainActivity.class));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddItems:
AddEntry addEntry = new AddEntry();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.FragmentHolder,addEntry)
.commit();
break;
}
}
}
CalorieDatabase.java
public class CalorieDatabase {
private static final String TAG = "DBAdapter";
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_NAME = "Description";
public static final String KEY_CalorieValue = "Calories";
public static final int COL_NAME = 1;
public static final int COL_CalorieValue= 2;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID,
KEY_NAME, KEY_CalorieValue};
public static final String DATABASE_NAME = "CalorieDb";
public static final String DATABASE_TABLE = "Calorie_Info";
public static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null, "
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public CalorieDatabase(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
public CalorieDatabase open() {
db = myDBHelper.getWritableDatabase();
return this;
}
public void close() {
myDBHelper.close();
}
public long insertRow(String description, int CalorieVal) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, description);
initialValues.put(KEY_CalorieValue, CalorieVal);
return db.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public boolean updateRow(long rowId, String description, int
CalorieValue) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, description);
newValues.put(KEY_CalorieValue, CalorieValue);
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int
newVersion) {
Log.w(TAG, "Upgrading application's database from version " +
oldVersion
+ " to " + newVersion + ", which will destroy all old
data!");
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(_db);
}
}
}
AddEntry.java
public class AddEntry extends Fragment implements
View.OnClickListener {
EditText DescriptionET,CalorieET;
ImageButton savebtn;
String description , calorieAmt;
CalorieDatabase calorieDB;
public AddEntry() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_add_entry, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
DescriptionET= (EditText)view.findViewById(R.id.foodEditText);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SaveBtn:
description = DescriptionET.getText().toString();
calorieAmt=CalorieET.getText().toString();
break;
case R.id.CancelBtn:
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
private static final String DATABASE_NAME = "CalorieDb.db";
And then call below method in oncreat()
public void checkDB() {
try {
//android default database location is : /data/data/youapppackagename/databases/
String packageName = this.getPackageName();
String destPath = "/data/data/" + packageName + "/databases";
String fullPath = "/data/data/" + packageName + "/databases/"
+ DATABASE_NAME;
//this database folder location
File f = new File(destPath);
//this database file location
File obj = new File(fullPath);
//check if databases folder exists or not. if not create it
if (!f.exists()) {
f.mkdirs();
f.createNewFile();
}
//check database file exists or not, if not copy database from assets
if (!obj.exists()) {
this.CopyDB(fullPath);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Unintall app and clean and rebuild project then I think solve your problem.
Try Replaceing this, Removing the last Comma(,) from the statement
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null "
+ ");";
Remove , from last field
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null "
+ ");";
private static final String DATABASE_CREATE_SQL =
" create table " + DATABASE_TABLE
+ " ( " + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null, "
+ " ); ";
Add space " ) "
i follow this example
it works fine, but as i modified the inserting methode, i got NullpointerException in this line:
return DB.insert(tableName, null, initialValues);
tableName is assigned and initialValues also. i don't know why i got NullpointerException.
my code:
public class MainActivity extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
private String tableName = DBHelper.tableName;
private SQLiteDatabase newDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
InsertTheData();
openAndQueryDatabase();
displayResultList();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void displayResultList() {
TextView tView = new TextView(this);
tView.setText("This data is retrieved from the database and only 4 " +
"of the results are displayed");
getListView().addHeaderView(tView);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
}
private void InsertTheData()
{
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
dbHelper.insertSomeItmes();
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(getClass().getSimpleName(), "Could not Insert data");
}
finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
private void openAndQueryDatabase() {
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT FirstName, Age FROM " +
tableName +
" where Age > 10 LIMIT 4", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("FirstName"));
int age = c.getInt(c.getColumnIndex("Age"));
results.add("Name: " + firstName + ",Age: " + age);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
}
and DbHelper class:
public class DBHelper extends SQLiteOpenHelper {
public SQLiteDatabase DB;
public String DBPath;
public static String DBName = "sample";
public static final int version = '1';
public static Context currentContext;
public static String tableName = "Resource";
public static final String KEY_LastName = "LastName";
public static final String KEY_FirstName = "FirstName";
public static final String KEY_Country = "Country";
public static final String KEY_Age = "Age";
private static final String TAG = "Create_The_DB";
private static final String TABLE_CREATE = "CREATE TABLE IF NOT EXISTS " +
tableName + " ( "+ KEY_LastName + " VARCHAR, "+ KEY_FirstName +" VARCHAR," + KEY_Country + " VARCHAR,"+ KEY_Age +" INT(3))";
public DBHelper(Context context) {
//super(context, name, factory, version);
// TODO Auto-generated constructor stub
super(context, DBName, null, version);
currentContext = context;
DBPath = "/data/data/" + context.getPackageName() + "/databases";
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
Log.w(TAG, TABLE_CREATE);
boolean dbExists = checkDbExists();
if (dbExists) {
// do nothing
} else {
DB = currentContext.openOrCreateDatabase(DBName, 0, null);
DB.execSQL(TABLE_CREATE);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CREATE);
onCreate(db);
}
private boolean checkDbExists() {
SQLiteDatabase checkDB = null;
try {
String myPath = DBPath + DBName;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
public long createItmes(String LeLastName, String LeFirstName, String LeCountry, int LeAge) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_LastName, LeLastName);
initialValues.put(KEY_FirstName, LeFirstName);
initialValues.put(KEY_Country, LeCountry);
initialValues.put(KEY_Age, LeAge);
return DB.insert(tableName, null, initialValues);
}
public void insertSomeItmes() {
createItmes("AFG","Afghanistan","Asia",5);
createItmes("ALB","Albania","Europe",9);
createItmes("DZA","Algeria","Africa",52);
createItmes("AND","Andorra","Europe",55);
createItmes("AGO","Angola","Africa",63);
createItmes("AIA","Anguilla","North America",75);
}
}
I'm just guessing, but when you reach DBHelper#onCreate and if the DBHelper#checkDbExists returns true there might be possibility that the DB field is still unassigned.
You should have provided stack trace.
I have been read in somewhere is primary key is mandatory
This is the code:
TodoTable.java:
public class TodoTable {
// Database table
public static final String TABLE_TODO = "todo";
public static final String COLUMN_ID_U = "_id";
public static final String COLUMN_CATEGORY = "category";
public static final String COLUMN_SUMMARY = "summary";
public static final String COLUMN_DESCRIPTION = "description";
public static final String COLUMN_SATZE = "satze";
// Database creation SQL statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_TODO
+ "("
+ COLUMN_ID_U + " integer primary key autoincrement, "
+ COLUMN_CATEGORY + " text not null, "
+ COLUMN_SUMMARY + " text not null, "
+ COLUMN_DESCRIPTION + " text not null, "
+ COLUMN_SATZE + " text not null"
+ ");";
public static void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
public static void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {
Log.w(TodoTable.class.getName(), "Upgrading database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS " + TABLE_TODO);
onCreate(database);
}}
TodoDetailAktivity.java:
public class TodoDetailActivity extends Activity {
private Spinner mCategory;
private EditText mTitleText;
private EditText mBodyText;
private EditText mSatzText;
private EditText mPauseText;
private EditText mWDHText;
private EditText mGewichtText;
private Uri todoUri;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.todo_edit);
mCategory = (Spinner) findViewById(R.id.category);
mTitleText = (EditText) findViewById(R.id.todo_edit_summary);
mBodyText = (EditText) findViewById(R.id.todo_edit_description);
mSatzText = (EditText) findViewById(R.id.editTextsatz);
Button confirmButton = (Button) findViewById(R.id.todo_edit_button);
Bundle extras = getIntent().getExtras();
// Check from the saved Instance
todoUri = (bundle == null) ? null : (Uri) bundle
.getParcelable(MyTodoContentProvider.CONTENT_ITEM_TYPE);
// Or passed from the other activity
if (extras != null) {
todoUri = extras
.getParcelable(MyTodoContentProvider.CONTENT_ITEM_TYPE);
fillData(todoUri);
}
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (TextUtils.isEmpty(mTitleText.getText().toString())) {
makeToast();
} else {
setResult(RESULT_OK);
finish();
}
}
});
}
private void fillData(Uri uri) {
String[] projection = { TodoTable.COLUMN_SUMMARY,
TodoTable.COLUMN_DESCRIPTION, TodoTable.COLUMN_CATEGORY };
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
if (cursor != null) {
cursor.moveToFirst();
String category = cursor.getString(cursor
.getColumnIndexOrThrow(TodoTable.COLUMN_CATEGORY));
for (int i = 0; i < mCategory.getCount(); i++) {
String s = (String) mCategory.getItemAtPosition(i);
if (s.equalsIgnoreCase(category)) {
mCategory.setSelection(i);
}
}
mTitleText.setText(cursor.getString(cursor
.getColumnIndexOrThrow(TodoTable.COLUMN_SUMMARY)));
mBodyText.setText(cursor.getString(cursor
.getColumnIndexOrThrow(TodoTable.COLUMN_DESCRIPTION)));
mSatzText.setText(cursor.getString(cursor
.getColumnIndexOrThrow(TodoTable.COLUMN_SATZE)));
// Always close the cursor
cursor.close();
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putParcelable(MyTodoContentProvider.CONTENT_ITEM_TYPE, todoUri);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
private void saveState() {
String category = (String) mCategory.getSelectedItem();
String summary = mTitleText.getText().toString();
String description = mBodyText.getText().toString();
String satze = mSatzText.getText().toString();
// Only save if either summary or description
// is available
if (description.length() == 0 && summary.length() == 0 && satze.length() == 0) {
return;
}
ContentValues values = new ContentValues();
values.put(TodoTable.COLUMN_CATEGORY, category);
values.put(TodoTable.COLUMN_SUMMARY, summary);
values.put(TodoTable.COLUMN_DESCRIPTION, description);
values.put(TodoTable.COLUMN_SATZE, satze);
if (todoUri == null) {
// New todo
todoUri = getContentResolver().insert(MyTodoContentProvider.CONTENT_URI, values);
} else {
// Update todo
getContentResolver().update(todoUri, values, null, null);
}
}
private void makeToast() {
Toast.makeText(TodoDetailActivity.this, "Please maintain a summary",
Toast.LENGTH_LONG).show();
}}
TodosOverviewAktivity.java:
/*
* TodosOverviewActivity displays the existing todo items
* in a list
*
* You can create new ones via the ActionBar entry "Insert"
* You can delete existing ones via a long press on the item
*/
#TargetApi(11)
public class TodosOverviewActivity extends ListActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final int ACTIVITY_CREATE = 0;
private static final int ACTIVITY_EDIT = 1;
private static final int DELETE_ID = Menu.FIRST + 1;
// private Cursor cursor;
private SimpleCursorAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.todo_list);
this.getListView().setDividerHeight(1);
fillData();
registerForContextMenu(getListView());
}
// Create the menu based on the XML defintion
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.listmenu, menu);
return true;
}
// Reaction to the menu selection
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.insert:
createTodo();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Uri uri = Uri.parse(MyTodoContentProvider.CONTENT_URI + "/"
+ info.id);
getContentResolver().delete(uri, null, null);
fillData();
return true;
}
return super.onContextItemSelected(item);
}
private void createTodo() {
Intent i = new Intent(this, TodoDetailActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
// Opens the second activity if an entry is clicked
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, TodoDetailActivity.class);
Uri todoUri = Uri.parse(MyTodoContentProvider.CONTENT_URI + "/" + id);
i.putExtra(MyTodoContentProvider.CONTENT_ITEM_TYPE, todoUri);
// Activity returns an result if called with startActivityForResult
startActivityForResult(i, ACTIVITY_EDIT);
}
// Called with the result of the other activity
// requestCode was the origin request code send to the activity
// resultCode is the return code, 0 is everything is ok
// intend can be used to get data
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
}
private void fillData() {
// Fields from the database (projection)
// Must include the _id column for the adapter to work
String[] from = new String[] { TodoTable.COLUMN_SUMMARY };
// Fields on the UI to which we map
int[] to = new int[] { R.id.label };
getLoaderManager().initLoader(0, null, this);
adapter = new SimpleCursorAdapter(this, R.layout.todo_row, null, from,
to, 0);
setListAdapter(adapter);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}
// Creates a new loader after the initLoader () call
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = { TodoTable.COLUMN_ID_U, TodoTable.COLUMN_SUMMARY };
CursorLoader cursorLoader = new CursorLoader(this,
MyTodoContentProvider.CONTENT_URI, projection, null, null, null);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// data is not available anymore, delete reference
adapter.swapCursor(null);
}}
MyTodoContentProvider.java:
public class MyTodoContentProvider extends ContentProvider {
// database
private TodoDatabaseHelper database;
// Used for the UriMacher
private static final int TODOS = 10;
private static final int TODO_ID = 20;
private static final String AUTHORITY = "de.vogella.android.todos.contentprovider";
private static final String BASE_PATH = "todos";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/" + BASE_PATH);
public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE
+ "/todos";
public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE
+ "/todo";
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
sURIMatcher.addURI(AUTHORITY, BASE_PATH, TODOS);
sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/#", TODO_ID);
}
#Override
public boolean onCreate() {
database = new TodoDatabaseHelper(getContext());
return false;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// Uisng SQLiteQueryBuilder instead of query() method
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
// Check if the caller has requested a column which does not exists
checkColumns(projection);
// Set the table
queryBuilder.setTables(TodoTable.TABLE_TODO);
int uriType = sURIMatcher.match(uri);
switch (uriType) {
case TODOS:
break;
case TODO_ID:
// Adding the ID to the original query
queryBuilder.appendWhere(TodoTable.COLUMN_ID_U + "="
+ uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
SQLiteDatabase db = database.getWritableDatabase();
Cursor cursor = queryBuilder.query(db, projection, selection,
selectionArgs, null, null, sortOrder);
// Make sure that potential listeners are getting notified
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
#Override
public String getType(Uri uri) {
return null;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
int uriType = sURIMatcher.match(uri);
SQLiteDatabase sqlDB = database.getWritableDatabase();
int rowsDeleted = 0;
long id = 0;
switch (uriType) {
case TODOS:
id = sqlDB.insert(TodoTable.TABLE_TODO, null, values);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return Uri.parse(BASE_PATH + "/" + id);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int uriType = sURIMatcher.match(uri);
SQLiteDatabase sqlDB = database.getWritableDatabase();
int rowsDeleted = 0;
switch (uriType) {
case TODOS:
rowsDeleted = sqlDB.delete(TodoTable.TABLE_TODO, selection,
selectionArgs);
break;
case TODO_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsDeleted = sqlDB.delete(TodoTable.TABLE_TODO,
TodoTable.COLUMN_ID_U + "=" + id,
null);
} else {
rowsDeleted = sqlDB.delete(TodoTable.TABLE_TODO,
TodoTable.COLUMN_ID_U + "=" + id
+ " and " + selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsDeleted;
}
#Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int uriType = sURIMatcher.match(uri);
SQLiteDatabase sqlDB = database.getWritableDatabase();
int rowsUpdated = 0;
switch (uriType) {
case TODOS:
rowsUpdated = sqlDB.update(TodoTable.TABLE_TODO,
values,
selection,
selectionArgs);
break;
case TODO_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsUpdated = sqlDB.update(TodoTable.TABLE_TODO,
values,
TodoTable.COLUMN_ID_U + "=" + id,
null);
} else {
rowsUpdated = sqlDB.update(TodoTable.TABLE_TODO,
values,
TodoTable.COLUMN_ID_U + "=" + id
+ " and "
+ selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}
private void checkColumns(String[] projection) {
String[] available = { TodoTable.COLUMN_CATEGORY,
TodoTable.COLUMN_SUMMARY, TodoTable.COLUMN_DESCRIPTION, TodoTable.COLUMN_SATZE, TodoTable.COLUMN_ID_U };
if (projection != null) {
HashSet<String> requestedColumns = new HashSet<String>(Arrays.asList(projection));
HashSet<String> availableColumns = new HashSet<String>(Arrays.asList(available));
// Check if all columns which are requested are available
if (!availableColumns.containsAll(requestedColumns)) {
throw new IllegalArgumentException("Unknown columns in projection");
}
}
}
}
TodoDatabaseHelper.java:
public class TodoDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "todotable.db";
private static final int DATABASE_VERSION = 1;
public TodoDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method is called during creation of the database
#Override
public void onCreate(SQLiteDatabase database) {
TodoTable.onCreate(database);
}
// Method is called during an upgrade of the database,
// e.g. if you increase the database version
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {
TodoTable.onUpgrade(database, oldVersion, newVersion);
}
}
The most of code I have copied from: http://www.vogella.com/articles/AndroidSQLite/article.html#todo
But I get the errormessage (LogCat):
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.de.vogella.android.todos/com.example.de.vogella.android.todos.TodoDetailActivity}: java.lang.IllegalArgumentException: column 'satze' does not exist
Can anybody find a mistake in the code?
Thanks
Here is your bug:
private void fillData(Uri uri) {
String[] projection = { TodoTable.COLUMN_SUMMARY,
TodoTable.COLUMN_DESCRIPTION, TodoTable.COLUMN_CATEGORY }; //add satze here!
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
if (cursor != null) {
cursor.moveToFirst();
String category = cursor.getString(cursor
.getColumnIndexOrThrow(TodoTable.COLUMN_CATEGORY));
for (int i = 0; i < mCategory.getCount(); i++) {
String s = (String) mCategory.getItemAtPosition(i);
if (s.equalsIgnoreCase(category)) {
mCategory.setSelection(i);
}
}
mTitleText.setText(cursor.getString(cursor
.getColumnIndexOrThrow(TodoTable.COLUMN_SUMMARY)));
mBodyText.setText(cursor.getString(cursor
.getColumnIndexOrThrow(TodoTable.COLUMN_DESCRIPTION)));
mSatzText.setText(cursor.getString(cursor
.getColumnIndexOrThrow(TodoTable.COLUMN_SATZE)));//you don't have satze in projection!
// Always close the cursor
cursor.close();
}
}
You are trying to read TodoTable.COLUMN_SATZE but you forgot about it in projection:
Please change this line:
String[] projection = { TodoTable.COLUMN_SUMMARY,
TodoTable.COLUMN_DESCRIPTION, TodoTable.COLUMN_CATEGORY };
into this:
String[] projection = { TodoTable.COLUMN_SUMMARY,
TodoTable.COLUMN_DESCRIPTION, TodoTable.COLUMN_CATEGORY, TodoTable.COLUMN_SATZE };
In your CREATE TABLE statement you need spaces between your column names and column types.