I would like to check whether a record exists or not.If exist , i want to add the quantity.
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = etCode.getText().toString();
String product = etProduct.getText().toString();
String qty = etQty.getText().toString();
try {
if (isExist(code)) {
rQty = Integer.parseInt(rQty + etQty.getText().toString());
} else {
myDB.addData(code, product, Integer.parseInt(qty));
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
}
}
});
}
public boolean isExist(String code) {
boolean result;
SQLiteDatabase db = myDB.getReadableDatabase();
try {
Cursor cursor = db.rawQuery("SELECT QTY FROM users_data WHERE CODE " + code + "'", null);
if (cursor.getCount() > 0 ){
while (cursor.moveToFirst()){
rQty = cursor.getInt(cursor.getColumnIndex("QTY"));
}
result = true;
}else {
result = false;
}
}
catch (Exception ex){
result = false;
}
return result;
}
}
Here is the code.if insert the same code of item , the data become duplicate and it not add the quantity for the same code.Please help me to solve this problem .
There are multiple errors and bugs in your code. One problem is this code
rQty = Integer.parseInt(rQty + etQty.getText().toString());
It won't add qQty with input quantity. because here strings concatenated.
You have to use
rQty += Integer.parseInt (qty);
Second one is your sqlite query is not right and it is incomplete
so change
Cursor cursor = db.rawQuery("SELECT QTY FROM users_data WHERE CODE " + code + "'", null);
to
Cursor cursor = db.rawQuery("SELECT QTY FROM users_data WHERE CODE = '" + code + "'", null);
Try below code
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = etCode.getText().toString();
String product = etProduct.getText().toString();
String qty = etQty.getText().toString();
try {
if (isExist(code)) {
rQty += Integer.parseInt (qty);
} else {
myDB.addData(code, product, Integer.parseInt(qty));
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
}
}
});
}
public boolean isExist(String code) {
boolean result;
SQLiteDatabase db = myDB.getReadableDatabase();
try {
Cursor cursor = db.rawQuery("SELECT QTY FROM users_data WHERE CODE = '" + code + "'", null);
if (cursor.getCount() > 0 ){
while (cursor.moveToFirst()){
rQty = cursor.getInt(cursor.getColumnIndex("QTY"));
}
result = true;
}else {
result = false;
}
}
catch (Exception ex){
result = false;
}
return result;
}
Related
I'm having a problem with my code. I don't know how to check multiple columns in the database to insert different data on every not existing data.
For example:
1st input
Name: Raymond Jay Berin
Event: INTRAMURALS
FACILITATOR: CSG
2nd input
Name: Raymond Jay Berin
Event: LOVE SYMPOSIUM
FACILITATOR: DSSC
the thing here is that. Raymond Jay Berin already existed in the database, but I want Raymond Jay Berin will be inserted into a different event...
also, I already tried to create multiple tables but my project crashes when I click the attendance button to add data.
Code for DatabaseHelper.class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "attendance.sqlite";
public static final String TABLE_NAME = "attendance";
public static final String COL_1 = "ID";
public static final String COL_2 = "FULLNAME";
public static final String COL_EVENT_2 = "EVENT_NAME";
public static final String COL_EVENT_3 = "FACILITATOR_NAME";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
//ATTENDANCE
db.execSQL(" create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"FULLNAME TEXT NOT NULL, EVENT_NAME TEXT NOT NULL, FACILITATOR_NAME TEXT NOT NULL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//ATTENDANCE
db.execSQL(" DROP TABLE IF EXISTS "+TABLE_NAME );
//recreate
onCreate(db);
}
//ATTENDANCE
public boolean insertData (String fullname, String event, String facilitator){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,fullname);
contentValues.put(COL_EVENT_2,event);
contentValues.put(COL_EVENT_3,facilitator);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
public boolean checkIfRecordExist(String nameOfTable,String columnName,String columnValue) {
SQLiteDatabase db = null;
try {
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT "+columnName+" FROM "+nameOfTable+" WHERE "+columnName+"='"+columnValue+"'",null);
if (cursor.moveToFirst()) {
db.close();
Log.d("Record Already Exists", "Table is:" + nameOfTable + " ColumnName:" + columnName);
return true;//record Exists
}
Log.d("New Record ", "Table is:" + nameOfTable + " ColumnName:" + columnName + " Column Value:" + columnValue);
db.close();
} catch (Exception errorException) {
Log.d("Exception occured", "Exception occured " + errorException);
db.close();
}
return false;
} }
Code for the Attendance.java class
public class Attendance extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
DatabaseHelper myDb;
EditText fname , eventname, faciname;
Button attendance;
Button view;
Switch lock;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
myDb = new DatabaseHelper(this);
fname = findViewById(R.id.txtFullname);
eventname = findViewById(R.id.eventname);
faciname = findViewById(R.id.faciname);
attendance = findViewById(R.id.btnatt);
view = findViewById(R.id.btnview);
lock = findViewById(R.id.switchLock);
viewAll();
AddData();
lock.setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (lock.isChecked()){
eventname.setEnabled(false);
faciname.setEnabled(false);
}else{
eventname.setEnabled(true);
faciname.setEnabled(true);
}
}
public void viewAll() {
view.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = myDb.getAllData();
if (res.getCount() == 0) {
// show message
showMessage("Error", "Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("ID :" + res.getString(0) + "\n");
buffer.append("NAME :" + res.getString(1) + "\n");
buffer.append("EVENT :" + res.getString(2) + "\n");
buffer.append("FACILITATOR :" + res.getString(3) + "\n"+"\n");
}
// Show all data
showMessage("ATTENDANCE LIST", buffer.toString());
}
}
);
}
public void showMessage(String title, String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
public void AddData() {
attendance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String valInput = fname.getText().toString();
final String valInput1 = eventname.getText().toString();
final String valInput2 = faciname.getText().toString();
boolean valid = true;
if (TextUtils.isEmpty(valInput)) {
fname.setError("This Item must not be empty!");
valid = false;
}
if (TextUtils.isEmpty(valInput1)) {
eventname.setError("This Item must not be empty!");
valid = false;
}
if (TextUtils.isEmpty(valInput2)) {
faciname.setError("This Item must not be empty!");
valid = false;
}
if (valid) {
boolean isExist = myDb.checkIfRecordExist(DatabaseHelper.TABLE_NAME, DatabaseHelper.COL_1, fname.getText().toString());
if (!isExist) {
boolean isInserted = myDb.insertData(fname.getText().toString(), eventname.getText().toString(), faciname.getText().toString());
if (isInserted) {
Toast.makeText(Attendance.this, "Attendance Success", Toast.LENGTH_LONG).show();
fname.setText(null);
} else if (isInserted == false) {
Toast.makeText(Attendance.this, "Failed to Attendance", Toast.LENGTH_LONG).show();
}
}else if (isExist == true){
Toast.makeText(Attendance.this, "Failed to Attendance "+fname+" Already Existed", Toast.LENGTH_LONG).show();
}
}
}
}); }
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.Logout)
.setMessage(R.string.really_logout)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
Intent intent = new Intent(Attendance.this, MainActivity.class);
startActivity(intent);
Attendance.this.finish();
}
})
.setNegativeButton(R.string.no, null)
.show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}}
change checkIfRecordExist method like this
public boolean checkIfRecordExist(String nameOfTable,String columnName1,String columnValue1,String columnName2,String columnValue2) {
SQLiteDatabase db = null;
try {
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM "+nameOfTable+" WHERE "+columnName1+"='"+columnValue1+"' and "+ columnName2 +"='"+columnValue2+"'",null);
.......................
change below line like this
boolean isExist = myDb.checkIfRecordExist(DatabaseHelper.TABLE_NAME, DatabaseHelper.COL_1, fname.getText().toString(),DatabaseHelper.COL_2, eventname.getText().toString())
Could someone help me? my records are not updating.
I guess the edittext stay the same but not too sure.
How to change the view values that is being put in the edittext to change to the values in updating edittexts.
Would appreciate some help with this
Thank you.
DatabaseManager
public Cursor selectRow(String ID) {
String query = "Select * from " + TABLE_NAME + " where studentID = " + ID;
Cursor cursor = db.rawQuery(query, null);
return cursor;
}
public boolean updateData(String id, String fn, String ln, String ge, String cs, String a, String loc) {
ContentValues contentValues = new ContentValues();
contentValues.put("studentID", id);
contentValues.put("first_name", fn);
contentValues.put("last_name", ln);
contentValues.put("gender", ge);
contentValues.put("course_study", cs);
contentValues.put("age", a);
contentValues.put("location", loc);
db.update(TABLE_NAME, contentValues, "studentID = ?", new String[]{id});
return true;
}
The above is parts of my database that I use in this activity.
activity main.java
private void UpdateData() {
u.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
uptable.setVisibility(View.VISIBLE);
again.setVisibility(View.VISIBLE);
Cursor res = mydManager.selectRow(text);
if (res != null && res.moveToFirst()) {
String id = Integer.toString(res.getInt(0));
String nme = res.getString(1);
String lnme = res.getString(2);
String gen = res.getString(3);
String corse = res.getString(4);
String ag = Integer.toString(res.getInt(5));
String lo = res.getString(6);
studid.setText(id);
fname.setText(nme);
lname.setText(lnme);
gender.setText(gen);
course.setText(corse);
age.setText(ag);
loc.setText(lo);
}
}
}
);
}
public void UpdateData1() {
again.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
uptable.setVisibility(View.GONE);
String id = studid.getText().toString();
String nme = fname.getText().toString();
String lnme = lname.getText().toString();
String gen = gender.getText().toString();
String corse = course.getText().toString();
String ag = age.getText().toString();
String lo = loc.getText().toString();
boolean isUpdated = mydManager.updateData(id, nme , lnme, gen, corse ,ag , lo);
if (isUpdated == true)
Toast.makeText(Main4Activity.this, "Data Updated", Toast.LENGTH_LONG).show();
else
Toast.makeText(Main4Activity.this, "Data Not Updated", Toast.LENGTH_LONG).show();
}
}
);
}
I tried having a button to set the data but it still stays the same.
Sorry din't read the code, take the sample if it helps
Just the logic..
public long updateNote(NoteModel noteModel) {
if (LOG_DEBUG) UtilLogger.showLogUpdate(TAG, noteModel, noteModel.getRow_pos());
long updatedRow = 0;
try {
ContentValues contentValues = new ContentValues();
contentValues.put(DBSchema.DB_TITLE, noteModel.getTitle());
contentValues.put(DBSchema.DB_IMAGE_PATH, noteModel.getImgUriPath());
contentValues.put(DBSchema.DB_SUB_TEXT, noteModel.getSub_text());
contentValues.put(DBSchema.DB_CREATE_DATE, noteModel.getCreateDate());
contentValues.put(DBSchema.DB_UPDATE_DATE, noteModel.getUpdateDate());
contentValues.put(DBSchema.DB_SCHEDULED_TIME_LONG, noteModel.getScheduleTimeLong());
contentValues.put(DBSchema.DB_SCHEDULED_TIME_WHEN, noteModel.getScheduledWhenLong());
contentValues.put(DBSchema.DB_SCHEDULED_TITLE, noteModel.getScheduledTitle());
contentValues.put(DBSchema.DB_IS_ALARM_SCHEDULED, noteModel.getIsAlarmScheduled());
contentValues.put(DBSchema.DB_IS_TASK_DONE, noteModel.getIsTaskDone());
contentValues.put(DBSchema.DB_IS_ARCHIVED, noteModel.getIsArchived());
updatedRow = mSqLiteDatabase.updateWithOnConflict(
DBSchema.DB_TABLE_NAME,
contentValues,
DBSchema.DB_ROW_ID + " =?", new String[]{String.valueOf(noteModel.get_id())}, mSqLiteDatabase.CONFLICT_REPLACE);
return updatedRow;
} catch (SQLException e) {
e.printStackTrace();
}
return updatedRow;
}
then take the cursor
public Cursor getCursorForAlarmScheduled(String passAlarmScheduledStatus) {
if (LOG_DEBUG)
Log.w(TAG, " pick all record with alarmScheduled 1 : " + passAlarmScheduledStatus);
return mSqLiteDatabase.rawQuery(DBSchema.DB_SELECT_ALL +
" WHERE " + DBSchema.DB_IS_ALARM_SCHEDULED + " = " + passAlarmScheduledStatus, null);
}
and then extract
//common operation for all,
public static List<NoteModel> extractCommonData(Cursor cursor, List<NoteModel> noteModelList) {
noteModelList = new ArrayList<>();
if (LOG_DEBUG) Log.i(TAG, "inside extractCommonData()");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
NoteModel noteModel = new NoteModel();
noteModel.set_id(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_ROW_ID)));
noteModel.setTitle(cursor.getString(cursor.getColumnIndex(DBSchema.DB_TITLE)));
noteModel.setImgUriPath(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IMAGE_PATH)));
noteModel.setSub_text(cursor.getString(cursor.getColumnIndex(DBSchema.DB_SUB_TEXT)));
noteModel.setCreateDate(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_CREATE_DATE)));
noteModel.setUpdateDate(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_UPDATE_DATE)));
noteModel.setScheduleTimeLong(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TIME_LONG)));
noteModel.setScheduledWhenLong(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TIME_WHEN)));
noteModel.setScheduledTitle(cursor.getString(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TITLE)));
noteModel.setIsAlarmScheduled(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_ALARM_SCHEDULED)));
noteModel.setIsTaskDone(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_TASK_DONE)));
noteModel.setIsArchived(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_ARCHIVED)));
noteModelList.add(noteModel);
} while (cursor.moveToNext());
}
cursor.close();
}
return noteModelList;
}
Again, I din't read,just copied from my old samples
Please do find the needful, cheers
I have create custom incoming call screen that can current show the name and phone number of an incoming call. If the contact has a profile pic set that image should display in the ImageView. I calls the below method, and assigns the picture to the ImageView. The problem is that the else statement is always executed:
public static Uri getPhotoUri(String savedNumber, Context context) {
try {
Cursor cur = context
.getContentResolver()
.query(
ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID
+ "="
+ getContactIDFromNumber(savedNumber,
context)
+ " AND "
+ ContactsContract.Data.MIMETYPE
+ "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
+ "'", null, null);
if (cur != null) {
if (!cur.moveToFirst()) {
return null; // no photo
}
} else {
return null; // error in cursor process
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
getContactIDFromNumber(savedNumber, context));
return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
public static int getContactIDFromNumber(String contactNumber,Context context) {
int phoneContactID = 0;
Cursor contactLookupCursor = context.getContentResolver().query(
Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(contactNumber)),
new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID},
null, null, null);
try {
contactLookupCursor.moveToFirst();
while (contactLookupCursor.moveToNext()) {
phoneContactID = contactLookupCursor.getInt(contactLookupCursor
.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
}
} finally {
contactLookupCursor.close();
}
return phoneContactID;
}
IncomingActivity:
#Override
protected void onResume() {
super.onResume();
callerNumber.setText(savedNumber);
callerName.setText(CommonMethods.getCallerName(savedNumber, this));
callerImageUri = CommonMethods.getPhotoUri(savedNumber, this);
if (callerImageUri != null) {
callerImage.setImageURI(callerImageUri);
} else {
callerImage.setImageResource(R.drawable.contact_default);
}
}
Does anyone have any ideas as to why "callerInamgeUri" is remaining null?
I'm doing a project on estimote shoe sticker and I'm now doing database for the sticker. My issue is now how to set counter in database sqlite. Every once the sticker is picked up or clicked, in the database it will show an increment in count. I have post the codes for database and main activity below.
NearablesDemoActivity.java
private void displayCurrentNearableInfo() {
stickerdb = new Database_sticker(this);
dbRow = stickerdb.getResult(currentNearable.identifier);
dbRow.getId();
dbRow.getIdentifier();
count = stickerdb.getCount(currentNearable.identifier);
dbRow.getCount();
String desc = dbRow.getDesc().toString();
dbRow.getCa().toString();
dbRow.getSa().toString();
String coo = dbRow.getCoo().toString();
String sm = dbRow.getSm().toString();
String price = dbRow.getPrice().toString();
//Set the text to the TextView
Desc.setText(desc);
COO.setText(coo);
SM.setText(sm);
Price.setText("$" + price);
}
Database_sticker.java
public int getCount(String identifier) {
String countQuery = "UPDATE" + TABLE_SRESULT + " SET " + KEY_COUNT + "=" + KEY_COUNT + "+1"
+ " WHERE " + KEY_IDENTIFIER + "='" + identifier + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
if(cursor != null && !cursor.isClosed()){
cursor.close();
}
return cursor.getCount();
}
public Sresult getResult(String identifier) {
String selectQuery = "SELECT * FROM " + TABLE_SRESULT + " WHERE " + KEY_IDENTIFIER + "='" + identifier + "'";
SQLiteDatabase db = this.getWritableDatabase(); //open database
Cursor cursor = db.rawQuery(selectQuery, null);
//looping through all rows and adding to list
Sresult sresult = new Sresult();
if (cursor.moveToFirst()) {
do {
sresult.setId(Integer.parseInt(cursor.getString(0)));
sresult.setIdentifier(cursor.getString(1));
sresult.setDesc(cursor.getString(2));
sresult.setSa(cursor.getString(3));
sresult.setCa(cursor.getString(4));
sresult.setCoo(cursor.getString(5));
sresult.setSm(cursor.getString(6));
sresult.setPrice(Float.parseFloat(cursor.getString(7)));
sresult.setCount(Integer.parseInt(cursor.getString(8)));
} while (cursor.moveToNext());
}
return sresult;
}
ListNearablesActivity.java
beaconManager.setNearableListener(new BeaconManager.NearableListener() {
#Override
public void onNearablesDiscovered(List<Nearable> nearables) {
toolbar.setSubtitle("Found shoes: " + nearables.size());
adapter.replaceWith(nearables);
for (Nearable nearable : nearables) {
if (nearable.isMoving) {
try {
Class<?> clazz = Class.forName(getIntent().getStringExtra(EXTRAS_TARGET_ACTIVITY));
Intent intent = new Intent(ListNearablesActivity.this, clazz);
intent.putExtra(EXTRAS_NEARABLE, adapter.getItem(nearables.indexOf(nearable)));
startActivity(intent);
} //close for try
catch (ClassNotFoundException e) {
Log.e(TAG, "Finding class by name failed", e);
} //close for catch (ClassNotFoundException e)
}
}
} //for override
}); //for beaconManager.setNearable
private AdapterView.OnItemClickListener createOnItemClickListener() {
return new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
if (getIntent().getStringExtra(EXTRAS_TARGET_ACTIVITY) != null){
try {
Class<?> clazz = Class.forName(getIntent().getStringExtra(EXTRAS_TARGET_ACTIVITY));
Intent intent = new Intent(ListNearablesActivity.this, clazz);
intent.putExtra(EXTRAS_NEARABLE, adapter.getItem(position));
startActivity(intent);
} //close for try
catch (ClassNotFoundException e) {
Log.e(TAG, "Finding class by name failed", e);
} //close for catch (ClassNotFoundException e)
} //close for getintent.getStringExtra()
} //close for public void onitemclick
}; //close for return new adapterview
} //close for private adapter
Solution
Database_sticker.java
public int getStickerCount(String identifier) {
String countQuery = "UPDATE " + TABLE_SRESULT + " SET " + KEY_SCOUNT + " = " + KEY_SCOUNT + "+1" + " WHERE " + KEY_IDENTIFIER + "= '" + identifier + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int scount = 0;
if (cursor.moveToFirst())
{
do
{
scount = Integer.parseInt(cursor.getString(8));
} while(cursor.moveToNext());
}
return scount; }
For incrementing value by one in counter , you need to fire UPDATE query to Table.
Like below :
UPDATE "Your tablename"
SET "counter column name"= "counter column name"+ 1
WHERE id= "pass your reference id";
Hope it will help you.
I am new to android and learning to connect sqllite database to an app. This is the main activity and getting an error in Cursor cursor = (Cursor) db.getAllQuestions(); line.
Error says Type mismatch: cannot convert from List<class name> to Cursor. please can somebody help me overcome this.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
String destPath = "/data/data/" + getPackageName()
+ "/databases/questions";
File f = new File(destPath);
if (!f.exists()) {
CopyDB(getBaseContext().getAssets().open("questions"),
new FileOutputStream(destPath));
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Error File", Toast.LENGTH_SHORT)
.show();
}
catch (IOException e1) {
e1.printStackTrace();
Toast.makeText(MainActivity.this, "Error IO", Toast.LENGTH_SHORT)
.show();
}
DatabaseHandler db = new DatabaseHandler(this);
// db.open();
long id = db.addQuestion(new addtodb(0, "Question1", "answer1"));
id = db.addQuestion(new addtodb(0, "Question2", "answer2"));
db.close();
// db.open();
Cursor cursor = (Cursor) db.getAllQuestions();
if (cursor.moveToFirst())
{
do {
DisplayRecord(cursor);
}
while(cursor.moveToNext());
}
db.close();
}
public void CopyDB(InputStream inputstream, OutputStream outputstream)
throws IOException {
byte[] buffer = new byte[1024];
int length;
while ((length = inputstream.read(buffer))>0){
outputstream.write(buffer, 0, length);
}
inputstream.close();
outputstream.close();
}
public void DisplayRecord(Cursor cursor){
Toast.makeText(this,
"id:" + cursor.getString(0) + "\n" +
"Question:" + cursor.getString(1) + "\n" +
"Answer:" + cursor.getString(2),
Toast.LENGTH_SHORT).show();
}
}
This is my getAllQuestions method.
public List<addtodb> getAllQuestions() {
List<addtodb> QuestionList = new ArrayList<addtodb>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_QUESTIONS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
addtodb question = new addtodb();
question.setID(Integer.parseInt(cursor.getString(0)));
question.setName(cursor.getString(1));
question.setPhoneNumber(cursor.getString(2));
// Adding contact to list
QuestionList.add(question);
} while (cursor.moveToNext());
}
// return contact list
return QuestionList;
}
Obviously you want to wrap your List whose length is 3 into a Cursor.
You can use MatrixCursor for this purpose. For example :
List<?> resultList = getAllQuestion();
MatrixCursor cursor = new MatrixCursor(new String[] { "0", "1", "2" });
cursor.addRow(resultList);
You need to return the cursor object instead of List. That would help.