display primary key after inserting in database - android

I am developing an android app, and i want to display the primary key in the textview so that every-time I edit a textfield, I will be using the primary key to update.can anyone help me with this? below is the inserting of data in the sqlite. My problem is how to get the primary key...
public class UsedataActivity extends Activity {
DatabaseHandler db = new DatabaseHandler(this);
ImageButton evsave;
EditText evname;
EditText evtime;
EditText evdate;
EditText evcode;
TextView evadmin;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_onetoone);
evsave = (ImageButton)findViewById(R.id.event_save);
evname = (EditText)findViewById(R.id.eventname);
evtime = (EditText)findViewById(R.id.time1);
evdate = (EditText)findViewById(R.id.eventdate);
evcode = (EditText)findViewById(R.id.eventcode);
evadmin = (TextView)findViewById(R.id.adminname_1to1);
evsave.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Events addev =
new Events(evname.getText().toString(),evcode.getText().toString(),evdate.getText().toString(),Integer.parseInt(evtime.getText().toString()),evadmin.getText().toString());
db.addEvents(addev);
Toast.makeText(getApplicationContext(), "Event: "+ evname.getText()+" successfully save",
Toast.LENGTH_SHORT).show();
}
});
}
database handler class:
public void addEvents(Events event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_EV_NAME, event.get_name());
values.put(KEY_EV_PASS, event.get_pass());
values.put(KEY_EV_DATE, event.get_date());
values.put(KEY_EV_TIME, event.get_time());
values.put(KEY_EV_ADMIN, event.get_admin());
// Inserting Row
db.insert(TABLE_EVENTS, null, values);
db.close();
}

As it can be observed from the docs for the SQLiteDatabase, db.insert will return the id of the newly created object. Just make addEvents return it (instead of being `void).
PS: Please paste code in edits of the question, not in comments. In comments they really look awful!
EDIT
public long addEvents(Events event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_EV_NAME, event.get_name());
values.put(KEY_EV_PASS, event.get_pass());
values.put(KEY_EV_DATE, event.get_date());
values.put(KEY_EV_TIME, event.get_time());
values.put(KEY_EV_ADMIN, event.get_admin());
// Inserting Row
long id = db.insert(TABLE_EVENTS, null, values);
db.close();
return id;
}
And then:
long id = db.addEvents(addev);
Toast.makeText(getApplicationContext(),
"Event with id: "+ id + " successfully saved",
Toast.LENGTH_SHORT).show();

Related

onclick update value in a row in sqlite

Hi I'm new to Android Java and SQLite, I'm trying to make an onClick listener change the value in the column from 1 to 2 but I'm confused about what I need to do. I tried doing some research on it but seem to get the basic way of updating your entries you added. Can anyone help me with this?
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (database.updateReserved() == 1) {
database.updateReserved(reserved);
}
}
});
public void updateReserved(Integer reserved){
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("reserved",reserved);
String tableName="cars"; //Table Name
db.update(tableName , contentValues, "=" + reserved,null) ;
}
If you want to make sure that only rows with reserved = 1 will be updated, change updateReserved() so that both the current value and the new value of reserved are passed as arguments.
So, in the 3d argument of update(), which is the WHERE clause, pass the current value:
public void updateReserved(int oldReserved, int newReserved) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("reserved", newRreserved);
String tableName = "cars";
db.update(tableName, contentValues, "reserved = ?", new String[] {String.valueOf(oldReserved)}) ;
}
Now you can simplify the click listener like this:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
database.updateReserved(1, reserved);
}
});

I can't insert data

I'm making an app to insert data. But when I click on add button by giving all the details. App return me to previous page
This is the way I create insert class
public class InsertStudent extends AppCompatActivity {
Button instudent;
DBHelper dbHelper;
EditText sName,sDOB,sAddress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_student);
instudent = findViewById(R.id.btninsert);
sName = findViewById(R.id.insertname);
sDOB = findViewById(R.id.insertdob)
;
sAddress = findViewById(R.id.insertaddress);
Below is the way I coded to insert data
instudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String userName = sName.getText().toString();
String dateB = sDOB.getText().toString();
String addr = sAddress.getText().toString();
boolean count = dbHelper.addInfo(userName,dateB,addr );
if(count =true){
Toast.makeText(InsertStudent.this, "Inserted!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(InsertStudent.this, "Something went wrong!", Toast.LENGTH_SHORT).show();
}
}
});
This is addinfo method in DBHelper class
public boolean addInfo(String stdName, String stdDOB, String stdAddress){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(UserProfile.Users.COLUMN_STDNAME, stdName);
contentValues.put(UserProfile.Users.COLUMN_DATEOFBIRTH, stdDOB);
contentValues.put(UserProfile.Users.TABLE_ADDRESS, stdAddress);
long result = sqLiteDatabase.insert(UserProfile.Users.TABLE_NAME, null, contentValues);
if(result==1)
return false;
else
return true;
}
}
The insert method of "SQLiteDatabase" class doesn't return the
count, it's returns the id of the inserted row. so you are checking
if return result is 1, it's a true process, but it's not a way to
check the insert method. It means you need to check if there is any
return result, your insert action performed successfully, but if
there is a problem, the application will crash.
Make sure you created the table that you want to insert data in it.

Updating my Column in SQLite with Android

I have a method in my activity class which should print a random role to the player (stores in an SQLite database). I am getting a success message but it is not being carried out. I only have 1 record in my SQLite database so far and will be adding a while loop after to populate each row.
This is my my activity class:
public class StartGame extends AppCompatActivity implements View.OnClickListener {
DatabaseHelper myDb;
Button btnRoles;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_startgame);
myDb = new DatabaseHelper(this);
btnRoles = (Button) findViewById(R.id.btnAssignRoles);
assignRoles();
}
public String RandomNumber() {
List < String > roles = Arrays.asList("Mafia", "Mafia", "Angel", "Detective", "Civilian", "Civilian", "Civilian");
Collections.shuffle(roles);
return roles.get(0);
}
public void assignRoles() {
btnRoles.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
{
boolean isUpdated = myDb.updateRole(RandomNumber().toString());
if (isUpdated == true)
Toast.makeText(StartGame.this, "Roles assigned, keep them secret!", Toast.LENGTH_LONG).show();
else
Toast.makeText(StartGame.this, "UNSUCCESSFUL!", Toast.LENGTH_LONG).show();
}
}
}
);
}
And this is the method in my Database Helper class:
public boolean updateRole(String role){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_ROLE, role);
db.update(TABLE_NAME, contentValues, "Role =?", new String[] {role});
return true;
}
What am I doing wrong?
You got an error in this line:
db.update(TABLE_NAME, contentValues, "Role =?", new String[] {role});
You are updating all the rows in the table where Role = {role} to have the column Role the value {role}. So obviously this will have no effect.
You need to have some thing like id and use that in your where statement, some thing like this:
db.update(TABLE_NAME, contentValues, "id =?", new String[] {id});

Checkbox in a custom adapter to update the database

I am trying to get the checkbox I created in a custom adapter for a list to update the database upon clicking on it. I implemented the onclicklistener on the checkbox inside the customAdapter (code below). I also added a Toast to check if it works. The problem is that the Toast displays the right information for each row (the name of the item i click on); however the database doesn't get updated.
datasource = new MySQLiteHelper((AssTasksActivity) context);
CB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Task Ta = task; //Task is an object with a separate class that is stored in the sqlite db.
if(CB.isChecked()){
Ta.setState(0);
datasource.updateTask(Ta);
//Toast T;
Toast.makeText(context, Ta.getTaskName(),
Toast.LENGTH_LONG).show();
}
else{
Ta.setState(1);
datasource.updateTask(Ta);
Toast.makeText(context, Ta.getTaskName(),
Toast.LENGTH_LONG).show();
}
}
});
Here is the sqlite code for the update
public int updateTask(Task task){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.T_COLUMN_TASK_ID, task.getId());
values.put(MySQLiteHelper.T_COLUMN_TASKNAME, task.getTaskName());
values.put(MySQLiteHelper.T_COLUMN_DESCRIPTION, task.getDescription());
values.put(MySQLiteHelper.T_COLUMN_STATE, task.getState());
values.put(MySQLiteHelper.T_COLUMN_PK, task.getAssignmentId());
values.put(MySQLiteHelper.T_COLUMN_ERROR_DESCRIPTION, task.getErrorDescription());
return database.update(TABLE_TASKS, values, T_COLUMN_ROWID + " = ?",
new String[] { String.valueOf(task.getId()) });
}
T_COLUMN_ROWID in the return statement should be T_COLUMN_TASK_ID. Silly mistake.

how to insert data into an sq-lite database at runtime [duplicate]

This question already exists:
how to insert data into sq-lite database at run-time [closed]
Closed 9 years ago.
I built an application that uses sq-lite database and within the application at run-time i made a button that when pressed added a new Edit-Text i'm wondering how can i save the values in the new Edit-Text into my database? please help me
Use this method :
public long saveData(Context context, String editTextValue) {
long x = -1;
appDb = new AppDatabase(context);
sqliteDb = appDb.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("monthOfBirth", editTextValue);
try {
if (sqliteDb.isOpen()) {
x = sqliteDb.insert("password", null, values);
if (x >= 0)
{
Toast.makeText(context, "Password Save", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception exc) {
exc.printStackTrace();
}
return x;
}
Call this method in your button's onClickListener()
button.setOnCLickListener(new View.OnClickListener())
{
#override
public void onClick(View v)
{
if(editText.getText().toString.equals(""))
{
Toast.makeText(context, "Fill Value first.", Toast.LENGTH_SHORT).show();
return;
}
saveData(YourActivity.this, editText.getText().toString());
}
}
Have you created the class extending SQLiteOpenHelper? If you have it, then use the constructor and get an object of this class:
dbHelper = new SQLiteHelper(context, getString(R.string.db_name_dev), null, DB_VERSION);
And then for example:
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("term", term);
db.insert("Search", null, cv);
Simply make a String which contains insert query of SQL. Then call the method
db.execSQL(sql);
on your datebase refence variable.
String sql =
"INSERT INTO <TABLE_NAME> VALUES('this is','03/04/2005','5000','tran','y')" ;
db.execSQL(sql);

Categories

Resources