Looping code through database records - android

I have a database with some records in and i have the code i wish to execute on each row but I'm having trouble creating a suitable loop, ive been trying while(movetonext) but it hasnt been working.
cursor = getAppts();
cursor.moveToNext();
String titlefromdb = cursor.getString(3);
if (strTitle.equals(titlefromdb) && cursor.getString(1).equals(dateselforap))
{
// matching code update box
final Dialog matchdiag = new Dialog(CW2Organisor.this);
matchdiag.setContentView(R.layout.apptmatch);
matchdiag.setTitle("View/Edit Appointment");
matchdiag.setCancelable(true);
TextView matchtxt = (TextView) matchdiag.findViewById(R.id.matchtxt);
matchtxt.setText("Appointment \"" + titlefromdb + "\" already exists, please choose a different event title");
Button btnmatchok = (Button) matchdiag.findViewById(R.id.btnmatch);
btnmatchok.setOnClickListener(new OnClickListener() {
// on click for cancel button
#Override
public void onClick(View v) {
matchdiag.dismiss();
}
});
matchdiag.show();
}
else
{
addAppt(strTime, strTitle, strDet);
dialog.dismiss();
}
What I would need is for each row of my database i would need the titlefromdb to hold the title field of the current row and the for the if statement to run and then move to the next row.

You could try
cursor.moveToFirst();
loop with some sort of check
cursor.moveToNext();
end loop
... and I would also try to qualify your "it's not working" statement. What's not working?

Related

How to prompt user for text input in a loop?

I am writing an android app in that main activity starts and populates a list of contacts, and needs to prompt the user for today's rating of all the contacts(promptUserForInput) and immediately process received rating of all the contacts. I thought i can use a dialogue box that prompt for every contact and gets the rating from the user. But below code fails as the main thread is not waiting for the user to finish enter rating of all the users.
Here is my function which I am calling in the main activity in a do while loop for all the contact names. rating is a global variable.
double rating=0;
private synchronized void promptUserForInput(String firstName, String lastName) {
final String fname = firstName;
final String lName = lastName;
AlertDialog.Builder alert = new AlertDialog.Builder(this);
String custName = firstName + " " + lastName;
final EditText input = new EditText(this);
alert.setTitle(custName);
alert.setView(input);
Log.v("Diva: in promptUserForInput", "setting positive buton");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Editable res = input.getText();
if(res == null) {
Log.v("Diva..", "In positivebutton..befoer getting rating res is null");
}
rating = Double.valueOf(input.getText().toString());
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
rating=0;
}
});
alert.show();
}
My caller of this promptUserForInput() looks like below.
// get list of contacts in a cursor
Cursor cursor = ManageDataBaseActivity.queryDataBase(this,
ManageDataBaseActivity.CONTACT_INFO_TABLE);
if(cursor.getCount()>0) {
double totalRatingForStats=0;
cursor.moveToFirst();
do {
String[] colNames = cursor.getColumnNames();
Log.v("Diva Colum names = ", colNames[0] + " " + colNames[1] + " " + colNames[2] + " " + colNames[3]);
String firstName = cursor.getString(cursor.getColumnIndex("FirstName"));
Log.v("Diva ..:", firstName);
String lastName = cursor.getString(cursor.getColumnIndex("LastName"));
String key = ManageDataBaseActivity.getDbKey(firstName, lastName,
date, ManageDataBaseActivity.CUSTOMER_DATA_TABLE);
promptUserForInput(firstName, lastName);
double ratingReceived = rating;
totalRatingForStats = totalRatingForStats+ratingReceived;
// some more processing
ManageDataBaseActivity.insertValueToDB(ManageDataBaseActivity.
CONTACT_DATA_TABLE+" ", .....);
} while(cursor.moveToNext());
The short answer: Don't.
The long answer: You should never block the main thread of a GUI program while waiting for user input.
Instead you should provide a continue button, which fires a event which causes the program to continue. There are several ways to accomplish this, the one that comes to mind first is signals and semaphores.
I'm not that well versed in Android programming - but there should be something similar in the API, perhaps dependent on Intents.
Looping in the main thread of an Activity is generally not a very good idea. But you could implement something like a pollNext() method that gets the next dataset from the cursor and change your click-methods to this:
#Override
public void onClick(DialogInterface dialog, int which) {
// do your rating stuff
// reads the next dataset
pollNext();
// shows the next dialog
// of course, firstName and lastName must be membervariables to make this work
promptUserForInput(firstName, lastName);
}
The idea behind that is very common and also used in the MVC-pattern

Editing the content of database in android

I have a edit tab in my app where the user can edit his details given during the time of registration .Inside the edit activity i have a save button which when clicked it saves the
data or update the datas into the database.
CODE
public void onSave(View btn)
{
EditText edtName = (EditText) findViewById(R.id.edtNameED);
EditText edtPass = (EditText) findViewById(R.id.edtPassED);
EditText edtEmail = (EditText) findViewById(R.id.edtEmailED);
EditText edtPh = (EditText) findViewById(R.id.edtPhED);
int id=0;
String where = DataBase_Server.C_ID+"=?";
String[] whereArgs = {id+""};
DataBase_Server database=new DataBase_Server(Edit.this);
SQLiteDatabase db=database.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DataBase_Server.MOBILE_NO, edtPh.getText().toString());
values.put(DataBase_Server.PASS, edtPass.getText().toString());
values.put(DataBase_Server.EMAIL, edtEmail.getText().toString());
for(int i=0;i<edtName.length();i++)
{
id+=(int)edtName.getText().toString().charAt(i);
}
Toast.makeText(this,id+" hello", Toast.LENGTH_LONG).show();
try
{
db.update(DataBase_Server.TABLE, values,where,whereArgs);
}catch(Exception e){}
Toast.makeText(this,"UPDATE SUCESSFULL !!", Toast.LENGTH_LONG).show();
db.close();
database.close();
}
The code is giving not a single error but it is not even updating anything in the database. The database is not changed at all even after the user edit his details.
You are adding up the values of all the characters in the name:
for(int i=0;i<edtName.length();i++)
id+=(int)edtName.getText().toString().charAt(i);
This is unlikely to be your real ID value. With no record matching the WHERE condition, the update will do nothing, silently.
You must remember the ID value from when you loaded the data, because the name may have changed.

android sqlite next record incorrect

This is the getContact method which takes the rowID in this case the counter
public Cursor getContact(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
question, possibleAnsOne,possibleAnsTwo, possibleAnsThree,realQuestion,userR}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
// moves to the the first record
mCursor.moveToFirst();
}
return mCursor;
}
Here is my problem. I start at record one. So the counter is set to one.
in the public oncreate method. When I click next for some reason it is not setting the value of the first record with db.updateUserResult(counter,8); I think it is missing the first record. The reason I know this is that if I chose the answer which is one ahead. Lets say that Question 1 right answer is option 2 and Question 2's right answer is option 3. If you choose option 3 for question 1 then you get the right answer. If i keep choosing the right answer one record ahead I get all the right results.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
boolean TimerStarted = b.getBoolean("timerlogic");
System.out.println("what is the logic of the timer" + TimerStarted);
Log.e(LOGS, "Whatis the first value for the timer inside the timer_btn" + TimerStarted);
setContentView(R.layout.basic);
// this method is better then a try and catch block as it actually prevents the occurence occuring instead of just patching it.
// the purpose of t
db.open();
Cursor c = db.getContact(1);
if(c.isFirst())
{
TextView question = (TextView)findViewById(R.id.question);
RadioButton radio1 = (RadioButton)findViewById(R.id.radio1);
RadioButton radio2 = (RadioButton)findViewById(R.id.radio2);
RadioButton radio3 = (RadioButton)findViewById(R.id.radio3);
answerCounterText = (TextView)findViewById(R.id.answerCounterText);
answerCounterText.setText(String.valueOf("0"));
// for the first record set the counter to zero
// question.setText(String.valueOf("0"));
TextView QuestionNumber = (TextView)findViewById(R.id.QuestionNumber);
Complete = (Button)findViewById(R.id.Continue);
Complete.setBackgroundResource(R.drawable.complete);
Complete.setVisibility(View.INVISIBLE);
QuestionNumber.setText(String.valueOf("Question Number :" + counter));
System.out.println("what is the setup counter after loop" + counter);
//DisplayContact(c,radio1);
DisplayRadioButton(c,radio1,radio2,radio3,question);
}
// }
// }
// Previous = (Button)findViewById(R.id.Previous);
Next = (Button)findViewById(R.id.Next);
Next.setBackgroundResource(R.drawable.next);
// get the results from the checked box
Next.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
// Cursor c = db.getContact(1);
/*
if (firstrecordchosen)
{
Cursor c = db.getContact(1);
System.out.println("what is the current value of the counter 0" + counter);
firstrecordchosen = false;
}
counter++;
*/
counter++;
Cursor c = db.getContact(counter);
if (c.moveToFirst() && !c.isNull(0))
{
TextView question = (TextView)findViewById(R.id.question);
RadioButton radio1 = (RadioButton)findViewById(R.id.radio1);
RadioButton radio2 = (RadioButton)findViewById(R.id.radio2);
RadioButton radio3 = (RadioButton)findViewById(R.id.radio3);
TextView answerCounterText = (TextView)findViewById(R.id.answerCounterText);
TextView QuestionNumber = (TextView)findViewById(R.id.QuestionNumber);
RadioGroup radioGroup1 = (RadioGroup)findViewById(R.id.radioGroup1);
QuestionNumber.setText(String.valueOf("Question Number :" + counter));
Log.e(LOGS, "default user set variable " + c.getString(5));
Log.e(LOGS, "real value" + c.getString(6));
System.out.println("what is the current value of the counter" + counter);
// DisplayContact(c,radio1);
DisplayRadioButton(c,radio1,radio2,radio3,question);
final String questionOneDb = c.getString(5);
String radioOneIndex = "1";
String radioTwoIndex = "2";
String radioThreeIndex = "3";
// set the first question to have the right value
if(radio1.isChecked() )
{
db.updateUserResult(counter,8);
if (questionOneDb.equals(radioOneIndex))
{
Log.e(LOGS, "correct" );
rightAnswer(c,radio1,answerCounterText);
// DisplayContact(c,radio1);
}
else
{
Log.e(LOGS, "wrong" );
}
}
if(radio2.isChecked() )
{
db.updateUserResult(counter,9);
if (questionOneDb.equals(radioTwoIndex))
{
System.out.println("is this counter being reached");
// db.updateUserResult(1, 2);
// db.updateUserResult(counter, 2);
// db.updateUserResult(recordval, 6);
Log.e(LOGS, "correct" );
rightAnswer(c,radio1,answerCounterText);
}
else
{
Log.e(LOGS, "wrong" );
}
}
if(radio3.isChecked() )
{
db.updateUserResult(counter,10);
if (questionOneDb.equals(radioThreeIndex))
{
Log.e(LOGS, "correct" );
System.out.println("you have the right answer");
rightAnswer(c,radio1,answerCounterText);
}
else
{
Log.e(LOGS, "wrong" );
}
}
}
/* when you get ot the last record you want to be able to close the db */
if (c.isAfterLast())
{
// this halts the timer when there are no questiosn left
Next.setVisibility(View.GONE);
// Previous.setVisibility(View.GONE);
Toast.makeText(getBaseContext(), "More questions available in the full version PHPExpert " , Toast.LENGTH_LONG).show();
Complete.setVisibility(View.VISIBLE);
handler.removeCallbacks(timedTask);
db.close();
intentcalls();
}
}
});
Home = (Button)findViewById(R.id.home_btn);
Home.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(Basic_database_questionsActivity.this,AndroidGUIActivity.class);
startActivity(i);
}
});
}
If I am not totally wrong, you have a timing issue.
First you get your first question and you show the UI (your radio buttons and stuff).
You check with the click on the Next button, if the chosen answer is right, correct?
If so, you make the mistake that you first increase the counter and then query for the question based on counter (which will be the next). After that you check if the chosen radio button is the correct one. As you already read the next question from the database, you check the chosen answer to your first question with the stored answer of the second one.
Hope that was clear.
Short tip: try to clean up some code. Don't put anything inside the onCreate() make smaller chunks so you can see and follow the code flow easier...
Try this
Cursor c1 = mDbHelper.fetAll(); \\ or whatever your method is to get data from database.
if(c1.moveToFirst()){
do{
\\ Do what you want to do with it.
}while(c1.moveToNext()); \\ this will move the cursor to next line.
}
c1.close(); \\ make sure you close it, else errors will pop up in LOGCAT.

SQLite Update Not Applying Android

When I click on a ListItem, it opens up a custom dialog with 4 EditText fields. The fields are set with current data depending on the row that is clicked. The purpose of the dialog is to allow the user to update the data (it is a financial app). I am having trouble actually applying the update when the user clicks "submit" in the dialog. There are no errors in the app when I run. Here is the onclick method:
protected void onListItemClick(ListView l, View v, int position, long id) {
List<Debt> values = datasource.getAllDebt();
Debt item = values.get(position);
final long boxId = item.getId();
// final String BoxId = String.valueOf(boxId);
final String BoxName = item.getName();
final String BoxBalance = item.getBalance();
final String BoxApr = item.getApr();
final String BoxPayment = item.getPayment();
// set up dialog
final Dialog dialog = new Dialog(manageDebts.this);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Edit Debt Details");
dialog.setCancelable(true);
// set up text
EditText et1 = (EditText) dialog.findViewById(R.id.editText1);
EditText et2 = (EditText) dialog.findViewById(R.id.editText2);
EditText et3 = (EditText) dialog.findViewById(R.id.editText3);
EditText et4 = (EditText) dialog.findViewById(R.id.editText4);
et1.setText(BoxName);
et2.setText(BoxBalance);
et3.setText(BoxApr);
et4.setText(BoxPayment);
// set up button
Button button = (Button) dialog.findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
datasource.updateDebt(boxId, BoxName, BoxBalance, BoxApr,
BoxPayment);
dialog.dismiss();
}
});
dialog.show();
}
The Update Method in my Database helper class is shown here:
public boolean updateDebt(long updateId, String debt_name, String debt_total, String apr, String payment)
{
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_ID, updateId);
values.put(MySQLiteHelper.COLUMN_DEBT_NAME, debt_name);
values.put(MySQLiteHelper.COLUMN_DEBT_TOTAL, debt_total);
values.put(MySQLiteHelper.COLUMN_APR, apr);
values.put(MySQLiteHelper.COLUMN_PAYMENT, payment);
return database.update(MySQLiteHelper.TABLE_DEBT, values, MySQLiteHelper.COLUMN_ID + " = " + updateId, null) > 0;
}
I have verified that the COLUMN_ID and the updateId are pointing to the correct rows in the ListView and the SQL database.
Does someone see something I am not?
Perhaps you are violating a constraint with your update? Just a guess without seeing the DB code.
EDIT
Lose the single quotes around the row id variable, that is making the DB treat it as a string, and a string compared to a number is a fail.
This will work better:
String whereClause = MySQLiteHelper.COLUMN_ID + " = ?";
String[] whereArgs = new String[]{ String.valueOf(updateId) };
return database.update(MySQLiteHelper.TABLE_DEBT,
values, whereClause, whereArgs) > 0;
The String.valueOf() call simply converts the ID to a String value.
I test your code in my computer.
The update method works fine.
So I think you should post more code .
or You should check your logic.
I was missing a step between 2 and 3.
Setting the variable again, inside the onClick method. Once the user pressed the update button, the variable had to be RE-SET to the new value of the EditText field. Like this (simplified version):
String name = null;
EditText et;
name = debt.getName();
et.setText(name);
onclick {
***name = et.getText().toString();***
datasource.updateDebt(name);
}

How to enable the record for delete after retrieve in sqlite?

I fetch record from database using following code.
for (LocWiseProfileBeans cn : LocWiseProfile) {
// get a reference for the TableLayout
TableLayout table = (TableLayout) findViewById(R.id.locprofile_table);
// create a new TableRow
TableRow row = new TableRow(this);
// count the counter up by one
counter++;
String log = "Loc Name: "+cn.getLocname()+" ,Lattitude: " + cn.getLattitude()+ " ,Longitude: " + cn.getLongitude()+ " , Selected Profile :"+cn.getSelectedprofile();
TextView t = new TextView(this);
// set the text to "text xx"
t.setText(cn.getLocname());
TextView t2 = new TextView(this);
t2.setText(cn.getSelectedprofile());
row.addView(t);
row.addView(t2);
table.addView(row,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
But i need to enable this record for deletion on user request.
Means if user click on second record then this record will be delete.
I try to find the answer but not find any appropriate answer.......
Please provide me reference code or article.
Thank you in Advance!
You can do this by setting onClickListener to your row.
To determine which row is clicked, you can set a unique tag to that row.
row.setTag(counter); // use counter or index for tag, so you can get the data from LocWiseProfile later
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int tag = (Integer)view.getTag();
LocWiseProfileBeans cn = LocWiseProfile.get(tag);
// Perform delete action here
// ...
}
});
If you want to simply display the result from db as a list, I suggest you using ListActivity or ListView, with using adapter you can show and manage your data in more simple way.
//decleration
EventDataSQLHelper eventsData; //Class where table is created
SQLiteDatabase dbx,rdbx;
//onCreate
eventsData = new EventDataSQLHelper(this);
rdbx= eventsData.getReadableDatabase();
dbx=eventsData.getWritableDatabase();
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//specify the id of the record to be deleted
dbx.delete("tablename", "id=" ?, null);
}
});

Categories

Resources