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)
Related
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'm developing a contacts app with a photo. I have Store and retrieve data from SQLite and it's working fine on my list view.
The problem is when I click a list item from it's supposed to show an image view and few other details. but the image is not showing on the Activity
List View on Main Activity
In the empty space here should be an image of the contacts
UserDBHelper.java
package com.example.arif.contacts;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
public class UserDBHelper extends SQLiteOpenHelper {
String TAG = "DEBUG";
private static final String DATABASE_NAME = "USERINFO.DB";
private static final String TABLE_NAME = "ContactTable";
private static final String TABLE_COL_NAME = "NAME";
private static final String TABLE_COL_MOB = "MOB";
private static final String TABLE_COL_EMAIL = "EMAIL";
private static final String TABLE_COL_IMG = "EMAIL";
private static final String TABLE_COL_ID = "ID";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY =
"CREATE TABLE "+TABLE_NAME+"("+TABLE_COL_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+TABLE_COL_NAME+" TEXT, "+TABLE_COL_MOB+" TEXT, "+TABLE_COL_EMAIL+" TEXT, "+TABLE_COL_IMG+" blob)" ;
public UserDBHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.e("DataBase", "Database created / Opened");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.e("DataBase", "Table Created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public boolean AddInfo(String Name, String Mob , String Email, byte[] img )
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues CV = new ContentValues();
CV.put("NAME", Name);
CV.put("MOB", Mob);
CV.put("EMAIL", Email );
CV.put("NewImage", img);
long result = db.insert(TABLE_NAME, null,CV);
Log.e("DataBase", "Add Info Bug");
if(result == -1)
{
return false;
}
else
{
return true;
}
}
public Cursor getInformation()
{
Cursor data;
SQLiteDatabase db = this.getWritableDatabase();
String query = "Select * from " + TABLE_NAME;
data = db.rawQuery(query,null);
return data;
}
public String fetch_Name(int i)
{
String Str = "";
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select "+TABLE_COL_NAME+" FROM " + TABLE_NAME + " WHERE " +TABLE_COL_ID+" = "+i;
Cursor data = db.rawQuery(query,null);
if(data.moveToFirst())
{
Str = data.getString(data.getColumnIndex(TABLE_COL_NAME+""));
}
return Str;
}
public String fetch_MOB(int i)
{
String Str = "";
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select "+TABLE_COL_MOB+" FROM " + TABLE_NAME + " WHERE " +TABLE_COL_ID+" = "+i;
Cursor data = db.rawQuery(query,null);
if(data.moveToFirst())
{
Str = data.getString(data.getColumnIndex(TABLE_COL_MOB+""));
}
return Str;
}
public String fetch_Email(int i)
{
String Str = "";
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select "+TABLE_COL_EMAIL+" FROM " + TABLE_NAME + " WHERE " +TABLE_COL_ID+" = "+i;
Cursor data = db.rawQuery(query,null);
if(data.moveToFirst())
{
Str = data.getString(data.getColumnIndex(TABLE_COL_EMAIL+""));
}
return Str;
}
public Bitmap fetch_Img(int i) { /// THIS FUNCTION IS NOT WORKING
byte[] ImgByte;
SQLiteDatabase db = this.getWritableDatabase();
String query = "Select "+TABLE_COL_IMG+" FROM " + TABLE_NAME + " WHERE " +TABLE_COL_ID+" = "+i;
Cursor data = db.rawQuery(query,null);
if(data.moveToFirst())
{
ImgByte = data.getBlob(data.getColumnIndex(TABLE_COL_IMG+""));
Bitmap bitMAP = BitmapFactory.decodeByteArray(ImgByte, 0, ImgByte.length); // Here it's Always Returning Null
if(bitMAP == null)
{
Log.e( TAG, "Bitmap is null :/ ");
}
return bitMAP;
}
return null;
}
}
DetailsViewActivity
package com.example.arif.contacts;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class DetailsOfContacts extends AppCompatActivity {
int Pos;
TextView Name_View, Mob_View, Email_View;
ImageView Image_View;
UserDBHelper userDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_of_contacts);
//---- ---- Intend Bundle ---- ----
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
Pos = -1;
if(bundle != null)
{
Pos = bundle.getInt("Position");
}
Toast.makeText(getApplicationContext(), "Position "+ Pos,Toast.LENGTH_SHORT).show();
// ---- ---- Find View ---- ----
Name_View = (TextView) findViewById(R.id.DetName);
Mob_View = (TextView) findViewById(R.id.DetMob);
Email_View = (TextView) findViewById(R.id.DetEmail);
Image_View = (ImageView) findViewById(R.id.DetImg);
/// --- --- DataBase -----
UserDBHelper userDBHelper = new UserDBHelper(getApplicationContext());
Name_View.setText(userDBHelper.fetch_Name(Pos+1)); // Working Fine
Mob_View.setText(userDBHelper.fetch_MOB(Pos+1));// Working Fine
Email_View.setText(userDBHelper.fetch_Email(Pos+1));// Working Fine
Image_View.setImageBitmap(userDBHelper.fetch_Img(Pos+1)); // it's Not showing The image in activity
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.edit_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id ;
id = item.getItemId();
if(id == R.id.EditButt)
{
Toast.makeText(getApplicationContext(),"Edit Button Clicked", Toast.LENGTH_SHORT).show();
Intent I = new Intent(DetailsOfContacts.this, EditActivity.class);
startActivity(I);
return true;
}
return super.onOptionsItemSelected(item);
}
}
09-18 09:35:56.866 26144-26144/com.example.arif.contacts E/DEBUG: Bitmap is null :/
Column name of image and email are same
private static final String TABLE_COL_EMAIL = "EMAIL";
private static final String TABLE_COL_IMG = "EMAIL";
Change column name of image.
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.
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;
}
}
I am making an application and I have made a class setup email.java in which I am saving the values entered by the user in sqlite database.But the class is not able to load and it is saying that:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.astrada/com.example.astrada.Setupemail}:
java.lang.InstantiationException: can't instantiate class com.example.astrada.Setupemail; no empty constructor
Here is my code:
package com.example.astrada;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.example.astrada.R;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Setupemail extends Activity implements OnClickListener {
EditText editEmail, editPhon1, editPhon2, editphone3, editphone4, uname,
useraddress;
TextView TitleInfo;
Button save;
SqlOpenHelper mHelper;
Cursor mCursor;
SimpleCursorAdapter mAdapter;
private final Context context;
private SqlOpenHelper DBHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "databaseofuser.db";
private static final String DATABASE_TABLE = "usertable";
private static final int DATABASE_VERSION = 1;
public static final String EMAIL_COLUMN = "email";
public static final String PHONE1_COLUMN = "phon1";
public static final String PHONE2_COLUMN = "phon2";
public static final String PHONE3_COLUMN = "phon3";
public static final String PHONE4_COLUMN = "phon4";
public static final String UNAME_COLUMN = "phon4";
public static final String UADDR_COLUMN = "phon4";
private static final String DATABASE_CREATE = "create table "
+ DATABASE_TABLE + " (" + EMAIL_COLUMN + "," + PHONE1_COLUMN + ","
+ PHONE2_COLUMN + "," + PHONE3_COLUMN + "," + PHONE4_COLUMN + ","
+ UNAME_COLUMN + "," + UADDR_COLUMN + ");";
public Setupemail(Context ctx) {
this.context = ctx;
DBHelper = new SqlOpenHelper(context);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setupemail);
editEmail = (EditText) this.findViewById(R.id.editEmail);
editPhon1 = (EditText) this.findViewById(R.id.editPhon1);
editPhon2 = (EditText) this.findViewById(R.id.editPhon2);
editphone3 = (EditText) this.findViewById(R.id.editPhon3);
editphone4 = (EditText) this.findViewById(R.id.editPhon3);
uname = (EditText) this.findViewById(R.id.nameofuser);
useraddress = (EditText) this.findViewById(R.id.addressofuser);
editPhon1.append("+91");
editPhon2.append("+91");
editphone3.append("+91");
editphone4.append("+91");
mHelper = new SqlOpenHelper(this);
save = (Button) this.findViewById(R.id.btnSaveData);
save.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String email, phon1, phon2, phon3, phon4;
boolean isEntryValid, isPhon1Valid, isPhone2Valid;
if (v == save) {
email = editEmail.getText().toString();
phon1 = editPhon1.getText().toString();
phon2 = editPhon2.getText().toString();
phon3 = editphone3.getText().toString();
phon4 = editphone4.getText().toString();
if (isEmailIdValid(email) && isPhoneValid(phon1)
&& isPhoneValid(phon2)) {
if (phon1.equals(phon2) || phon1.equals(phon3)
|| phon1.equals(phon4) || phon2.equals(phon3)
|| phon2.equals(phon4) || phon3.equals(phon4)) {
Toast.makeText(getApplicationContext(),
" Can't enter same numbers!!", Toast.LENGTH_LONG)
.show();
} else {
// /Saveinto DB
ContentValues cv = new ContentValues();
cv.put(EMAIL_COLUMN, editEmail.getText().toString());
cv.put(PHONE1_COLUMN, editPhon1.getText().toString());
cv.put(PHONE2_COLUMN, editPhon2.getText().toString());
cv.put(PHONE3_COLUMN, editphone3.getText().toString());
cv.put(UNAME_COLUMN, uname.getText().toString());
cv.put(UADDR_COLUMN, useraddress.getText().toString());
mDb.insert(DATABASE_TABLE, null, cv);
mCursor.requery();
mAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Good Job!!",
Toast.LENGTH_LONG).show();
}
} else {
String x = "Invalid Entry!!\nProvide Information Properly..";
Toast.makeText(getApplicationContext(), x, Toast.LENGTH_LONG)
.show();
editEmail.setText("");
}
}
// TODO Auto-generated method stub
}
private boolean isPhoneValid(String phon) {
final Pattern pattern = Pattern.compile(
"^([\\+](91))?([7-9]{1})([0-9]{9})$", Pattern.CASE_INSENSITIVE
| Pattern.MULTILINE);
Matcher match = pattern.matcher(phon);
if (match.matches()) {
return true;
} else {
return false;
}
}
private boolean isEmailIdValid(String Email) {
boolean isValid = false;
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = Email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
public class SqlOpenHelper extends SQLiteOpenHelper {
public SqlOpenHelper() {
super(context, null, null, 0);
}
public SqlOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION, null);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);
}
public SQLiteOpenHelper open() throws SQLException {
mDb = DBHelper.getWritableDatabase();
return this;
}
public void colse() {
DBHelper.close();
}
public long insertContact(String email, String phon1, String phon2,
String phon3, String phon4, String name, String address) {
ContentValues initialValues = new ContentValues();
initialValues.put(EMAIL_COLUMN, email);
initialValues.put(PHONE1_COLUMN, phon1);
initialValues.put(PHONE2_COLUMN, phon2);
initialValues.put(PHONE3_COLUMN, phon3);
initialValues.put(PHONE4_COLUMN, phon4);
initialValues.put(UNAME_COLUMN, name);
initialValues.put(UADDR_COLUMN, address);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("TaskDBAdapter", "Upgrading from version" + oldVersion
+ " to " + newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new
// version. Multiple previous versions can be handled by
// comparing oldVersion and newVersion values.
// The simplest case is to drop the old table and create a new one.
db.execSQL("DROP TABLE IF IT EXISTS " + DATABASE_TABLE);
// Create a new one.
onCreate(db);
}
}
}
Activity should not have constructor! All should be done in lifecycle callbacks. Move content from ctor to onCreate() and remove ctor:
public Setupemail(Context ctx) {
this.context = ctx;
DBHelper = new SqlOpenHelper(context);
}
Drop this:
public Setupemail(Context ctx) {
this.context = ctx;
DBHelper = new SqlOpenHelper(context);
}
and delete context field. Setupemail class is inherited from Activity, it's a subclass of Context itself. If you want to reference Context you can use getBaseContext in inner class or even omit it at the Setupemail class.
you don't have an empty constructor. It needs to be defined when you define the other constructors
public Setupmail()
{
}