Can't instantiate Class and no empty constructor error - java

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()
{
}

Related

Insert data using content provider in android studio

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) 

why db.insertWithOnConflict return -1 here?

In this activity, we can enter information of a school's test, and add it to others one.
Test.java :
package com.example.amirmasoudfallahi.testcorrector;
import android.content.ContentValues;
import android.database.Cursor;
/**
* Created by AmirMasoud Fallahi on 11/18/2017.
*/
public class Test {
public static final String KEY_ID = "testID";
public static final String KEY_NAME = "testName";
public static final String KEY_SCHOOL_NAME = "schName";
public static final String KEY_QUESTION_NUM = "quesNum";
public static final String KEY_PARTICIPANT_NUM = "participantNum";
public static final String KEY_QUALITY_MARK = "qualityMark";
public static final String KEY_LESSON_NUM = "lessonNum";
private int testID;
private String testName;
private String schName;
private int quesNum;
private int participantNum;
private float qualityMark = 0;
private int lessonNum;
public int getLessonNum() {
return lessonNum;
}
public void setLessonNum(int lessonNum) {
this.lessonNum = lessonNum;
}
public String getName() {
return testName;
}
public void setName(String name) {
this.testName = name;
}
public String getSchName() {
return schName;
}
public void setSchName(String schName) {
this.schName = schName;
}
public int getQuesNum() {
return quesNum;
}
public void setQuesNum(int quesNum) {
this.quesNum = quesNum;
}
public int getParticipantNum() {
return participantNum;
}
public void setParticipantNum(int participantNum) {
this.participantNum = participantNum;
}
public float getQualityMark() {
return qualityMark;
}
public void setQualityMark(float qualityMark) {
this.qualityMark = qualityMark;
}
public int getId() {
return testID;
}
public void setId(int id) {
this.testID = id;
}
#Override
public String toString() {
return testName;
}
public ContentValues getContentValuesForDb(){
ContentValues values = new ContentValues();
values.put(Test.KEY_ID, testID);
values.put(Test.KEY_NAME, testName);
values.put(Test.KEY_SCHOOL_NAME, schName);
values.put(Test.KEY_QUESTION_NUM, quesNum);
values.put(Test.KEY_LESSON_NUM, lessonNum);
values.put(Test.KEY_QUALITY_MARK, qualityMark);
values.put(Test.KEY_PARTICIPANT_NUM, participantNum);
return values;
}
public static Test cursorToTest(Cursor cursor){
Test test = new Test();
test.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)));
test.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
test.setQuesNum(cursor.getInt(cursor.getColumnIndex(KEY_QUESTION_NUM)));
test.setParticipantNum(cursor.getInt(cursor.getColumnIndex(KEY_PARTICIPANT_NUM)));
test.setSchName(cursor.getString(cursor.getColumnIndex(KEY_SCHOOL_NAME)));
test.setQualityMark(cursor.getInt(cursor.getColumnIndex(KEY_QUALITY_MARK)));
test.setLessonNum(cursor.getInt(cursor.getColumnIndex(KEY_LESSON_NUM)));
return test;
}
}
TestDbHelper.java :
package com.example.amirmasoudfallahi.testcorrector;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Created by AmirMasoud Fallahi on 11/20/2017.
*/
public class TestDBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "test-db";
private static final int DB_VERSION = 1;
public static final String TABLE_TESTS = "tb_tests";
private static final String CMD =
"CREATE TABLE IF NOT EXISTS '" + TABLE_TESTS + "' ('" +
Test.KEY_ID + "' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, '" +
Test.KEY_NAME + "' TEXT, '" +
Test.KEY_SCHOOL_NAME + "' TEXT, '" +
Test.KEY_QUESTION_NUM + "' INTEGER, '" +
Test.KEY_LESSON_NUM + "' INTEGER, '" +
Test.KEY_QUALITY_MARK + "' REAL, '" +
Test.KEY_PARTICIPANT_NUM + "' INTEGER " +
")";
private static final String[] allColumns = {Test.KEY_ID, Test.KEY_NAME, Test.KEY_SCHOOL_NAME,
Test.KEY_QUESTION_NUM, Test.KEY_PARTICIPANT_NUM, Test.KEY_QUALITY_MARK, Test.KEY_LESSON_NUM};
public TestDBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CMD);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TESTS);
onCreate(db);
}
public void insetItem(Test test) {
// if(getTests(Test.KEY_ID + " = " + test.getId()).isEmpty()) {
SQLiteDatabase db = getWritableDatabase();
long insertId = db.insertWithOnConflict(TABLE_TESTS, null, test.getContentValuesForDb(), SQLiteDatabase.CONFLICT_REPLACE);
if(insertId == -1) {
Log.i("TestDbHelper", "data insertion failed. (item : " + test.toString() + ")");
} else {
Log.i("TestDbHelper", "data inserted with id : " + insertId);
}
if(db.isOpen()) db.close();
// }
}
public List<Test> getTests(String selection){
SQLiteDatabase db = getReadableDatabase();
List<Test> testList = new ArrayList<>();
Cursor cursor = db.query(TABLE_TESTS, allColumns, selection, null, null, null, null);
if(cursor.moveToFirst()){
do{
Test test = Test.cursorToTest(cursor);
testList.add(test);
} while (cursor.moveToNext());
}
cursor.close();
if(db.isOpen()) db.close();
return testList;
}
}
DefineTestActivity.java :
package com.example.amirmasoudfallahi.testcorrector;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class DefineTestActivity extends AppCompatActivity {
TestDBHelper dbHelper;
EditText inputTestName, inputSchName, inputPrtNum, inputQuesNum, inputLessNum;
Button subTest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_define_test);
dbHelper = new TestDBHelper(this);
inputTestName = (EditText) findViewById(R.id.txt_testNameIn);
inputSchName = (EditText) findViewById(R.id.txt_schNameIn);
inputPrtNum = (EditText) findViewById(R.id.txt_prtcpntNumIn);
inputQuesNum = (EditText) findViewById(R.id.txt_testQuesNumIn);
inputLessNum = (EditText) findViewById(R.id.txt_lessNum);
subTest = (Button) findViewById(R.id.btn_createTestSubmit);
subTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Test test = new Test();
test.setName(inputTestName.getText().toString().trim());
test.setSchName(inputSchName.getText().toString().trim());
test.setQuesNum(Integer.parseInt(inputQuesNum.getText().toString().trim()));
test.setParticipantNum(Integer.parseInt(inputPrtNum.getText().toString().trim()));
test.setLessonNum(Integer.parseInt(inputLessNum.getText().toString().trim()));
dbHelper.insetItem(test);
Intent intent = new Intent(DefineTestActivity.this, AnswerKeysActivity.class);
intent.putExtra("lessonNum", test.getLessonNum());
startActivity(intent);
}
});
}
}
Activity Preview:
[]
in this case, I'm entering information of new Test to be added to Tests list.
when I press the button it should add a new Test to test's table in database.
as you see, in this line it should add it:
dbHelper.insetItem(test);
is insert function, in this line:
long insertId = db.insertWithOnConflict(TABLE_TESTS, null, test.getContentValuesForDb(), SQLiteDatabase.CONFLICT_REPLACE);
it should add it and return a non -1 .
but it return -1, it shows our insertion did failed.
there is no errors. And I actually don't know why it get -1 and didn't insert the item in DB.
Can anyone solve this problem???
Make sure you have some appropriate constraint in your table, such as PRIMARY KEY or UNIQUE.
When inserting, add a value to this constrained column via ContentValues. If inserting the new row would violate some constraint, the conflicting rows are first deleted and then the new row is inserted.
In your case, COLUMN_ID looks like a good candidate for PRIMARY KEY constraint. The second arg nullColumnHack with value COLUMN_ID in your code is not necessary, you can pass it as null.

Why SQLite to ImageView, BitmapFactory.decodeByteArray Returning Null?

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.

How to populate ListView with SQLite database info with next button click

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;
}
}

Data not inserted into SQLite database on android?

I have developed an Android database application.
The problem is that when I click the add button then a message shows that data was successfully added.
But the data is not inserted into the database.
I then open the database with SQLite viewer and there I can't find any of the data I inserted...
Register page code :
package com.example.dbapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class Register extends Activity {
Button add;
TextView b,c;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
add = (Button) findViewById(R.id.btnReg);
b = (TextView) findViewById(R.id.etName);
c = (TextView) findViewById(R.id.etOccu);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
String name = b.getText().toString();
String occ = c.getText().toString();
DataCon entry = new DataCon(Register.this);
entry.open();
entry.createEntry(name, occ);
entry.close();
Toast toast = Toast.makeText(getApplicationContext(), "Sucess", Toast.LENGTH_SHORT);
toast.show();
}
catch(Exception e) {
String err = e.toString();
Toast toast = Toast.makeText(getApplicationContext(), err, Toast.LENGTH_SHORT);
toast.show();
}
}
});
}
Database Connection code :
package com.example.dbapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DataCon {
public static final String rowid = "_id";
public static final String name = "persons_name";
public static final String hot = "persons_hotness";
private static final String DB_NAME = "myDB";
private static final String DB_TABLE = "tbl_me";
private static final int DB_VER = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VER);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DB_TABLE + " (" + rowid +
" INTEGER PRIMARY KEY AUTOINCREMENT, " + name + "TEXT NOT NULL, " +
hot + " TEXT NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " +DB_TABLE);
onCreate(db);
}
}
public DataCon(Context c) {
ourContext = c;
}
public DataCon open() {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String name2, String occ) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(name, name2);
cv.put(hot, occ);
return ourDatabase.insert(DB_TABLE, null, cv);
}
}
Now how can I solve the problem? thanks
An error in your sql. You haven't provide space between column name and type. Correct one should be
db.execSQL("CREATE TABLE " + DB_TABLE + " (" + rowid +
" INTEGER PRIMARY KEY AUTOINCREMENT, " + name + " TEXT NOT NULL, " +
--------------------------- ^
hot + " TEXT NOT NULL);");`

Categories

Resources