why db.insertWithOnConflict return -1 here? - java

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.

Related

I'm having this error when I try to update/edit the Sqlite database java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 can any on help me

I'm having this error when I try to update/edit the Sqlite database java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 can any on helping me.
when I try to delete the existing data from the database it works. But when I try to update or edit the existing data from the database, it does not work and the app crashes.
when I check the database inspector then I find one thing that when I try to edit the table data on the database the Class_table will gone or you can say delete automatically. and I don't find any solution for this problem can anyone help me plz.
Here is the error code:
Process: com.example.attendance, PID: 20112
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at com.example.attendance.MainActivity.updateClass(MainActivity.java:135)
at com.example.attendance.MainActivity.lambda$showUpdateDialog$4$MainActivity(MainActivity.java:131)
at com.example.attendance.-$$Lambda$MainActivity$m9twlugKZZaVnr6kCG8LrRCoXMM.onClick(Unknown Source:4)
at com.example.attendance.MyDialog.lambda$getUpdateClassDialog$1$MyDialog(MyDialog.java:94)
at com.example.attendance.-$$Lambda$MyDialog$5v1iqgaO8riJO2phwUfadWXdoyM.onClick(Unknown Source:6)
at android.view.View.performClick(View.java:8160)
at android.widget.TextView.performClick(TextView.java:16222)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:8137)
at android.view.View.access$3700(View.java:888)
at android.view.View$PerformClick.run(View.java:30236)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8512)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
I/Process: Sending signal. PID: 20112 SIG: 9
Here is My Activity:
package com.example.attendance;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toolbar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
FloatingActionButton floatingActionButton;
RecyclerView recyclerView;
ClassAdapter classAdapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<ClassItem> classItems = new ArrayList<>();
Toolbar toolbar;
DbHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new DbHelper(this);
floatingActionButton = findViewById(R.id.fab_main);
floatingActionButton.setOnClickListener(V -> showDialog());
loadData();
recyclerView = findViewById(R.id.att_list);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
classAdapter = new ClassAdapter(this, classItems);
recyclerView.setAdapter(classAdapter);
classAdapter.setOnItemClickListener(position -> gotoItemActivity(position));
setToolbar();
}
private void loadData() {
Cursor cursor = dbHelper.getClassTable();
classItems.clear();
while (cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex(DbHelper.C_ID));
String department = cursor.getString(cursor.getColumnIndex(DbHelper.CLASS_NAME_KEY));
String subject = cursor.getString(cursor.getColumnIndex(DbHelper.SUBJECT_NAME_KEY));
classItems.add(new ClassItem(id,department,subject));
}
}
private void setToolbar() {
toolbar = findViewById(R.id.toolbar);
TextView title = toolbar.findViewById(R.id.tool_title);
TextView subTitle = toolbar.findViewById(R.id.tool_sub_title);
TextView samiTitle = toolbar.findViewById(R.id.tool_sami_title);
ImageButton back = toolbar.findViewById(R.id.tool_back);
ImageButton save = toolbar.findViewById(R.id.tool_save);
title.setText("Attendance");
subTitle.setVisibility(View.GONE);
samiTitle.setVisibility(View.GONE);
save.setVisibility(View.GONE);
back.setOnClickListener(v -> onBackPressed());
}
private void gotoItemActivity(int position) {
Intent intent = new Intent(this,StudentActivity.class);
intent.putExtra("departmentName",classItems.get(position).getDepartment());
intent.putExtra("subjectName",classItems.get(position).getSubject());
intent.putExtra("position",position);
startActivity(intent);
}
private void showDialog() {
MyDialog dialog = new MyDialog();
dialog.show(getSupportFragmentManager(),MyDialog.CLASS_ADD_DIALOG);
dialog.setListener((department,subject)->addClass(department,subject));
}
private void addClass(String department, String subject) {
long cid = dbHelper.addClass(department,subject);
ClassItem classItem = new ClassItem(cid,department,subject);
classItems.add(classItem);
classAdapter.notifyDataSetChanged();
}
#Override
public boolean onContextItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case 0:
showUpdateDialog(item.getGroupId());
case 1:
deleteClass(item.getGroupId());
}
return super.onContextItemSelected(item);
}
private void showUpdateDialog(int position) {
MyDialog updateDialog = new MyDialog();
updateDialog.show(getSupportFragmentManager(),MyDialog.CLASS_UPDATE_DIALOG);
updateDialog.setListener((department,subject)->updateClass(position,department,subject));
}
// when I try to Update the Data its don't work and the app will crash
private void updateClass(int position, String department, String subject) {
dbHelper.updateClass(classItems.get(position).getCid(),department,subject);
classItems.get(position).setDepartment(department);
classItems.get(position).setSubject(subject);
classAdapter.notifyItemChanged(position);
}
private void deleteClass(int position) {
dbHelper.deleteClass(classItems.get(position).getCid());
classItems.remove(position);
classAdapter.notifyItemRemoved(position);
}
}
Here is my Adepter
package com.example.attendance;
import android.content.Context;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ClassAdapter extends RecyclerView.Adapter<ClassAdapter.ClassViewHolder> {
private OnItemClickListener onItemClickListener;
public interface OnItemClickListener {
void onClick(int position);
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public ClassAdapter(Context context, ArrayList<ClassItem> classItems) {
this.classItems = classItems;
this.context = context;
}
ArrayList<ClassItem> classItems;
Context context;
public static class ClassViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
TextView department, subject;
public ClassViewHolder(#NonNull View itemView,OnItemClickListener onItemClickListener) {
super(itemView);
department = itemView.findViewById(R.id.dep_tv);
subject = itemView.findViewById(R.id.sub_tv);
itemView.setOnClickListener(v -> onItemClickListener.onClick(getAdapterPosition()));
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.add(getAdapterPosition(),0,0,"EDIT");
menu.add(getAdapterPosition(),1,0,"DELETE");
}
}
#NonNull
#Override
public ClassViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.class_item, parent, false);
return new ClassViewHolder(itemView, onItemClickListener);
}
#Override
public void onBindViewHolder(#NonNull ClassViewHolder holder, int position) {
holder.department.setText(classItems.get(position).getDepartment());
holder.subject.setText(classItems.get(position).getSubject());
}
#Override
public int getItemCount() {
return classItems.size();
}
}
Here is Database
package com.example.attendance;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class DbHelper extends SQLiteOpenHelper {
private static final int VERSION = 1;
//Class table
private static final String CLASS_TABLE_NAME= "CLASS_TABLE";
public static final String C_ID= "_CID";
public static final String CLASS_NAME_KEY= "CLASS_NAME";
public static final String SUBJECT_NAME_KEY= "SUBJECT_NAME";
private static final String CREATE_CLASS_TABLE=
"CREATE TABLE " + CLASS_TABLE_NAME + "(" +
C_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
CLASS_NAME_KEY + " TEXT NOT NULL, " +
SUBJECT_NAME_KEY + " TEXT NOT NULL, " +
" UNIQUE ( " + CLASS_NAME_KEY + "," + SUBJECT_NAME_KEY + ")" +
");";
private static final String DROP_CLASS_TABLE = "DROP TABLE IF EXISTS "+CLASS_TABLE_NAME;
private static final String SELECT_CLASS_TABLE = "SELECT * FROM "+CLASS_TABLE_NAME;
//Student table
private static final String STUDENT_TABLE_NAME= "STUDENT_TABLE";
private static final String S_ID= "_SID";
private static final String STUDENT_NAME_KEY= "STUDENT_NAME";
private static final String STUDENT_ROLL_KEY= "ROLL";
private static final String CREATE_STUDENT_TABLE=
"CREATE TABLE "+ STUDENT_TABLE_NAME +
"( "+
S_ID+ " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "+
C_ID + " TEXT NOT NULL, "+
STUDENT_NAME_KEY + " TEXT NOT NULL, "+
STUDENT_ROLL_KEY + " INTEGER, "+
" FOREIGN KEY ( "+C_ID+ " ) REFERENCES "+ CLASS_TABLE_NAME + "("+C_ID+")"+
");";
private static final String DROP_STUDENT_TABLE = "DROP TABLE IF EXISTS "+STUDENT_TABLE_NAME;
private static final String SELECT_STUDENT_TABLE = "SELECT * FROM "+STUDENT_TABLE_NAME;
//Status table
private static final String STATUS_TABLE_NAME= "STATUS_TABLE";
private static final String STATUS_ID= "_STATUS_ID";
private static final String DATE_KEY= "STATUS_NAME";
private static final String STATUS_KEY= "STATUS";
private static final String CREATE_STATUS_TABLE=
"CREATE TABLE "+STATUS_TABLE_NAME+
"("+
STATUS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "+
S_ID + " INTEGER NOT NULL, "+
DATE_KEY + " DATE NOT NULL, "+
STATUS_KEY + " TEXT NOT NULL, "+
" UNIQUE ( " + S_ID + "," + DATE_KEY + ")," +
" FOREIGN KEY ( "+ S_ID+ " ) REFERENCES "+ STUDENT_TABLE_NAME + "( "+S_ID+")"+
");";
private static final String DROP_STATUS_TABLE = "DROP TABLE IF EXISTS "+ STATUS_TABLE_NAME;
private static final String SELECT_STATUS_TABLE = "SELECT * FROM "+ STATUS_TABLE_NAME;
public DbHelper(#Nullable Context context) {
super(context, "Attendance.db", null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_CLASS_TABLE);
db.execSQL(CREATE_STUDENT_TABLE);
db.execSQL(CREATE_STATUS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_CLASS_TABLE);
db.execSQL(DROP_STUDENT_TABLE);
db.execSQL(DROP_STATUS_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
long addClass(String className,String subjectName){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CLASS_NAME_KEY,className);
values.put(SUBJECT_NAME_KEY,subjectName);
return database.insert(CLASS_TABLE_NAME,null,values);
}
Cursor getClassTable(){
SQLiteDatabase database = this.getReadableDatabase();
return database.rawQuery(SELECT_CLASS_TABLE,null);
}
int deleteClass(long cid){
SQLiteDatabase database = this.getReadableDatabase();
return database.delete(CLASS_TABLE_NAME,C_ID+"=?",new String[]{String.valueOf(cid)});
}
long updateClass(long cid,String className,String subjectName){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CLASS_NAME_KEY,className);
values.put(SUBJECT_NAME_KEY,subjectName);
return database.update(CLASS_TABLE_NAME,values,C_ID+"=?",new String[]{String.valueOf(cid)});
}
}
After dropping your tables, you forgot to create them again in your onUpgrade method.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_CLASS_TABLE);
db.execSQL(DROP_STUDENT_TABLE);
db.execSQL(DROP_STATUS_TABLE);
onCreate(db);
} catch (SQLException e) {
e.printStackTrace();
}
}
Also it is a good idea to call .close() method every time you call .getWritableDatabase() or .getReadableDatabase(). Here is an example ...
long addClass(String className, String subjectName){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CLASS_NAME_KEY,className);
values.put(SUBJECT_NAME_KEY,subjectName);
database.close();
long id = database.insert(CLASS_TABLE_NAME,null,values);
return id;
}
Hope it helps, happy coding!
The issue is in your MainActivity.class and StudentActivity.class.
In your onContextItemSelected(#NonNull MenuItem item) method, you forgot to break; your switch statement.
#Override
public boolean onContextItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case 0:
showUpdateDialog(item.getGroupId());
break;
case 1:
deleteClass(item.getGroupId());
break;
} return true;
}
Also, instead of adding classItems or studentItems to their respective ArrayLists after updating or deleting data in your SQLite Database, just call loadData() method again!
private void deleteClass(int position) {
dbHelper.deleteClass(classItems.get(position).getCid());
loadData();
classAdapter.notifyDataSetChanged();
}
private void updateClass(int position, String department, String subject) {
dbHelper.updateClass(classItems.get(position).getCid(),department,subject);
loadData();
classAdapter.notifyDataSetChanged();
}
The same thing applies to your StudentActivity.class. Happy Coding!

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

Android not displaying data from database

I created a very simple application which allows the user to save emergency information into a database and then displays it on a different screen. The information the user can save is first name, blood type, contact number, phone number and relationship type.
However the problem is that the application is not displaying all of the information. It is only displaying the first name. I believe the cursor is not moving onto the next row, so I think the problem is in the code below:
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
//Every Column and row
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
//Cursor points to a location in your results
//First row point here, second row point here
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
//Extracts first name and adds to string
if(c.getString(c.getColumnIndex("firstName"))!=null){
dbString += c.getString(c.getColumnIndex("firstName"));
c.moveToNext();
/*
* Displaying all other columns
*/
}
}
db.close();
return dbString;
}
Here is the full Code:
Database Class:
package com.example.androidsimpledbapp1;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;
public class MyDBHandler extends SQLiteOpenHelper {
/*
* Class for Working with DB
*/
//Update each time DB structure changes e.g. adding new property
private static final int DATABASE_VERSION = 1;
//DB Name
private static final String DATABASE_NAME = "details.db";
//Table name
public static final String TABLE_PRODUCTS = "products";
//DB Columns
public static final String COLUMN_ID = "_Id";
public static final String COLUMN_PERSONNAME = "firstName";
public static final String COLUMN_PERSONBLOOD = "bloodType";
public static final String COLUMN_PERSONCONTACT = "contactName";
public static final String COLUMN_PERSONNUMBER = "phoneNumber";
public static final String COLUMN_PERSONRELATION = "relationship";
//Constructor
/*
* Passing information to super class in SQL
* Context is background information
* name of db
* Database version
*/
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
/*
* What to do first time when you create DB
* Creates the table the very first time
* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
* Remember to use Commas as shown below
*/
#Override
public void onCreate(SQLiteDatabase db){
String query = "CREATE TABLE "+ TABLE_PRODUCTS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
COLUMN_PERSONNAME + " TEXT, "+
COLUMN_PERSONBLOOD + " TEXT, "+
COLUMN_PERSONCONTACT + " TEXT, "+
COLUMN_PERSONNUMBER + " TEXT, " +
COLUMN_PERSONRELATION + " TEXT " +
");";
//Execute the query
db.execSQL(query);
}
/*
* If ever upgrading DB call this method
* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
//Delete the current table
db.execSQL("DROP TABLE IF EXISTS" + TABLE_PRODUCTS);
//create new table
onCreate(db);
}
//Add new row to the database
public void addProduct(Details details){
//Built in class - set values for different columns
//Makes inserting rows quick and easy
ContentValues values = new ContentValues();
values.put(COLUMN_PERSONNAME, details.get_firstName());
values.put(COLUMN_PERSONBLOOD, details.get_bloodType());
values.put(COLUMN_PERSONCONTACT, details.get_contactName());
values.put(COLUMN_PERSONNUMBER, details.get_phoneNumber());
values.put(COLUMN_PERSONRELATION, details.get_relationship());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRODUCTS, null, values);
db.close();
}
/*Table was deleted*/
public void deleteProducts(){
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_PRODUCTS, null, null);
}
//Take DB and Convert to String
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
//Every Column and row
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
//Cursor points to a location in your results
//First row point here, second row point here
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
//Extracts first name and adds to string
if(c.getString(c.getColumnIndex("firstName"))!=null) {
dbString += c.getString(c.getColumnIndex("firstName"));
c.moveToNext();
/*
* Displaying all other columns
*/
}
}
db.close();
return dbString;
}
}
Details Class:
package com.example.androidsimpledbapp1;
public class Details {
//primary key
private int _id;
//Properties
private String _firstName;
private String _bloodType;
private String _contactName;
private String _phoneNumber;
private String _relationship;
//Dont Have to Enter Everything each time
public Details(){
}
public Details(String firstName){
this.set_firstName(firstName);
}
//Passing in details
//Setting values from the user
public Details(String firstName, String bloodType,
String contactName, String phoneNumber,
String relationship){
this.set_firstName(firstName);
this.set_bloodType(bloodType);
this.set_contactName(contactName);
this.set_phoneNumber(phoneNumber);
this.set_relationship(relationship);
}
//Retrieve the data
public int get_id() {
return _id;
}
//Setter allows to give property
public void set_id(int _id) {
this._id = _id;
}
public String get_firstName() {
return _firstName;
}
public void set_firstName(String _firstName) {
this._firstName = _firstName;
}
public String get_bloodType() {
return _bloodType;
}
public void set_bloodType(String _bloodType) {
this._bloodType = _bloodType;
}
public String get_contactName() {
return _contactName;
}
public void set_contactName(String _contactName) {
this._contactName = _contactName;
}
public String get_phoneNumber() {
return _phoneNumber;
}
public void set_phoneNumber(String _phoneNumber) {
this._phoneNumber = _phoneNumber;
}
public String get_relationship() {
return _relationship;
}
public void set_relationship(String _relationship) {
this._relationship = _relationship;
}
}
Edit Screen - The screen where the user adds the data into the DB, upon pressing save the all the database information should display on the main activity
package com.example.androidsimpledbapp1;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class EditScreen extends Activity {
EditText firstNameInput;
EditText bloodTypeInput;
EditText contacNameInput;
EditText phoneNumberInput;
EditText relationshipInput;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_screen);
//Setting EditTexts
firstNameInput = (EditText) findViewById(R.id.inputname);
bloodTypeInput = (EditText) findViewById(R.id.inputblood);
contacNameInput = (EditText) findViewById(R.id.inputcontact);
phoneNumberInput = (EditText) findViewById(R.id.inputnum);
relationshipInput = (EditText) findViewById(R.id.inputraltion);
//Setting DbHandler object
dbHandler = new MyDBHandler(this, null, null, 1);
}
public void saveMe(View v){
/*
* Making a new object
* Object takes 5 parameters
*/
Details detail = new Details(firstNameInput.getText().toString(),
bloodTypeInput.getText().toString(),
contacNameInput.getText().toString(),
phoneNumberInput.getText().toString(),
relationshipInput.getText().toString());
dbHandler.addProduct(detail);
//Sending Text To Main Activity
String dbString = dbHandler.databaseToString();
Intent myIntent = new Intent(v.getContext(),MainActivity.class);
myIntent.putExtra("mytext",dbString);
startActivity(myIntent);
//End of Sending to Main Activity
//Setting the text in Edit Text
firstNameInput.setText(dbString);
}
public void clearBtnPressed(View v){
dbHandler.deleteProducts();
}
}
MainActivity - This screen displays the data
package com.example.androidsimpledbapp1;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Grabs the TextView
mTextView = (TextView)findViewById(R.id.dbname);
mTextView.setText(getIntent().getStringExtra("mytext"));
}
//Changing Activity
public void editBtnPressed(View v){
Intent intent = new Intent(MainActivity.this, EditScreen.class);
startActivity(intent);
}
}

Can't instantiate Class and no empty constructor error

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

How to create a two table in single Database in Android Application?

I have Created a database in Sqllite Android Application and I tried to add two tables in my Database, but I have problem to create that Database. First Table only Created. Can anyBody help me?
package com.android.cdtech;
import java.sql.SQLException;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class saveData {
public static final String KEY_ROWID = "rowid"; public static final String KEY_DATE = "Date";public static final String KEY_NAME = "CustomerName";public static final String KEY_AMOUNT = "Amount";public static final String KEY_BANK = "Banks";
private static final String TAG = "DBAdapter";
public static final String KEY_BUSNAME="BusinessName";public static final String KEY_ADD="Address";public static final String KEY_CPERSON="ContactPerson";;
private static final String DATABASE_NAME = "EXPORTDETAILS";
private static final String DATABASE_TABLE = "Payment";
private static final String DATABASE_TABLE2 = "Customer";
private static final int DATABASE_VERSION = 1;
private static String DATABASE_CREATE =
"create table Payment (_id integer primary key autoincrement, "
+ "Date text not null,"+"CustomerName text not null,"+"Amount text not null,"+"Banks text not null);";
private static final String DATABASE_CREATECUS =
"create table Customer (_id integer primary key autoincrement, "
+ "BusinessName text not null,"+"Address text not null,"+"ContactPerson text not null,"+"PhoneNumber text not null,);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public saveData(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
db.execSQL(DATABASE_CREATECUS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS titles");
onCreate(db);
}
}
public saveData open()throws SQLException
{
db=DBHelper.getWritableDatabase();
return this;
}
public void close()
{
DBHelper.close();
}
public long insert(String Date,String CustomerName,String Amount,String Banks) {
// TODO Auto-generated method stub
ContentValues cv=new ContentValues();
cv.put(KEY_DATE,Date);
cv.put(KEY_NAME,CustomerName);
cv.put(KEY_AMOUNT,Amount);
cv.put(KEY_BANK,Banks);
return db.insert(DATABASE_TABLE, null,cv);
}
public long insertForm(String BusinessName ,String Address ,String ContactPerson) {
// TODO Auto-generated method stub
ContentValues cv=new ContentValues();
cv.put(KEY_BUSNAME,BusinessName);
cv.put(KEY_ADD,Address);
cv.put(KEY_CPERSON,ContactPerson);
}
public Cursor getlatlng()
{
Cursor latlngCursor = db.rawQuery("select * from " + DATABASE_TABLE,null);
if (latlngCursor != null)
{
latlngCursor.moveToFirst();
}
db.close();
return latlngCursor;
}
public Cursor order()
{
Cursor latlngCursor = db.rawQuery("select * from " + DATABASE_TABLE2,null);
if (latlngCursor != null)
{
latlngCursor.moveToFirst();
}
db.close();
return latlngCursor;
}
}
Error Code =1 No Such table for Customer
use below two class
package Your 'packagename';
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "BistroDB";
private static final int DATABASE_VERSION =1;
// Database creation sql statement
public static final String Table1= "create table table1name ("Your cloumns");";
public static final String Table2 = "create table table2name ("Your cloumns");";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method is called during creation of the database
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(table1);
database.execSQL(table2);
}
// Method is called during an upgrade of the database, e.g. if you increase
// the database version
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {
Log.w(DBHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS table1");
database.execSQL("DROP TABLE IF EXISTS table2");
onCreate(database);
}
public boolean deleteDatabase(Context context) {
return context.deleteDatabase(DATABASE_NAME);
}
}
Use below class to insert values into table
package 'Your package name';
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DataBaseAdapter {
// Database fields
private Context context;
private SQLiteDatabase database;
private DBHelper dbHelper;
public DataBaseAdapter(Context context) {
this.context = context;
}
public DataBaseAdapter open() throws SQLException {
dbHelper = new DBHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close() {
dbHelper.close();
}
public Cursor fetchAllTAble1data() {
return database.query("MenuData", new String[] { "id", "Title",
"Image", "Description" }, null, null, null, null, null);
}
public Cursor fetchAllTable2data() {
return database.query("RestaurantsData", new String[] {
"restaurant_id", "name", "phone", "email", "open_days",
"timing", "website", "loc_name", "street", "city", "longitude",
"latitude", "zip" }, null, null, null, null, null);
}
public void deleteTable(String tablename){
database.execSQL("drop table if exists "+tablename+';');
}
public void createIndividualTable(String query){
database.execSQL(query);
}
public void InsertTable1Data(TAble1 review) {
ContentValues values = new ContentValues();
values.put("Name", review.Name);
values.put("Email", review.Email);
values.put("Comment", review.Comment);
values.put("Rating", review.Rating);
database.insert("ReviewsData", null, values);
}
public void InsertTable2Data(TAble2 photos) {
ContentValues values = new ContentValues();
values.put("photo", photos.Photos);
database.insert("PhotosData", null, values);
}
public ContentValues createContentValues(String category, String summary,
String description) {
ContentValues values = new ContentValues();
return values;
}
}
Try removing the "," at the end of DATABASE_CREATECUS

Categories

Resources