简体   繁体   中英

how to update integer value in sqlite android

i am having problem with the updation part of the below code. insertion is working properly. when i added the update method for addition/subtraction of the integer stored in the database, the code is no longer working. it says the app has closed unfortunately. the app is not even opening. please check the update method and make sufficient changes.

first i used this code to accept name and email. then this code was changed to accept a number and email. variable name and column name has not been changed. please dont get confused with these.

thank you.

MainActivity.java

package com.sqltut;



import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

Button save,load,updatebtn;
EditText name,email,update;
DataHandler handler; 
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    save=(Button) findViewById(R.id.save);
    load=(Button) findViewById(R.id.load);
    name=(EditText) findViewById(R.id.name);
    email=(EditText) findViewById(R.id.email);

    save.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            String getName=name.getText().toString();
            String getEmail=email.getText().toString();

            int number = Integer.parseInt(getName);

            handler=new DataHandler(getBaseContext());
            handler.open();
            long id=handler.insertData(number, getEmail);
            Toast.makeText(getBaseContext(), "Data Inserted", Toast.LENGTH_LONG).show();
            handler.close();
        }
    });

    load.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String getEmail;
            Integer getName;
            getName=0;
            getEmail="";
            handler=new DataHandler(getBaseContext());
            handler.open();
            Cursor C=handler.returnData();
            if(C.moveToFirst())
            {
                do
                {
                getName=C.getInt(0);    
                getEmail=C.getString(1);
                }while(C.moveToNext());
            }
            handler.close();
            Toast.makeText(getBaseContext(), "Name:"+getName+" And Email:"+getEmail,Toast.LENGTH_LONG).show();
        }
    });

    updatebtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

        int number,flag=0; //flag to check for addition or subtraction
        String getupdate=update.getText().toString();
        number=Integer.parseInt(getupdate);
        handler=new DataHandler(getBaseContext());
        handler.open();
        handler.updateData(number,flag);
        //subtraction: flag=0, addition: flag=1
        handler.close();
        }
    });

    //to call next activity
   /* Button createAppointment = (Button)findViewById(R.id.Next);
    createAppointment.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            // TODO Auto-generated method stub
            Intent myIntent = new Intent(MainActivity.this, Page2.class);
            MainActivity.this.startActivity(myIntent);            
        }
    });
*/  }



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

DataHandler.java

package com.sqltut;

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;

public class DataHandler {

public static final String NAME="name";
public static final String EMAIL="email";
public static final String TABLE_NAME="mytable";
public static final String DATA_BASE_NAME="mydatabase";
public static final int DATABASE_VERSION=1;
public static final String TABLE_CREATE="create table mytable(name text not null, email text not null);";

DataBaseHelper dbhelper;
Context ctx;
SQLiteDatabase db;
public DataHandler(Context ctx)
{ 
    this.ctx = ctx;
    dbhelper=new DataBaseHelper(ctx);
}

private static class DataBaseHelper extends SQLiteOpenHelper
{
    public DataBaseHelper(Context ctx)
    {
        super(ctx,DATA_BASE_NAME,null,DATABASE_VERSION);
    } 

    @Override
    public void onCreate(SQLiteDatabase db) {
     try{
        db.execSQL(TABLE_CREATE);
     }
     catch(SQLException e)
     {
         e.printStackTrace();
     }

    }



    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

        db.execSQL("DROP TABLE IF EXISTS mytable ");
         onCreate(db);
    }

}
public DataHandler open()
{
    db=dbhelper.getWritableDatabase();
    return this;
}

public void close()
{
    dbhelper.close();
}

public long insertData(Integer name, String email)
{
    ContentValues content=new ContentValues();
    content.put(NAME, name);
    content.put(EMAIL,email);
    return db.insert(TABLE_NAME, null, content);

}

public void updateData(Integer number,Integer flag)
{
    db = dbhelper.getReadableDatabase();
    String select = "select name from  " + TABLE_NAME ;
    Cursor c = db.rawQuery(select, null);
    int current=0;
    if (c.moveToFirst()) {
        current=  Integer.parseInt(c.getString(0));
    }
    if(flag==0)//subtraction
    {
        current=current-number;
    }
    else//addition
    {
        current=current+number;
    }
    c.close();
    db.close();

    db = dbhelper.getReadableDatabase();
    ContentValues content=new ContentValues();
    content.put(NAME, current);
     db.update(TABLE_NAME, content,null,null);

}


public Cursor returnData()
{
    return db.query(TABLE_NAME, new String[] {NAME,EMAIL}, null, null, null, null, null);
}
}

Edited updateData()

public void updateData(Integer value,Integer flag)
{
    db = dbhelper.getReadableDatabase();
    String selectQuery = "select balance from  " + TABLE_NAME ;
    Cursor cursor = db.rawQuery(selectQuery, null);
    int current = 0;
        if (cursor.moveToFirst()) {
            current=  Integer.parseInt(cursor.getString(0));

    }
    if(flag==0){
            current = current-value;
    }else {
            current = current+value ; 
    }
    cursor.close();
    db.close();
    try{
        db = dbhelper.getWritableDatabase();
        String rawQuery = "update mytable set balance="+current;
        db.rawQuery(rawQuery, null);
        }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
}

Code worked. db.rawQuery(rawQuery, null); changed to db.execSQL(rawQuery);

You can update any value in your table by below method:

public void updateInteger(Integer newID)
    {
        try{
            sqliteDb = appDb.getWritableDatabase();
            String rawQuery = "update <table_name> set id="+newID;
            sqliteDb.rawQuery(rawQuery, null);
            Log.v(TAG, "ID updated");
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM