This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to practise on the loader and content provider i have a database of students that contains (name , degree) in the activity_main.xml i have a recyclerview and 2 editText one for name other for degree my target is that when a user click on the button the name will appear in the recyclerview
here's my logcat
FATAL EXCEPTION: main
Process: com.example.abdelmagied.myapplication, PID: 16160
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.abdelmagied.myapplication.recyclerview.swapcursor(android.database.Cursor)' on a null object reference
at com.example.abdelmagied.myapplication.MainActivity.onLoadFinished(MainActivity.java:97)
at com.example.abdelmagied.myapplication.MainActivity.onLoadFinished(MainActivity.java:17)
at android.support.v4.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:476)
at android.support.v4.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManager.java:444)
at android.support.v4.content.Loader.deliverResult(Loader.java:126)
at android.support.v4.content.CursorLoader.deliverResult(CursorLoader.java:105)
at android.support.v4.content.CursorLoader.deliverResult(CursorLoader.java:37)
at android.support.v4.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:255)
at android.support.v4.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:80)
at android.support.v4.content.ModernAsyncTask.finish(ModernAsyncTask.java:485)
at android.support.v4.content.ModernAsyncTask$InternalHandler.handleMessage(ModernAsyncTask.java:502)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
this is my mainactivity class
package com.example.abdelmagied.myapplication;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>{
public static final String[] MAIN_STUDENT_PROJECTION = {
studentContract.StudentEntry._ID ,
studentContract.StudentEntry.COLUMN_NAME ,
studentContract.StudentEntry.COLUMN_DEGREE ,
};
public static final int INDEX_COLUMN_ID = 0;
public static final int INDEX_COLUMN_NAME = 1;
public static final int INDEX_COLUMN_DEGREE = 2;
private recyclerview recyclerAdapter;
private int mposition = RecyclerView.NO_POSITION;
public static final int ID_STUDNET_LOADER = 99;
// details of the recyclerview
RecyclerView recycler;
RecyclerView.Adapter myadapter;
RecyclerView.LayoutManager mymanager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// adjust the recyclerview
recycler = (RecyclerView) findViewById(R.id.recyclerid);
myadapter = new recyclerview(this);
mymanager = new LinearLayoutManager(this);
recycler.setAdapter(myadapter);
recycler.setLayoutManager(mymanager);
getSupportLoaderManager().initLoader(ID_STUDNET_LOADER , null , this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
switch(id)
{
case ID_STUDNET_LOADER :
Uri Query = studentContract.StudentEntry.CONTENT_URI;
return new CursorLoader(this ,
Query ,
MAIN_STUDENT_PROJECTION ,
null ,
null ,
null
);
default:
throw new RuntimeException("Loader is not implemented : " + id);
}
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
recyclerAdapter.swapcursor(data);
if(mposition == RecyclerView.NO_POSITION) mposition = 0;
recycler.smoothScrollToPosition(mposition);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
recyclerAdapter.swapcursor(null);
}
public void addtodatabase(View view) {
EditText name = (EditText) findViewById(R.id.name);
EditText degree=(EditText) findViewById(R.id.degree);
// make a contentvalues and put name , degree , salary on it...
ContentValues values = new ContentValues();
values.put(studentContract.StudentEntry.COLUMN_NAME , name.getText().toString());
values.put(studentContract.StudentEntry.COLUMN_DEGREE , degree.getText().toString());
getContentResolver().insert(studentContract.StudentEntry.CONTENT_URI , values);
}
}
here's the recyclerview adapter
package com.example.abdelmagied.myapplication;
import android.content.Context;
import android.database.Cursor;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by AbdELMagied on 8/4/2017.
*/
public class recyclerview extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
private Cursor mycursor;
public recyclerview(Context context) {
this.context = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recyclerrow , parent , false);
return new viewholder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
mycursor.move(position);
viewholder myholder = (viewholder) holder;
myholder.mytxt.setText(mycursor.getString(MainActivity.INDEX_COLUMN_NAME));
}
void swapcursor(Cursor mycurso)
{
this.mycursor = mycurso;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
if(mycursor == null) return 0;
return mycursor.getCount();
}
public class viewholder extends RecyclerView.ViewHolder
{
public TextView mytxt;
public viewholder(View itemView) {
super(itemView);
mytxt = (TextView) itemView.findViewById(R.id.textView);
}
}
}
here's my content provider
package com.example.abdelmagied.myapplication;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.text.TextUtils;
/**
* Created by AbdELMagied on 8/4/2017.
*/
public class studentprovider extends ContentProvider {
databaseopenhelper mydatabase;
static final int STUDENT = 100;
static final int STUDENT_WITH_ID = 101;
private UriMatcher urimatcher = matcher();
private UriMatcher matcher() {
UriMatcher mymatcher = new UriMatcher(UriMatcher.NO_MATCH);
mymatcher.addURI(studentContract.authority, "student", STUDENT);
mymatcher.addURI(studentContract.authority, "student/#", STUDENT_WITH_ID);
return mymatcher;
}
#Override
public boolean onCreate() {
mydatabase = new databaseopenhelper(getContext());
return true;
}
#Nullable
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Cursor returncursor;
switch (urimatcher.match(uri)) {
case STUDENT:
returncursor = mydatabase.getReadableDatabase().query(
studentContract.StudentEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
case STUDENT_WITH_ID:
String where = "_id = " + uri.getLastPathSegment() + (!TextUtils.isEmpty(selection)? " AND " + selection : "");
returncursor = mydatabase.getReadableDatabase().query(
studentContract.StudentEntry.TABLE_NAME,
projection,
where,
selectionArgs,
null,
null,
sortOrder
);
break;
default:
throw new UnsupportedOperationException("not found uri " + uri);
}
returncursor.setNotificationUri(getContext().getContentResolver() , uri);
return returncursor;
}
#Nullable
#Override
public String getType(Uri uri) {
return null;
}
#Nullable
#Override
public Uri insert(Uri uri, ContentValues values) {
long rowid = mydatabase.getWritableDatabase().insert(studentContract.StudentEntry.TABLE_NAME, null , values);
if(rowid > 0)
{
Uri _uri = ContentUris.withAppendedId(studentContract.StudentEntry.CONTENT_URI, rowid);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLException("Faild to add a record " + uri);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
if(selection == "") selection= "1";
int numberofdeleted = 0;
switch (urimatcher.match(uri))
{
case STUDENT:
String where = "_id = " + uri.getLastPathSegment() + (!TextUtils.isEmpty(selection)? "AND " + selection : "");
numberofdeleted = mydatabase.getWritableDatabase().delete("students" , where , selectionArgs);
break;
default:
throw new UnsupportedOperationException("uri not found " + uri);
}
if(numberofdeleted != 0)
{
getContext().getContentResolver().notifyChange(uri , null);
}
return numberofdeleted;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}
here's the database class
package com.example.abdelmagied.myapplication;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by AbdELMagied on 8/4/2017.
*/
public class databaseopenhelper extends SQLiteOpenHelper {
public databaseopenhelper(Context context) {
super(context, "student.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_STUDENT_TABLE =
"CREATE TABLE " + studentContract.StudentEntry.TABLE_NAME + " (" +
studentContract.StudentEntry._ID + " INTEGER PRIMARY KEY , " +
studentContract.StudentEntry.COLUMN_NAME + " TEXT , " +
studentContract.StudentEntry.COLUMN_DEGREE + " TEXT ); " ;
db.execSQL(SQL_CREATE_STUDENT_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop database if exists student");
onCreate(db);
}
}
here's studentcontract class
package com.example.abdelmagied.myapplication;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.text.TextUtils;
/**
* Created by AbdELMagied on 8/4/2017.
*/
public class studentprovider extends ContentProvider {
databaseopenhelper mydatabase;
static final int STUDENT = 100;
static final int STUDENT_WITH_ID = 101;
private UriMatcher urimatcher = matcher();
private UriMatcher matcher() {
UriMatcher mymatcher = new UriMatcher(UriMatcher.NO_MATCH);
mymatcher.addURI(studentContract.authority, "student", STUDENT);
mymatcher.addURI(studentContract.authority, "student/#", STUDENT_WITH_ID);
return mymatcher;
}
#Override
public boolean onCreate() {
mydatabase = new databaseopenhelper(getContext());
return true;
}
#Nullable
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Cursor returncursor;
switch (urimatcher.match(uri)) {
case STUDENT:
returncursor = mydatabase.getReadableDatabase().query(
studentContract.StudentEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
case STUDENT_WITH_ID:
String where = "_id = " + uri.getLastPathSegment() + (!TextUtils.isEmpty(selection)? " AND " + selection : "");
returncursor = mydatabase.getReadableDatabase().query(
studentContract.StudentEntry.TABLE_NAME,
projection,
where,
selectionArgs,
null,
null,
sortOrder
);
break;
default:
throw new UnsupportedOperationException("not found uri " + uri);
}
returncursor.setNotificationUri(getContext().getContentResolver() , uri);
return returncursor;
}
#Nullable
#Override
public String getType(Uri uri) {
return null;
}
#Nullable
#Override
public Uri insert(Uri uri, ContentValues values) {
long rowid = mydatabase.getWritableDatabase().insert(studentContract.StudentEntry.TABLE_NAME, null , values);
if(rowid > 0)
{
Uri _uri = ContentUris.withAppendedId(studentContract.StudentEntry.CONTENT_URI, rowid);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLException("Faild to add a record " + uri);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
if(selection == "") selection= "1";
int numberofdeleted = 0;
switch (urimatcher.match(uri))
{
case STUDENT:
String where = "_id = " + uri.getLastPathSegment() + (!TextUtils.isEmpty(selection)? "AND " + selection : "");
numberofdeleted = mydatabase.getWritableDatabase().delete("students" , where , selectionArgs);
break;
default:
throw new UnsupportedOperationException("uri not found " + uri);
}
if(numberofdeleted != 0)
{
getContext().getContentResolver().notifyChange(uri , null);
}
return numberofdeleted;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}
recyclerAdapter is never instantiated. onCreate would be an ideal place to instantiate this object of type recyclerview.
Related
I'm having this error when I try to update/edit the Sqlite database java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 can any on helping me.
when I try to delete the existing data from the database it works. But when I try to update or edit the existing data from the database, it does not work and the app crashes.
when I check the database inspector then I find one thing that when I try to edit the table data on the database the Class_table will gone or you can say delete automatically. and I don't find any solution for this problem can anyone help me plz.
Here is the error code:
Process: com.example.attendance, PID: 20112
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at com.example.attendance.MainActivity.updateClass(MainActivity.java:135)
at com.example.attendance.MainActivity.lambda$showUpdateDialog$4$MainActivity(MainActivity.java:131)
at com.example.attendance.-$$Lambda$MainActivity$m9twlugKZZaVnr6kCG8LrRCoXMM.onClick(Unknown Source:4)
at com.example.attendance.MyDialog.lambda$getUpdateClassDialog$1$MyDialog(MyDialog.java:94)
at com.example.attendance.-$$Lambda$MyDialog$5v1iqgaO8riJO2phwUfadWXdoyM.onClick(Unknown Source:6)
at android.view.View.performClick(View.java:8160)
at android.widget.TextView.performClick(TextView.java:16222)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:8137)
at android.view.View.access$3700(View.java:888)
at android.view.View$PerformClick.run(View.java:30236)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8512)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
I/Process: Sending signal. PID: 20112 SIG: 9
Here is My Activity:
package com.example.attendance;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toolbar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
FloatingActionButton floatingActionButton;
RecyclerView recyclerView;
ClassAdapter classAdapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<ClassItem> classItems = new ArrayList<>();
Toolbar toolbar;
DbHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new DbHelper(this);
floatingActionButton = findViewById(R.id.fab_main);
floatingActionButton.setOnClickListener(V -> showDialog());
loadData();
recyclerView = findViewById(R.id.att_list);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
classAdapter = new ClassAdapter(this, classItems);
recyclerView.setAdapter(classAdapter);
classAdapter.setOnItemClickListener(position -> gotoItemActivity(position));
setToolbar();
}
private void loadData() {
Cursor cursor = dbHelper.getClassTable();
classItems.clear();
while (cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex(DbHelper.C_ID));
String department = cursor.getString(cursor.getColumnIndex(DbHelper.CLASS_NAME_KEY));
String subject = cursor.getString(cursor.getColumnIndex(DbHelper.SUBJECT_NAME_KEY));
classItems.add(new ClassItem(id,department,subject));
}
}
private void setToolbar() {
toolbar = findViewById(R.id.toolbar);
TextView title = toolbar.findViewById(R.id.tool_title);
TextView subTitle = toolbar.findViewById(R.id.tool_sub_title);
TextView samiTitle = toolbar.findViewById(R.id.tool_sami_title);
ImageButton back = toolbar.findViewById(R.id.tool_back);
ImageButton save = toolbar.findViewById(R.id.tool_save);
title.setText("Attendance");
subTitle.setVisibility(View.GONE);
samiTitle.setVisibility(View.GONE);
save.setVisibility(View.GONE);
back.setOnClickListener(v -> onBackPressed());
}
private void gotoItemActivity(int position) {
Intent intent = new Intent(this,StudentActivity.class);
intent.putExtra("departmentName",classItems.get(position).getDepartment());
intent.putExtra("subjectName",classItems.get(position).getSubject());
intent.putExtra("position",position);
startActivity(intent);
}
private void showDialog() {
MyDialog dialog = new MyDialog();
dialog.show(getSupportFragmentManager(),MyDialog.CLASS_ADD_DIALOG);
dialog.setListener((department,subject)->addClass(department,subject));
}
private void addClass(String department, String subject) {
long cid = dbHelper.addClass(department,subject);
ClassItem classItem = new ClassItem(cid,department,subject);
classItems.add(classItem);
classAdapter.notifyDataSetChanged();
}
#Override
public boolean onContextItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case 0:
showUpdateDialog(item.getGroupId());
case 1:
deleteClass(item.getGroupId());
}
return super.onContextItemSelected(item);
}
private void showUpdateDialog(int position) {
MyDialog updateDialog = new MyDialog();
updateDialog.show(getSupportFragmentManager(),MyDialog.CLASS_UPDATE_DIALOG);
updateDialog.setListener((department,subject)->updateClass(position,department,subject));
}
// when I try to Update the Data its don't work and the app will crash
private void updateClass(int position, String department, String subject) {
dbHelper.updateClass(classItems.get(position).getCid(),department,subject);
classItems.get(position).setDepartment(department);
classItems.get(position).setSubject(subject);
classAdapter.notifyItemChanged(position);
}
private void deleteClass(int position) {
dbHelper.deleteClass(classItems.get(position).getCid());
classItems.remove(position);
classAdapter.notifyItemRemoved(position);
}
}
Here is my Adepter
package com.example.attendance;
import android.content.Context;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ClassAdapter extends RecyclerView.Adapter<ClassAdapter.ClassViewHolder> {
private OnItemClickListener onItemClickListener;
public interface OnItemClickListener {
void onClick(int position);
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public ClassAdapter(Context context, ArrayList<ClassItem> classItems) {
this.classItems = classItems;
this.context = context;
}
ArrayList<ClassItem> classItems;
Context context;
public static class ClassViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
TextView department, subject;
public ClassViewHolder(#NonNull View itemView,OnItemClickListener onItemClickListener) {
super(itemView);
department = itemView.findViewById(R.id.dep_tv);
subject = itemView.findViewById(R.id.sub_tv);
itemView.setOnClickListener(v -> onItemClickListener.onClick(getAdapterPosition()));
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.add(getAdapterPosition(),0,0,"EDIT");
menu.add(getAdapterPosition(),1,0,"DELETE");
}
}
#NonNull
#Override
public ClassViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.class_item, parent, false);
return new ClassViewHolder(itemView, onItemClickListener);
}
#Override
public void onBindViewHolder(#NonNull ClassViewHolder holder, int position) {
holder.department.setText(classItems.get(position).getDepartment());
holder.subject.setText(classItems.get(position).getSubject());
}
#Override
public int getItemCount() {
return classItems.size();
}
}
Here is Database
package com.example.attendance;
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;
import androidx.annotation.Nullable;
public class DbHelper extends SQLiteOpenHelper {
private static final int VERSION = 1;
//Class table
private static final String CLASS_TABLE_NAME= "CLASS_TABLE";
public static final String C_ID= "_CID";
public static final String CLASS_NAME_KEY= "CLASS_NAME";
public static final String SUBJECT_NAME_KEY= "SUBJECT_NAME";
private static final String CREATE_CLASS_TABLE=
"CREATE TABLE " + CLASS_TABLE_NAME + "(" +
C_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
CLASS_NAME_KEY + " TEXT NOT NULL, " +
SUBJECT_NAME_KEY + " TEXT NOT NULL, " +
" UNIQUE ( " + CLASS_NAME_KEY + "," + SUBJECT_NAME_KEY + ")" +
");";
private static final String DROP_CLASS_TABLE = "DROP TABLE IF EXISTS "+CLASS_TABLE_NAME;
private static final String SELECT_CLASS_TABLE = "SELECT * FROM "+CLASS_TABLE_NAME;
//Student table
private static final String STUDENT_TABLE_NAME= "STUDENT_TABLE";
private static final String S_ID= "_SID";
private static final String STUDENT_NAME_KEY= "STUDENT_NAME";
private static final String STUDENT_ROLL_KEY= "ROLL";
private static final String CREATE_STUDENT_TABLE=
"CREATE TABLE "+ STUDENT_TABLE_NAME +
"( "+
S_ID+ " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "+
C_ID + " TEXT NOT NULL, "+
STUDENT_NAME_KEY + " TEXT NOT NULL, "+
STUDENT_ROLL_KEY + " INTEGER, "+
" FOREIGN KEY ( "+C_ID+ " ) REFERENCES "+ CLASS_TABLE_NAME + "("+C_ID+")"+
");";
private static final String DROP_STUDENT_TABLE = "DROP TABLE IF EXISTS "+STUDENT_TABLE_NAME;
private static final String SELECT_STUDENT_TABLE = "SELECT * FROM "+STUDENT_TABLE_NAME;
//Status table
private static final String STATUS_TABLE_NAME= "STATUS_TABLE";
private static final String STATUS_ID= "_STATUS_ID";
private static final String DATE_KEY= "STATUS_NAME";
private static final String STATUS_KEY= "STATUS";
private static final String CREATE_STATUS_TABLE=
"CREATE TABLE "+STATUS_TABLE_NAME+
"("+
STATUS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "+
S_ID + " INTEGER NOT NULL, "+
DATE_KEY + " DATE NOT NULL, "+
STATUS_KEY + " TEXT NOT NULL, "+
" UNIQUE ( " + S_ID + "," + DATE_KEY + ")," +
" FOREIGN KEY ( "+ S_ID+ " ) REFERENCES "+ STUDENT_TABLE_NAME + "( "+S_ID+")"+
");";
private static final String DROP_STATUS_TABLE = "DROP TABLE IF EXISTS "+ STATUS_TABLE_NAME;
private static final String SELECT_STATUS_TABLE = "SELECT * FROM "+ STATUS_TABLE_NAME;
public DbHelper(#Nullable Context context) {
super(context, "Attendance.db", null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_CLASS_TABLE);
db.execSQL(CREATE_STUDENT_TABLE);
db.execSQL(CREATE_STATUS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_CLASS_TABLE);
db.execSQL(DROP_STUDENT_TABLE);
db.execSQL(DROP_STATUS_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
long addClass(String className,String subjectName){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CLASS_NAME_KEY,className);
values.put(SUBJECT_NAME_KEY,subjectName);
return database.insert(CLASS_TABLE_NAME,null,values);
}
Cursor getClassTable(){
SQLiteDatabase database = this.getReadableDatabase();
return database.rawQuery(SELECT_CLASS_TABLE,null);
}
int deleteClass(long cid){
SQLiteDatabase database = this.getReadableDatabase();
return database.delete(CLASS_TABLE_NAME,C_ID+"=?",new String[]{String.valueOf(cid)});
}
long updateClass(long cid,String className,String subjectName){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CLASS_NAME_KEY,className);
values.put(SUBJECT_NAME_KEY,subjectName);
return database.update(CLASS_TABLE_NAME,values,C_ID+"=?",new String[]{String.valueOf(cid)});
}
}
After dropping your tables, you forgot to create them again in your onUpgrade method.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_CLASS_TABLE);
db.execSQL(DROP_STUDENT_TABLE);
db.execSQL(DROP_STATUS_TABLE);
onCreate(db);
} catch (SQLException e) {
e.printStackTrace();
}
}
Also it is a good idea to call .close() method every time you call .getWritableDatabase() or .getReadableDatabase(). Here is an example ...
long addClass(String className, String subjectName){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CLASS_NAME_KEY,className);
values.put(SUBJECT_NAME_KEY,subjectName);
database.close();
long id = database.insert(CLASS_TABLE_NAME,null,values);
return id;
}
Hope it helps, happy coding!
The issue is in your MainActivity.class and StudentActivity.class.
In your onContextItemSelected(#NonNull MenuItem item) method, you forgot to break; your switch statement.
#Override
public boolean onContextItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case 0:
showUpdateDialog(item.getGroupId());
break;
case 1:
deleteClass(item.getGroupId());
break;
} return true;
}
Also, instead of adding classItems or studentItems to their respective ArrayLists after updating or deleting data in your SQLite Database, just call loadData() method again!
private void deleteClass(int position) {
dbHelper.deleteClass(classItems.get(position).getCid());
loadData();
classAdapter.notifyDataSetChanged();
}
private void updateClass(int position, String department, String subject) {
dbHelper.updateClass(classItems.get(position).getCid(),department,subject);
loadData();
classAdapter.notifyDataSetChanged();
}
The same thing applies to your StudentActivity.class. Happy Coding!
I have made a content provider for my project, and also another project for content resolver.
but suddenly content resolver app is stop running.
this is the content provider app:
package com.example.connectly.database;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import static android.content.Context.MODE_PRIVATE;
public class SeekersContactsProvider extends ContentProvider {
SQLiteDatabase seekerSQLiteDatabase;
private static final String AUTHORITY = "com.example.connectly";
private static final String BASE_PATH = "seekers";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);
private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
private static final int SEEKER = 0;
// private static final String SEEKER_EMAIL = "email";
private static final int SEEKER_EMAIL = 1;
private static final String SEEKER_TABLE_NAME = "seeker";
Cursor cursor;
public static final String[] ALL_COLUMNS =
{"email", "password", "firstname", "lastname","phone","age","dob","gender"};
static {
uriMatcher.addURI(AUTHORITY, BASE_PATH, SEEKER);
// uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", EMAIL);
uriMatcher.addURI(AUTHORITY, BASE_PATH + "/" + SEEKER_TABLE_NAME, SEEKER_EMAIL);
}
#Override
public boolean onCreate() {
seekerSQLiteDatabase = getContext().openOrCreateDatabase("Users", MODE_PRIVATE, null);
seekerSQLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS seeker (email VARCHAR, password VARCHAR, firstname VARCHAR, lastname VARCHAR, phone VARCHAR, age VARCHAR, dob VARCHAR, gender VARCHAR)");
return true;
}
#Nullable
#Override
public Cursor query(#NonNull Uri uri, #Nullable String[] projection, #Nullable String selection, #Nullable String[] selectionArgs, #Nullable String sortOrder) {
switch (uriMatcher.match(uri)) {
case SEEKER:
cursor = seekerSQLiteDatabase.query(SEEKER_TABLE_NAME, ALL_COLUMNS,selection
, null, null, null, "firstname" + " ASC");
break;
default:
throw new IllegalArgumentException("This is an Unknown URI " + uri);
}
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
#Nullable
#Override
public String getType(#NonNull Uri uri) {
switch (uriMatcher.match(uri)) {
case SEEKER:
return "com.example.connectly/seeker";
default:
throw new IllegalArgumentException("This is an Unknown URI " + uri);
}
}
#Nullable
#Override
public Uri insert(#NonNull Uri uri, #Nullable ContentValues contentValues) {
long id = seekerSQLiteDatabase.insert(SEEKER_TABLE_NAME, null, contentValues);
if (id > 0) {
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, id);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLException("Insertion Failed for URI :" + uri);
}
#Override
public int delete(#NonNull Uri uri, #Nullable String selection, #Nullable String[] selectionArgs) {
int delCount = 0;
switch (uriMatcher.match(uri)) {
case SEEKER:
delCount = seekerSQLiteDatabase.delete(SEEKER_TABLE_NAME, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("This is an Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return delCount;
}
#Override
public int update(#NonNull Uri uri, #Nullable ContentValues values, #Nullable String selection, #Nullable String[] selectionArgs) {
int updCount = 0;
switch (uriMatcher.match(uri)) {
case SEEKER:
updCount = seekerSQLiteDatabase.update(SEEKER_TABLE_NAME, values, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("This is an Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return updCount;
}
}
this is the content resolver code, but when I run the app and click on the load data button, it suddenly stops:
p
ackage com.example.App2ContentProvider;
import androidx.appcompat.app.AppCompatActivity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button loadBtn;
Uri CONTENT_URI = Uri.parse("content://com.example.connectly/seekers");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadBtn = findViewById(R.id.load);
loadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// inserting complete table details in this text field
TextView resultView = (TextView) findViewById(R.id.textView);
// creating a cursor object of the
// content URI
Cursor cursor = getContentResolver().query(Uri.parse("content://com.example.connectly/seekers"), null, null, null, null);
// iteration of the cursor
// to print whole table
if (cursor.moveToFirst()) {
StringBuilder strBuild = new StringBuilder();
while (!cursor.isAfterLast()) {
strBuild.append("\n" + cursor.getString(
cursor.getColumnIndex("firstname")) + "-" + cursor.getString(cursor.getColumnIndex("lastname")) + cursor.getString(cursor.getColumnIndex("email")) + cursor.getString(cursor.getColumnIndex("phone")) +
cursor.getString(cursor.getColumnIndex("age")) + cursor.getString(cursor.getColumnIndex("dob")) +
cursor.getString(cursor.getColumnIndex("gender")) );
cursor.moveToNext();
}
resultView.setText(strBuild);
} else {
resultView.setText("No Records Found");
}
}
});
}
}
and this is the error shown:
FATAL EXCEPTION: main
Process: com.example.contentprovider_p2, PID: 9084
java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.database.Cursor.moveToFirst()' on a null object reference
at com.example.App2ContentProvider.MainActivity$1.onClick(MainActivity.java:35)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I am trying to write a program CFM.java to insert data into product table using content provider using android studio.
But the app crashes after clicking on the add button to add record to the database.
I can't solve the issue.
Any help is sincerely appreciated.
MyContentProvider.java
`
package com.example.cfm;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import java.util.HashMap;
import android.text.TextUtils;
public class MyContentProvider extends ContentProvider {
public MyContentProvider() {}
static final String PROVIDER_NAME = "com.example.cfm.MyContentProvider";
static final String URL = "content://" + PROVIDER_NAME + "/food_products";
static final Uri CONTENT_URI = Uri.parse(URL);
static final String _ID = "_id";
static final String NAME = "name";
static final String COSTPERITEM = "cost";
static final String NOOFITEMS = "itemsno";
private static HashMap<String, String> PRODUCT_PROJECTION_MAP;
static final int PRODUCTS = 1;
static final int PRODUCTS_ID = 2;
static final UriMatcher uriMatcher;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "products", PRODUCTS);
uriMatcher.addURI(PROVIDER_NAME, "products/#",PRODUCTS_ID);
}
private SQLiteDatabase db;
static final String DATABASE_NAME = "ProductDetails";
static final String PRODUCT_TABLE_NAME = "food_products";
static final int DATABASE_VERSION = 1;
static final String CREATE_TABLE = " CREATE TABLE " + PRODUCT_TABLE_NAME+
" (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ " name TEXT NOT NULL," +
"cost DECIMAL(6,2) NOT NULL,"+
"itemsno INTEGER NOT NULL)";
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper (Context context){
super(context, DATABASE_NAME ,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(CREATE_TABLE);
}
public void onUpgrade(SQLiteDatabase db,int previousversion,int newversion)
{
db.execSQL("DROP TABLE IF EXISTS " + PRODUCT_TABLE_NAME);
onCreate(db);
}
}
#Override
public boolean onCreate() {
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
db = dbHelper.getWritableDatabase();
if (db != null) {
return true;
}
return false;
}
#Override
public Uri insert(Uri uri, ContentValues values) throws SQLException {
long rowID = db.insert("PRODUCT_TABLE_NAME", "", values);
if (rowID > 0) {
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLException("RECORD NOT ADDED INTO" + uri);
}
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(PRODUCT_TABLE_NAME);
switch (uriMatcher.match(uri)) {
case PRODUCTS:
qb.setProjectionMap(PRODUCT_PROJECTION_MAP);
break;
case PRODUCTS_ID:
qb.appendWhere( _ID + "=" + uri.getPathSegments().get(1));
break;
default:
}
if (sortOrder == null || sortOrder =="") {
sortOrder = NAME;
}
Cursor c = qb.query(db, projection, selection, selectionArgs, null,
null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs)
{
int count = 0;
switch (uriMatcher.match(uri)){
case PRODUCTS:
count = db.delete(PRODUCT_TABLE_NAME,_ID + " id = ?"+ (!TextUtils.isEmpty(selection)? "AND(" + selection + ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("UNKOWN URI " + uri );
}
getContext().getContentResolver().notifyChange(uri,null);
return count;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case PRODUCTS:
count = db.update(PRODUCT_TABLE_NAME, values, selection, selectionArgs);
break;
case PRODUCTS_ID:
count = db.update(PRODUCT_TABLE_NAME,values,_ID+"="+uri.getPathSegments().get(1) +
(!TextUtils.isEmpty(selection) ?"AND (" + selection + ')':
""), selectionArgs);
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
#Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case PRODUCTS:
return "vnd.android.cursor.dir/vnd.example.food_products";
case PRODUCTS_ID:
return "und.android.cursor.item/vnd.example.students";
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
}
}
MainActivity.java
package com.example.cfm;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button add;
EditText Name;
EditText Cost;
EditText No;
TextView seeProduct;
TextView seeCost;
TextView seeNo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = findViewById(R.id.btnAdd);
Name = findViewById(R.id.editText1);
No = findViewById(R.id.editText2);
Cost = findViewById(R.id.editText3);
seeProduct = findViewById(R.id.product);
seeCost = findViewById(R.id.cost);
seeNo = findViewById(R.id.no);
}
public void onClickAddName(View view) {
ContentValues values = new ContentValues();
values.put(MyContentProvider.NAME, (Name).getText().toString());
values.put(MyContentProvider.NOOFITEMS, (No).getText().toString());
values.put(MyContentProvider.COSTPERITEM, (Cost).getText().toString());
Uri uri = getContentResolver().insert(MyContentProvider.CONTENT_URI, values);
//Name.setText("");
assert uri != null;
Toast.makeText(getBaseContext(),uri.toString(), Toast.LENGTH_LONG).show();
}
}
Stack Trace on Clicking the ADD button
Caused by: android.database.SQLException: RECORD NOT ADDED INTOcontent://com.example.cfm.MyContentProvider/food_products
at com.example.cfm.MyContentProvider.insert(MyContentProvider.java:76)
at android.content.ContentProvider.insert(ContentProvider.java:1673)
at android.content.ContentProvider$Transport.insert(ContentProvider.java:336)
at android.content.ContentResolver.insert(ContentResolver.java:2149)
at android.content.ContentResolver.insert(ContentResolver.java:2111)
at com.example.cfm.MainActivity.onClickAddName(MainActivity.java:39)
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28296)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I am trying to implement a search function into a custom list view. I using a menu for the search feature. When I type into the search bar, my project crashes with this error.
2019-11-19 18:50:05.762 17072-17072/? E/AndroidRuntime: FATAL
EXCEPTION: main
Process: com.example.medicationmanagementsystem, PID: 17072
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Iterator java.util.ArrayList.iterator()' on a null object
reference
at com.example.medicationmanagementsystem.ViewListContents$1.onQueryTextChange(ViewListContents.java:72)
I think it is getting null for the array and is therefore unable to show any details. Any help would be grateful.
ViewListContents.java
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.MenuItemCompat;
import com.example.medicationmanagementsystem.DAO.DatabaseHelper;
import java.util.ArrayList;
public class ViewListContents extends AppCompatActivity {
DatabaseHelper myDB;
ArrayList<Prescription> prescriptionList;
ListView listView;
Prescription prescription;
ArrayList<String> listItem;
ArrayAdapter adapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.viewcontents_layout);
myDB = new DatabaseHelper(this);
prescriptionList = new ArrayList<Prescription>();
Cursor data = myDB.getListContents();
int numRows = data.getCount();
if(numRows == 0){
Toast.makeText(ViewListContents.this, "There is nothing in this database", Toast.LENGTH_LONG).show();
}
else {
while(data.moveToNext()){
prescription = new Prescription(data.getString(1), data.getString(2), data.getString(3),
data.getString(4), data.getString(5), data.getString(6), data.getString(7),
data.getString(8), data.getString(9));
prescriptionList.add(prescription);
}
EightColumn_ListAdapter adapter = new EightColumn_ListAdapter(this,R.layout.prescription_view,prescriptionList);
listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
}
}
//END
//This code is based on SQLite Database to ListView- Part 4:Search Items- Android Studio Tutorial, KOD Dev, https://www.youtube.com/watch?v=QY-O49a_Ags
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.item_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
ArrayList<String> listViews = new ArrayList<>();
for (String prescription : listItem){
if (prescription.toLowerCase().contains(newText.toLowerCase())){
listViews.add(prescription);
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ViewListContents.this,R.layout.prescription_view,listViews);
listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
}
DatabaseHelper.java
package com.example.medicationmanagementsystem.DAO;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
//Create Database
public static final String DATABASE_NAME = "ManagementSystem.db";
//Create patient table
public static final String TABLE_PATIENT = "patient_table";
public static final String COL_PATIENT_PATIENTID = "PATIENTID";
public static final String COL_PATIENT_FNAME = "FNAME";
public static final String COL_PATIENT_SNAME = "SNAME";
public static final String COL_PATIENT_PPS = "PPS";
public static final String COL_PATIENT_DOB = "DOB";
public static final String COL_PATIENT_ADDRESS = "ADDRESS";
public static final String COL_PATIENT_TYPE = "PATIENTTYPE";
public static final String COL_PATIENT_MEDCOND = "PATIENTMEDCON";
public static final String COL_PATIENT_CARINGID = "CARINGID";
//Create prescription table
public static final String TABLE_PRESCRIPTION = "prescription_table";
public static final String COL_PRESCRIPTION_ID = "PRESCRIPTIONID";
public static final String COL_PRESCRIPTION__PATIENTID = COL_PATIENT_PATIENTID;
public static final String COL_PRESCRIPTION__DATE = "DATE";
public static final String COL_PRESCRIPTION__DRUGNAME = "DRUGNAME";
public static final String COL_PRESCRIPTION__CONCENTRATION = "CONCENTRATION";
public static final String COL_PRESCRIPTION__DOSAGE = "DOSAGE";
public static final String COL_PRESCRIPTION__PREPARATION = "PREPARATION";
public static final String COL_PRESCRIPTION__STARTDATE = "STARTDATE";
public static final String COL_PRESCRIPTION__ENDDATE = "ENDDATE";
public static final String COL_PRESCRIPTION__DOCTORID = "DOCTORID";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate (SQLiteDatabase db) {
String patienttable = "CREATE TABLE " + TABLE_PATIENT + "(PATIENTID INTEGER PRIMARY KEY AUTOINCREMENT, FNAME TEXT, SNAME TEXT, PPS TEXT, DOB TEXT, ADDRESS TEXT, PATIENTTYPE TEXT, PATIENTMEDCON TEXT, CARINGID INTEGER)";
String prescriptiontable = "CREATE TABLE " + TABLE_PRESCRIPTION + "(PRESCRIPTIONID INTEGER PRIMARY KEY AUTOINCREMENT, PATIENTID INTEGER, DATE TEXT, DRUGNAME TEXT, CONCENTRATION TEXT, DOSAGE TEXT, PREPARATION TEXT, STARTDATE TEXT, ENDDATE TEXT, DOCTORID INTEGER)";
db.execSQL(patienttable);
db.execSQL(prescriptiontable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_PATIENT);
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_PRESCRIPTION);
onCreate(db);
}
//insert patient data
public boolean insertPatientData(String fname, String sname, String pps, String dob, String address, String patienttype, String patientmedcon, String caringid) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues1 = new ContentValues();
contentValues1.put(COL_PATIENT_FNAME, fname);
contentValues1.put(COL_PATIENT_SNAME, sname);
contentValues1.put(COL_PATIENT_PPS, pps);
contentValues1.put(COL_PATIENT_DOB, dob);
contentValues1.put(COL_PATIENT_ADDRESS, address);
contentValues1.put(COL_PATIENT_TYPE, patienttype);
contentValues1.put(COL_PATIENT_MEDCOND,patientmedcon);
contentValues1.put(COL_PATIENT_CARINGID, caringid);
long result= db.insert(TABLE_PATIENT,null, contentValues1);
if (result == 1)
return false;
else
return true;
}
//insert prescription data
public boolean insertData(String patientid, String date, String drugname, String concentration,String dosage, String preparation, String startdate, String enddate, String doctorid) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues2 = new ContentValues();
contentValues2.put(COL_PRESCRIPTION__PATIENTID, patientid);
contentValues2.put(COL_PRESCRIPTION__DATE, date);
contentValues2.put(COL_PRESCRIPTION__DRUGNAME, drugname);
contentValues2.put(COL_PRESCRIPTION__CONCENTRATION, concentration);
contentValues2.put(COL_PRESCRIPTION__DOSAGE, dosage);
contentValues2.put(COL_PRESCRIPTION__PREPARATION, preparation);
contentValues2.put(COL_PRESCRIPTION__STARTDATE, startdate);
contentValues2.put(COL_PRESCRIPTION__ENDDATE, enddate);
contentValues2.put(COL_PRESCRIPTION__DOCTORID, doctorid);
long result= db.insert(TABLE_PRESCRIPTION,null, contentValues2);
if (result == 1)
return false;
else
return true;
//END
}
//Coding with mitch tutorial
public Cursor getListContents() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_PRESCRIPTION, null);
return data;
}
////This code is based on SQLite Database to ListView- Part 4:Search Items- Android Studio Tutorial, KOD Dev, https://www.youtube.com/watch?v=QY-O49a_Ags
public Cursor searchPrescriptions(String text) {
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select * from " + TABLE_PRESCRIPTION + "WHERE " + COL_PRESCRIPTION__PATIENTID + " Like '%" + text +"%'";
Cursor data = db.rawQuery(query, null);
return data;
}
}
Eight_Column_ListAdapter.java
package com.example.medicationmanagementsystem;
//The code below is based on Adding multiple columns to your ListView, CodingWithMitch, https://www.youtube.com/watch?v=8K-6gdTlGEA, https://www.youtube.com/watch?v=hHQqFGpod14, https://www.youtube.com/watch?v=jpt3Md9aDIQ
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class EightColumn_ListAdapter extends ArrayAdapter<Prescription> {
private LayoutInflater mInflater;
private ArrayList<Prescription> prescriptions;
private int mViewResourceId;
public EightColumn_ListAdapter(Context context, int textViewResourceId, ArrayList<Prescription> prescriptions) {
super(context, textViewResourceId, prescriptions);
this.prescriptions = prescriptions;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mViewResourceId = textViewResourceId;
}
public View getView(int position, View convertView, ViewGroup parents) {
convertView = mInflater.inflate(mViewResourceId, null);
Prescription prescription = prescriptions.get(position);
if (prescription != null) {
TextView patientID = (TextView) convertView.findViewById(R.id.textpatientID);
TextView date = (TextView) convertView.findViewById(R.id.textdate);
TextView drugname = (TextView) convertView.findViewById(R.id.textdrugname);
TextView concentration = (TextView) convertView.findViewById(R.id.textcontentration);
TextView dosage = (TextView) convertView.findViewById(R.id.textdosage);
TextView prep = (TextView) convertView.findViewById(R.id.textprep);
TextView startdate = (TextView) convertView.findViewById(R.id.textstartdate);
TextView enddate = (TextView) convertView.findViewById(R.id.textenddate);
TextView doctorID = (TextView) convertView.findViewById(R.id.textdoctorid);
if(patientID != null) {
patientID.setText((prescription.getPatientID()));
}
if(date != null) {
date.setText((prescription.getPresdate()));
}
if(drugname != null) {
drugname.setText((prescription.getDrugname()));
}
if(concentration != null) {
concentration.setText((prescription.getConcentration()));
}
if(dosage != null) {
dosage.setText((prescription.getDosage()));
}
if(prep != null) {
prep.setText((prescription.getPreparation()));
}
if(startdate != null) {
startdate.setText((prescription.getStartdate()));
}
if(enddate != null) {
enddate.setText((prescription.getEnddate()));
}
if(doctorID != null) {
patientID.setText((prescription.getDoctorID()));
}
}
return convertView;
}
}
You are trying to read the elements of your list called listItem . That list is null because you never set it to anything else.
Change this:
ArrayList<String> listItem;
to this:
ArrayList<String> listItem = new ArrayList<String>();
... or you can put it in your onCreate() method, just as you did with prescriptionList :
prescriptionList = new ArrayList<Prescription>();
listItem = new ArrayList<String>();
Also, don't name your list listItem because it is not an item... it is a list!
I am building an app that populates a ListView with a single random record from a SQLite DB every time I click on a "next" button for a guessing-style game. Currently I am able to pull a random record from the DB when the app opens, however, I do not know if I need a new class and I do not know where to put the code for the "next" button, nor do I know what the code should be. I'm basically trying to get the app to refresh the ListView with a new single random record from the DB every time someone clicks on a button that says "next". I already have the xml layout done and the app opens and displays the first random record perfectly. Thank you for any help! :)
MainActivity class:
package com.example.derek.guessinggame;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.Menu;
import android.view.MenuInflater;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fragmentManager = getSupportFragmentManager();
if (fragmentManager.findFragmentById(android.R.id.content) == null) {
GuessListFragment guessListFragment = new GuessListFragment();
fragmentManager.beginTransaction().add(android.R.id.content, guessListFragment).commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
ContentProvider class:
package com.example.derek.guessinggame;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;
public class GuessProvider extends ContentProvider {
private GuessDatabase mOpenHelper;
private static final String TAG = GuessProvider.class.getSimpleName();
private static final UriMatcher sUriMatcher = buildUriMatcher();
private static final int GUESS = 100;
private static final int GUESS_ID = 101;
private Uri uri;
private String selection;
private String[] selectionArgs;
private static UriMatcher buildUriMatcher() {
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = GuessContract.CONTENT_AUTHORITY;
matcher.addURI(authority, "guess", GUESS);
matcher.addURI(authority, "guess/*", GUESS_ID);
return matcher;
}
#Override
public boolean onCreate() {
mOpenHelper = new GuessDatabase(getContext());
return true;
}
private void deleteDatabase() {
mOpenHelper.close();
GuessDatabase.deleteDatabase(getContext());
mOpenHelper = new GuessDatabase(getContext());
}
#Override
public String getType(Uri uri) {
final int match = sUriMatcher.match(uri);
switch (match) {
case GUESS:
return GuessContract.Guess.CONTENT_TYPE;
case GUESS_ID:
return GuessContract.Guess.CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
final int match = sUriMatcher.match(uri);
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(GuessDatabase.Tables.GUESS);
switch (match) {
case GUESS:
// do nothing
break;
case GUESS_ID:
String id = GuessContract.Guess.getGuessId(uri);
queryBuilder.appendWhere(BaseColumns._ID + "=" + id);
break;
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
return cursor;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
Log.v(TAG, "insert(uri=" + uri + ", values=" + values.toString());
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
switch (match) {
case GUESS:
long recordId = db.insertOrThrow(GuessDatabase.Tables.GUESS, null, values);
return GuessContract.Guess.buildGuessUri(String.valueOf(recordId));
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Log.v(TAG, "update(uri=" + uri + ", values=" + values.toString());
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
String selectionCriteria = selection;
switch (match) {
case GUESS:
// do nothing
break;
case GUESS_ID:
String id = GuessContract.Guess.getGuessId(uri);
selectionCriteria = BaseColumns._ID + "=" + id
+ (!TextUtils.isEmpty(selection) ? " AND (" + selection + ")" : "");
break;
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
return db.update(GuessDatabase.Tables.GUESS, values, selectionCriteria, selectionArgs);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
Log.v(TAG, "delete(uri=" + uri);
if (uri.equals(GuessContract.BASE_CONTENT_URI)) {
deleteDatabase();
return 0;
}
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
switch (match) {
case GUESS_ID:
String id = GuessContract.Guess.getGuessId(uri);
String selectionCriteria = BaseColumns._ID + "=" + id
+ (!TextUtils.isEmpty(selection) ? " AND (" + selection + ")" : "");
return db.delete(GuessDatabase.Tables.GUESS, selectionCriteria, selectionArgs);
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
}
}
ListLoader class:
package com.example.derek.guessinggame;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.support.v4.content.AsyncTaskLoader;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class GuessListLoader extends AsyncTaskLoader<List<Guess>> {
private static final String LOG_TAG = GuessListLoader.class.getSimpleName();
private List<Guess> mGuess;
private ContentResolver mContentResolver;
private Cursor mCursor;
public GuessListLoader(Context context, Uri uri, ContentResolver contentResolver) {
super(context);
mContentResolver = contentResolver;
}
#Override
public List<Guess> loadInBackground() {
String[] projection = {BaseColumns._ID,
GuessContract.GuessColumns.GUESS_TITLE,
GuessContract.GuessColumns.GUESS_ANSWER,
GuessContract.GuessColumns.GUESS_HINT1,
GuessContract.GuessColumns.GUESS_HINT2,
GuessContract.GuessColumns.GUESS_HINT3,
GuessContract.GuessColumns.GUESS_HINT4,
GuessContract.GuessColumns.GUESS_HINT5};
List<Guess> entries = new ArrayList<Guess>();
mCursor = mContentResolver.query(GuessContract.URI_TABLE, projection, null, null, " random()");
if (mCursor != null) {
if (mCursor.moveToFirst()) {
do {
int _id = mCursor.getInt(mCursor.getColumnIndex(BaseColumns._ID));
String title = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_TITLE));
String answer = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_ANSWER));
String hint1 = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_HINT1));
String hint2 = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_HINT2));
String hint3 = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_HINT3));
String hint4 = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_HINT4));
String hint5 = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_HINT5));
Guess guess = new Guess(_id, title, answer, hint1, hint2, hint3, hint4, hint5);
entries.add(guess);
} while (mCursor.isLast());
}
}
return entries;
}
#Override
public void deliverResult(List<Guess> guess) {
if (isReset()) {
if (guess != null) {
mCursor.close();
}
}
List<Guess> oldGuessList = mGuess;
if (mGuess == null || mGuess.size() == 0) {
Log.d(LOG_TAG, "++++++++ No data returned");
}
mGuess = guess;
if (isStarted()) {
super.deliverResult(guess);
}
if (oldGuessList != null && oldGuessList != guess) {
mCursor.close();
}
}
#Override
protected void onStartLoading() {
if (mGuess != null) {
deliverResult(mGuess);
}
if (takeContentChanged() || mGuess == null) {
forceLoad();
}
}
#Override
protected void onStopLoading() {
cancelLoad();
}
#Override
protected void onReset() {
onStopLoading();
if (mCursor != null) {
mCursor.close();
}
mGuess = null;
}
#Override
public void onCanceled(List<Guess> guess) {
super.onCanceled(guess);
if (mCursor != null) {
mCursor.close();
}
}
#Override
public void forceLoad() {
super.forceLoad();
}
}
ListFragment class:
package com.example.derek.guessinggame;
import android.content.ContentResolver;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import java.util.List;
public class GuessListFragment extends ListFragment
implements LoaderManager.LoaderCallbacks<List<Guess>> {
private static final String LOG_TAG = GuessListFragment.class.getSimpleName();
private GuessCustomAdapter mAdapter;
private static final int LOADER_ID = 1;
private ContentResolver mContentResolver;
private List<Guess> mGuess;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mContentResolver = getActivity().getContentResolver();
mAdapter = new GuessCustomAdapter(getActivity(), getChildFragmentManager());
setEmptyText("No entries");
setListAdapter(mAdapter);
setListShown(false);
getLoaderManager().initLoader(LOADER_ID, null, this);
}
#Override
public Loader<List<Guess>> onCreateLoader(int id, Bundle args) {
mContentResolver = getActivity().getContentResolver();
return new GuessListLoader(getActivity(), GuessContract.URI_TABLE, mContentResolver);
}
#Override
public void onLoadFinished(Loader<List<Guess>> loader, List<Guess> guess) {
mAdapter.setData(guess);
mGuess = guess;
if(isResumed()) {
setListShown(true);
} else {
setListShownNoAnimation(true);
}
}
#Override
public void onLoaderReset(Loader<List<Guess>> loader) {
mAdapter.setData(null);
}
}
SQLiteOpenHelper class:
package com.example.derek.guessinggame;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
public class GuessDatabase extends SQLiteOpenHelper {
private static final String TAG = GuessDatabase.class.getSimpleName();
private static final String DATABASE_NAME = "guess.db";
private static final int DATABASE_VERSION = 2;
private final Context mContext;
interface Tables {
String GUESS = "guess";
}
public GuessDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + Tables.GUESS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ GuessContract.GuessColumns.GUESS_TITLE + " TEXT NOT NULL,"
+ GuessContract.GuessColumns.GUESS_ANSWER + " TEXT NOT NULL,"
+ GuessContract.GuessColumns.GUESS_HINT1 + " TEXT NOT NULL,"
+ GuessContract.GuessColumns.GUESS_HINT2 + " TEXT NOT NULL,"
+ GuessContract.GuessColumns.GUESS_HINT3 + " TEXT NOT NULL,"
+ GuessContract.GuessColumns.GUESS_HINT4 + " TEXT NOT NULL,"
+ GuessContract.GuessColumns.GUESS_HINT5 + " TEXT NOT NULL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
int version = oldVersion;
if (version == 1) {
version = 2;
}
if (version != DATABASE_VERSION) {
db.execSQL("DROP TABLE IF EXISTS " + Tables.GUESS);
onCreate(db);
}
}
public static void deleteDatabase(Context context) {
context.deleteDatabase(DATABASE_NAME);
}
}
ArrayAdapter class:
package com.example.derek.guessinggame;
import android.content.Context;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class GuessCustomAdapter extends ArrayAdapter<Guess> {
private LayoutInflater mLayoutInflater;
private static FragmentManager sFragmentManager;
public GuessCustomAdapter(Context context, FragmentManager fragmentManager) {
super(context, android.R.layout.simple_expandable_list_item_2);
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
sFragmentManager = fragmentManager;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final View view;
if (convertView == null) {
view = mLayoutInflater.inflate(R.layout.custom_guess, parent, false);
} else {
view = convertView;
}
final Guess guess = getItem(position);
final int _id = guess.getId();
final String title = guess.getTitle();
final String answer = guess.getAnswer();
final String hint1 = guess.getHint1();
final String hint2 = guess.getHint2();
final String hint3 = guess.getHint3();
final String hint4 = guess.getHint4();
final String hint5 = guess.getHint5();
((TextView) view.findViewById(R.id.guess_title)).setText(title);
((TextView) view.findViewById(R.id.guess_answer)).setText(answer);
((TextView) view.findViewById(R.id.guess_hint1)).setText(hint1);
((TextView) view.findViewById(R.id.guess_hint2)).setText(hint2);
((TextView) view.findViewById(R.id.guess_hint3)).setText(hint3);
((TextView) view.findViewById(R.id.guess_hint4)).setText(hint4);
((TextView) view.findViewById(R.id.guess_hint5)).setText(hint5);
return view;
}
public void setData(List<Guess> guesses) {
clear();
if (guesses != null) {
for (Guess guess : guesses) {
add(guess);
}
}
}
}
Contract class:
package com.example.derek.guessinggame;
import android.net.Uri;
import android.provider.BaseColumns;
public class GuessContract {
interface GuessColumns{
String GUESS_ID = "_id";
String GUESS_TITLE = "guess_title";
String GUESS_ANSWER = "guess_answer";
String GUESS_HINT1 = "guess_hint1";
String GUESS_HINT2 = "guess_hint2";
String GUESS_HINT3 = "guess_hint3";
String GUESS_HINT4 = "guess_hint4";
String GUESS_HINT5 = "guess_hint5";
}
public static final String CONTENT_AUTHORITY = "com.example.derek.guessinggame.provider";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
private static final String PATH_GUESS = "guess";
public static final Uri URI_TABLE = Uri.parse(BASE_CONTENT_URI.toString() + "/" + PATH_GUESS);
public static final String[] TOP_LEVEL_PATHS = {
PATH_GUESS
};
public static class Guess implements GuessColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendEncodedPath(PATH_GUESS).build();
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd." + CONTENT_AUTHORITY + ".guess";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd." + CONTENT_AUTHORITY + ".guess";
public static Uri buildGuessUri(String guessId) {
return CONTENT_URI.buildUpon().appendEncodedPath(guessId).build();
}
public static String getGuessId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
}
Getters and Setter class:
package com.example.derek.guessinggame;
public class Guess {
private int _id;
private String title;
private String answer;
private String hint1;
private String hint2;
private String hint3;
private String hint4;
private String hint5;
public Guess(int _id, String title, String answer, String hint1, String hint2, String hint3, String hint4, String hint5) {
this._id = _id;
this.title = title;
this.answer = answer;
this.hint1 = hint1;
this.hint2 = hint2;
this.hint3 = hint3;
this.hint4 = hint4;
this.hint5 = hint5;
}
public int getId() {
return _id;
}
public void setId(int _id) {
this._id = _id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public String getHint1() {
return hint1;
}
public void setHint1(String hint1) {
this.hint1 = hint1;
}
public String getHint2() {
return hint2;
}
public void setHint2(String hint2) {
this.hint2 = hint2;
}
public String getHint3() {
return hint3;
}
public void setHint3(String hint3) {
this.hint3 = hint3;
}
public String getHint4() {
return hint4;
}
public void setHint4(String hint4) {
this.hint4 = hint4;
}
public String getHint5() {
return hint5;
}
public void setHint5(String hint5) {
this.hint5 = hint5;
}
}