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.
Related
I am getting a problem in android textview.
I am simply setting text on the android textview like below
pAmount.setText("Rs." + receiptAmount + "/-");
but is showing null in the text
System.out.println("receiptAmount ====>"+ receiptAmount );
I had tried to print the value of receiptAmount to check whether, the value is null or not.
But, It is showing the right value in the log.
What is the issue does any body have any idea.
similarly , other texview are showing the null value in the same activity.
TextView pAmount= (TextView) findViewById(R.id.amount);
1.Call the set text After Declaring the above line in Oncreate.
2.get the Proper data in receiptAmount. Your Problem Solved
pAmount.setText("Rs." + receiptAmount + "/-");
public void FeeGetFeeTypes(String studentId, String fee_slotid) {
// TODO Auto-generated method stub
ArrayList<String> arrayList_FeeType=new ArrayList<String>();
ArrayList<String> arrayList_FeeTypeAmount=new ArrayList<String>();
try{
SQLiteDatabase db = this.getReadableDatabase();
final String MY_QUERY = "select * from feetype where student_id=? and slot_id=?";
Cursor res = db.rawQuery(MY_QUERY, new String[]{ studentId, fee_slotid });
res.moveToFirst();
while (res.isAfterLast() == false){
arrayList_FeeType.add(res.getString(res
.getColumnIndex(FEE_TYPE_COLUMN_FEETYPE)));
arrayList_FeeTypeAmount.add(res.getString(res
.getColumnIndex(FEE_TYPE_COLUMN_FEETYPEAMOUNT)));
}
if(arrayList_FeeType.size()>0){
PrintActivity.sendFeeType(arrayList_FeeType, arrayList_FeeTypeAmount);
}
}
catch(Exception e){
e.printStackTrace();
}
}
This is the code that is resulting the null values. When the data is large, I get out of memory exception
I have created a table with id and tag as column.
id is set as primary key. And in tag column, I have entered more than one value.
So now i want to get the count of how many times the tag value is repeated.
So my table is like this.
Id Tag
---------------------
1 Friend, Family
2 Family, Enemy
and my output should be like this:
friend (1)
family(2)
Enemy(1)
I have written a code but not getting the result I want.
This is MyDatabase.java code:
public Details calculateCount()
{
Details detail = null;
try
{
SQLiteDatabase db=this.getWritableDatabase();
String selectQuery=("select count(*),Tags from photodetails group by Tags" );
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToLast())
{
do
{
detail=new Details(Integer.parseInt(cursor.getString(0)),(cursor.getString(1)));
}while( cursor.moveToNext());
}
}
catch(Exception e)
{
e.printStackTrace();
}
return detail;
}
And this is MAinActivity.java code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
getActionBar().setDisplayHomeAsUpEnabled(true);
MyDataBase MyDB = new MyDataBase(this);
Log.d(LOGCAT,"Entered MAinActivity2");
Details c= MyDB.calculateCount();
if(c == null)
{
Log.d(LOGCAT,"C is null");
}
else
{
Log.d(LOGCAT,c.getTag()); // Here iam only retrieving tag dont know how to get that count.
}
}
Pls help me out on this
If you want to get a count, you're going to want to create a method such as a int getCount() method that will return the int value of the count. Currently, you have Details calculateCount() which will return a Details object.
Ok this should be straight forward but i'm having difficulty with it. So far i've got this code.
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
SpinnerFAQ = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + SpinnerFAQ,
Toast.LENGTH_LONG).show();
TextView tv = (TextView) findViewById(R.id.faq_answer);
ExerciseData question = new ExerciseData(this);
question.open();
String answer = question.getFaqAnswer();
question.close();
tv.setText(answer);
}
SpinnerFAQ is a global variable and it stores the value of the spinner as String.
public String getFaqAnswer() {
// TODO Auto-generated method stub
String[] columns = new String[] { FAQ_ROWID, FAQ_QUESTION, FAQ_ANSWER};
Cursor c = ourDatabase.query(DATABASE_TABLE2, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(FAQ_ROWID);
int iQuestion = c.getColumnIndex(FAQ_QUESTION);
int iAnswer = c.getColumnIndex(FAQ_ANSWER);
//c.getString(iRow) + " " +
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
if(FAQ.SpinnerFAQ == c.getString(iQuestion))
{
result = result + c.getString(iAnswer) + "\n";
break;
}
}
return result;
}
This is based on code I've already used, but basically I want to check the Spinner against the Question in my Database and if they match I want to change the Text View to the answer. Right now the FAQ.SpinnerFAQ works fine, but c.getString(iQuestion) always shows up as the last value in the database. This code "result = result + c.getString(iAnswer) + "\n";" works fine without the if statement, so I don't really understand why there is a problem with "c.getString(iQuestion)". Any help would be greatly appreciated.
if(FAQ.SpinnerFAQ == c.getString(iQuestion))
Never compare Strings with == in Java, always use equals(). Please read: How do I compare strings in Java? and change every String comparison to:
if(FAQ.SpinnerFAQ.equals(c.getString(iQuestion)))
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?
Hoping someone might be able to shine a little light on this for me to help out. I have a EditText field where a user will input a serial number and or reference number, then hit the load Button.
http://i.stack.imgur.com/95iWI.png
I made a method to check and see if that number has already been added to the Database. If it hasn't then i have a Yes/No dialog that pops up asking if they want to add to the database. Then if it is in the DB it will load that number's data into the four TextViews.
http://i.stack.imgur.com/dHbCQ.png
If they select yes then it runs the new intent, switching to the form screen(haven't yet looked into passing the user input to another class yet). but to get back on to my little issue, when testing this in the emulator everything runs fine. Then when i enter a number that i already entered in it still opens the dialog, (i have it in a if statement).
Load button code
String s = input.getText().toString();
int l = Integer.parseInt(s);
Db load = new Db(this);
load.open();
y = load.dbCheck(l);
if (y != 0) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
Intent i = new Intent("android.intent.action.FORM");
startActivity(i);
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Would you like to add to Database?")
.setTitle("Not in Database:")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener)
.show();
}
else
{
final Dialog dbentery = new Dialog(this);
dbentery.setTitle("Entry Exists!");
TextView tv = new TextView(this);
tv.setText("The serial number you have entered is already in database");
dbentery.setContentView(tv);
dbentery.show();
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
dbentery.dismiss();
t.cancel();
}
}, 2000);
}
load.close();
Now with the method i created I thought I had it right, but something just isn't working. I have it returning a integer back to the load button code where the if statement uses wither 0 or 1 to validate if it is in the DB and what it should do. I figured since it is running the Dialog that it is returning 0, that it might be with the cursor. I looked at a few other posts on here that were similar but didn't seem to help me and or i wasn't comprehending what was being done. So here's the checking method in my DBHelper class
/* this is to check to see if entry is in db or not */
public int dbCheck(int l) throws SQLException {
String[] cols = new String[] { KEY_ROWID, KEY_ONE, KEY_TWO, KEY_THREE, KEY_FOUR };
Cursor c = ourDB.query(KEY_TABLE, cols, KEY_ONE + "=" + l, null,
null, null, null);
if (c == null) {
return 0;
}else {
return 1;
}
}
this might be a simple fix, but I'm not seeing it... thanks for any help or insight to what i might be doing wrong
c == null if the query throws an error, otherwise c != null, but c.getCount == 0
public int dbCheck(int l) throws SQLException {
String[] cols = new String[] { KEY_ROWID, KEY_ONE, KEY_TWO, KEY_THREE, KEY_FOUR };
Cursor c = ourDB.query(KEY_TABLE, cols, KEY_ONE + "=" + l, null,
null, null, null);
if (c == null) {
return 0;
}else {
return c.getCount() == 0 ? 0:1;
}
}
First, rewrite dbCheck() to return boolean, not int. No point in having an int if you only return two values, waste of space.
Second, rewrite your query. There is no point in selecting all those columns if you only filter on one of them, and then throw the result away. Rewrite it into this:
String s = String.format("SELECT count(*) FROM %s WHERE %s = %d",
KEY_TABLE, KEY_ONE, l);
Cursor c = ourDB.rawQuery(s, null);
c.moveToFirst();
return (c.getInt(0) > 0); // returns a boolean
This will cut down the number of quirks you have in your code, and it will help you debug it easier.
EDIT: corrected query() into rawQuery().