Android : multiple task in single button click using if-else - android

I have a ADD TO CART Button to add the products to cart and in database.I would like to show the same button as ALREADY IN CART if the product is already in cart.I tried using if else,but it is not working.It does n't crash VM.But no effect on clicking.
My Code
add2cart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String nm=name.getText().toString();
String rate=price.getText().toString();
mydb=Product_Details.this.openOrCreateDatabase("addcart", MODE_PRIVATE, null);
Cursor cur=mydb.rawQuery("select * from add2cart where pnme='"+nm+"'",null);
while (cur.moveToNext())
{
String name=cur.getString(cur.getColumnIndex("pnme"));
if (nm.equals(name))
{
add2cart.setText("Already in Cart");
}
else {
mydb.execSQL("INSERT INTO add2cart (pnme,prate)VALUES('"+nm+"','"+prprice+"')");
Toast.makeText(getApplicationContext(),"add to cart",Toast.LENGTH_SHORT).show();
Intent in=new Intent(Product_Details.this,add2cart.class);
startActivity(in);
} }
}
});

Perhaps you should try to rename one of your "name" variables. You could use this.name to specify which one you are referring to but I don't see the need to do that. The problem in fact might be that when you do if(nm.equals(name)) you are referring to the global variable name and not the one you set in the previous line. Hope I could help

Related

Error while fetching data from a db

I have a table, c_question in which I stored some questions with this structure
autoincrement column _id,
question,
option1,
option2,
option3,
correct_answer
Now I want to retrieve the question in a TextView and the answers in a RadioGroup.
If the user selects the correct answer, then the question and options will change
in the same page.
Logcat: fatal exception at main ..... cursorIndexOutOfBoundException
The output shows the last data (question with answers) I entered in the db and if I click any answer, the app crashes.
String row="SELECT* FROM c_question";
final Cursor c=db.rawQuery(row, null);
c.moveToFirst();
if(c.moveToFirst())
{
do
{
tv1.setText(c.getString(1));
r0=(RadioButton)findViewById(R.id.radio0);
r0.setText(c.getString(2));
r1=(RadioButton)findViewById(R.id.radio1);
r1.setText(c.getString(3));
r2=(RadioButton)findViewById(R.id.radio2);
r2.setText(c.getString(4));
k.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int idd=r.getCheckedRadioButtonId();
r0=(RadioButton)findViewById(idd);
String r=r0.getText().toString();
if(r.equals(c.getString(5)))
{
Toast.makeText(QuestionsOn.this, "correct!!!", 123).show();
;
} else
Toast.makeText(QuestionsOn.this, "Incorrect!!!", 123).show();
}
});
} while(c.moveToNext());
}
Output showing the last data(Question with options) I entered in DB
That's what you get when you update the save views in a loop; only the last "row" will get shown.
If you want to show a list of data from the database, you need some Adapter class in a ListView / ViewPager
and if I click any option, the app crashes...
According to the error, c.getString(5) doesn't exist, so seems like you didn't create your database with the correct number of columns.

changing text into database values

when button is pressed i want to the text to change to the database collumn values, i know its wrong but here is the code:
private void MostraDados() {
// TODO Auto-generated method stub
final TextView text = (TextView) findViewById(R.id.tvUSUARIO);
Button mostrar = (Button) findViewById(R.id.bMostrar);
mostrar.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
db = openOrCreateDatabase("dbtest.db", Context.MODE_PRIVATE, null);
String q = "SELECT * FROM dbtest.db WHERE usuarioorigem='";
text.setText(q);
//text.execSQL("DROP COLUMN IF EXISTS usuarioorigem");
}
});
}
Your code is missing some critical parts for example a DatabaseClass that manages the cursor and database.
private void MostraDados() {
final TextView text = (TextView) findViewById(R.id.tvUSUARIO);
Button mostrar = (Button) findViewById(R.id.bMostrar);
mostrar.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// our missing a database helper
MyDatabaseClass dbhelper = new MyDatabaseClass();
dbhelper.open();
Cursor result = dbhelper.doMyQuery();
String mystring = result.getString(0);
text.setText(mystring);
dbhelper.close();
}
});
....
public class WorkoutDbAdapter {
....
public Cursor doMyQuery()
{
return this.mDb.query( yourQuery );
}
}
This is the minimum you'd need and even with the above i'm missing a lot of the smaller detail. Search for some tutorials on creating and using Databases.
Essentially however you need to get the cursor back, set the position of the cursor, or cursor.moveNext() and then get the value that you can assign to the textField.
Your source code lacks a correct call to a database and access to the cursor. Hopefully you'll find some decent tutorials that will flesh the rest out for you.
The SQL is not written correctly. You must SELECT from a column. And you're passing the query string the the text view. You should first review how to query the database with the cursor, and how to retrieve what you want from the cursor.
So I would look into how to use the curosr, all of that's available in the Android docs, and you might want to try the API demos in the emulator I'm sure you can learn how to work with the cursor there as well. So look here, http://developer.android.com/reference/android/database/Cursor.html.
And here, Is Android Cursor.moveToNext() Documentation Correct?.
After getting the cursor, you could do something like this:
while(c.moveToNext(){
text.setText(c.getString(0))
}

how to delete group from expandable list view

I am trying to get the primary key "_id" from the selected group using code
groupPositionID is a global variable initialized like this
and IngredientListGroup_cursor is a group cursor which fetches the group data for expanable list view.
String groupPositionID=null;
Cursor IngredientListGroup_cursor;
in the oncreate code:
public void onCreate(Bundle savedInstanceState) {
IngredientListGroup_cursor=helper.GetIngredientsList();
}
ExpandableIngredietnsList.setOnGroupClickListener(new OnGroupClickListener(){
#Override
public boolean onGroupClick(
ExpandableListView paramExpandableListView,
View paramView, int paramInt, long paramLong) {
// TODO Auto-generated method stub
groupPositionID=IngredientListGroup_cursor.getString(0);
Toast toast = Toast.makeText(getBaseContext(),groupPositionID ,Toast.LENGTH_LONG);
toast.show();
return false;
}
});
this is my SQLhelper function for deleting the selected group from database.
public Cursor GetIngredientsList(){
return(getReadableDatabase().rawQuery("SELECT _id,Ingredient_name FROM tblIngredients",null));
}
public Cursor DeleteIngredientsList_Item(String index){
String[] args={index};
return(getReadableDatabase().rawQuery("DELETE FROM tblIngredients WHERE _id=?",args));
}
The problem I am facing is tha although i am getting the id for the selected group from cursor (i m able to see that as toast) but then, why i am not able to delete that from context menu.
on selecting delete from context menu the following code should execute properly
public boolean onOptionsItemSelected(MenuItem IngredientItem){
if(IngredientItem.getItemId()==R.id.addIngredient){
Intent i= new Intent(Ingredients_List.this,Ingredients_Add.class);
startActivity(i);
return(true);
}
else if (IngredientItem.getItemId()==R.id.deleteIngredient) {
if(groupPositionID!=null){
helper.DeleteIngredientsList_Item(groupPositionID);
return(true);
}
else{
Toast.makeText(getBaseContext(), "Select The Ingredient You want to delete", Toast.LENGTH_LONG).show();
}
}
return (super.onOptionsItemSelected(IngredientItem));
}
I am getting the selected primary key id value from "groupPositionID" variable here.. accurate value is transferred to database raw query also... still not getting what i am expecting
Plz help ASAP I am new to both android and java
sdk information(although not required)
android:versionCode="1"
android:versionName="1.0"
android:minSdkVersion="8"
Thanks in Advance
public void DeleteIngredientsList_Item(long index){
String[] args = new String[]{Long.toString(index)};
Log.v("I am in", "SQLHelper");
getWritableDatabase().execSQL("DELETE FROM tblIngredients WHERE _id=?",args);
}
i modified this delete code in mysql helper
my function was earlier returning cursor thats why it was not working ... meanz in actual query was not getting executed...
rest was ok.. :)

In Android how to delete the entire record in Table without passing any arguments?

Hai i created a DataBase and inserted the value in one Class,and i try to delete the record in another class but,the Whole table is Deleted.i need to delete the entire record only without deleteing the table.is it possible to delete all record without any condition?
kindly help me
Thanks in advance
public void deletePayment()
{
db.delete(DATABASE_TABLE3, "KEY_ROLLID=?",null);//i want to delete all row in KEY_ROLLID
}
You doesn't try DELETE Statement,
In android you can execute Sql Query with db.rawQuery also, in this you can pass Delete Statement for your table, as:
db.rawQuery("Delete FROM Table_Name");
Use this concept:
public static void deletedatafromtable(Context context) {
// TODO Auto-generated method stub
try {
SQLiteDatabase SQLITE_db;
SQLITE_db = context.openOrCreateDatabase("databaseName",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
SQLITE_db.setVersion(1);
SQLITE_db.setLocale(Locale.getDefault());
SQLITE_db.setLockingEnabled(true);
String DELETEPASSCODE_DETAIL = "delete from tableName;";
SQLITE_db.execSQL(DELETEPASSCODE_DETAIL);
SQLITE_db.close();
} catch (Exception e) {
// TODO: handle exception
}
}

Trying to add info to database

So this is my first app and first database. I think I have finally created the DBAdapter correctly, and now I am trying to implement that into my main activity.
I have a save button listed under an onClick
public void onClick(View src) {
switch(src.getId()){
...other buttons here...
case R.id.buttonSave:
db.open();
long id;
id = db.insertFinalscore("20110612", "91", "18");
db.close();
break;
}
}
As I'm sure you can not see, I am trying to insert that data into the table. I have created an instance of DBAdapter inside my onClick:
public void onClick(View src) {
//***DATABASE INFO***//
DBAdapter db = new DBAdapter(this);
Is anyone able to tell me what I am missing? I am getting the following warning:
case R.id.buttonSave:
db.open();
long id; <--- The local variable id is never read
id = db.insertFinalscore("20110612", "91", "18");
db.close();
You are getting a warning, not an error. Basically the warning is saying that the variable id is never actually used. While you do set its value, you never read that value making the variable worthless. Your program will run just fine as is, but you might as well remove the variable id.
Your program should now look like this:
public void onClick(View src) {
switch(src.getId()){
...other buttons here...
case R.id.buttonSave:
db.open();
db.insertFinalscore("20110612", "91", "18");
db.close();
break;
}
}

Categories

Resources