'How do I get the maximum id from a table?
How do I get the maximum id from a table? What command can I use to fix it, or do I need to write a method? Thanks for the past answers.Is my program supposed to change the last entry? Any ideas give me, I am new to android developer.Is it possible to apply db.rawQuaery somehow? Or are there other ways to change the record? '
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class UserActivity<cursor> extends AppCompatActivity {
EditText nameBox;
EditText yearBox;
Button delButton;
Button saveButton;
DatabaseHelper sqlHelper;
SQLiteDatabase db;
Cursor userCursor;
long userId = 5;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
nameBox = findViewById(R.id.name);
yearBox = findViewById(R.id.year);
delButton = findViewById(R.id.deleteButton);
saveButton = findViewById(R.id.saveButton);
sqlHelper = new DatabaseHelper(this);
db = sqlHelper.getWritableDatabase();
Bundle extras = getIntent().getExtras();
if (extras != null) {
userId = extras.getLong("id");
}
if (userId > 0) {
userCursor = db.rawQuery("select * from " + DatabaseHelper.TABLE + " where " +
DatabaseHelper.COLUMN_ID + "=?", new String[]{String.valueOf(userId)});
userCursor.moveToFirst();
nameBox.setText(userCursor.getString(1));
yearBox.setText(String.valueOf(userCursor.getInt(2)));
userCursor.close();
} else {
delButton.setVisibility(View.GONE);
}
}
public void save(View view){
ContentValues cv = new ContentValues();
cv.put(DatabaseHelper.COLUMN_NAME, nameBox.getText().toString());
cv.put(DatabaseHelper.COLUMN_YEAR, Integer.parseInt(yearBox.getText().toString()));
if (userId > 0) {
db.update(DatabaseHelper.TABLE, cv, DatabaseHelper.COLUMN_ID + "=" + userId, null);
} else {
db.insert(DatabaseHelper.TABLE, null, cv);
}
goHome();
}
public void delete(View view){
db.delete(DatabaseHelper.TABLE, "_id = ?", new String[]{String.valueOf(userId)});
goHome();
}
private void goHome(){
db.close();
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
}
'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
