I am trying to update my database. It is not really updating. I think it is due to my update command
my main activity is a listview activity. I have a button on the action bar that basically starts a new activity with two editboxes. So once I click that button, I create a new database item. It is originally set to two empty strings. On my second activity, I have a save button that is supposed to save my changes into the textboxes
so after my main activity takes me to my second activity, the code is as follows
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
// if new then create new db, else retrieve old database, right now
// assume everything is new
db = new DBHandler(this);
nowAdd = new UENote("", "");
db.addNote(nowAdd);
}
i update my nowAdd contact strings through this function
public void updateColumnData() {
// gets the strings from edittext
EditText textTitle = (EditText) findViewById(R.id.editText1);
EditText textSubject = (EditText) findViewById(R.id.editText2);
// converts the string
String titleString = textTitle.getText().toString();
String subjectString = textSubject.getText().toString();
nowAdd.setSubject(subjectString);
nowAdd.setTitle(titleString);
db.updateNote(nowAdd);
}
the update note function is as follows
public int updateNote(UENote note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, note.getTitle());
values.put(KEY_SUBJECT, note.getSubject());
// updating row
return db.update(TABLE1, values, KEY_ID + " = ? ",
new String[] { String.valueOf(note.getID()) });
}
Make sure that the id you are passing in the db.update() is really the same one that you want to update. From the code snippet, it's not obvious how you are getting the value of note.getID(). Are you making query for empty record to get the id?
Assuming that KEY_ID is an auto incremented primary key, I would then debug getID() to check if it returns the same id of the record you wanted to update.
Related
While inserting my listview gets refreshed automatically but not update when the item in the listview is updated. It only updates on database. I can see the listview is updated when I close the application and open again, or come back from previous activity.
I found some discussion related to my problem. Like: Refresh ListView with ArrayAdapter after editing an Item . Her I found that make a new method to populate the Listview and call it in the onResume method of your activity.
And the problem has been solved using this. But I do not get how to make new method mentioned like there. Could anybody help me to make it understandable?
My code in activity class:
personNamesListView = (ListView) findViewById(R.id.traineeslist);
traineeListAdapter = new ArrayAdapter<Trainee>(this,
android.R.layout.simple_list_item_1,
currentTraining.getTraineeArrayList());
personNamesListView.setAdapter(traineeListAdapter);
protected void onResume() {
super.onResume();
}
And this way I populated my personNamesListView using method stringToString() in model class;
public void loadTraineeList() {
DatabaseHelper db = DatabaseHelper.getInstance();
this.traineeArrayList = new ArrayList <Trainee>();
Cursor cursor = db.select("SELECT * FROM person p JOIN attendance a ON p._id = a.person_id WHERE training_id="+Integer.toString(this.getId())+";");
while (cursor.moveToNext()) {
Trainee trainee = new Trainee();
trainee.setID(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.PERSON_ID)));
trainee.setFirstname(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_FIRSTNAME)));
trainee.setLastname(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_LASTNAME)));
trainee.setJobTitle(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_JOBTITLE)));
trainee.setEmail(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_EMAIL)));
trainee.setCompany(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_COMPANY)));
trainee.setDepartment(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_DEPARTMENT)));
trainee.setBadgeNumber(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_BADGE)));
// Pass to the arraylist
this.traineeArrayList.add(trainee);
}
}
public ArrayList<Trainee> getTraineeArrayList() {
return traineeArrayList;
}
public void setTraineeArrayList(ArrayList<Trainee> traineeArrayList) {
this.traineeArrayList = traineeArrayList;
}
I insert and Update data into database into one method:
public void storeToDB() {
DatabaseHelper db = DatabaseHelper.getInstance();
db.getWritableDatabase();
if (this.id == -1) {
// Person not yet stored into Db => SQL INSERT
// ContentValues class is used to store a set of values that the
// ContentResolver can process.
ContentValues contentValues = new ContentValues();
// Get values from the Person class and passing them to the
// ContentValues class
contentValues.put(DatabaseHelper.PERSON_FIRSTNAME, this
.getFirstname().trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_LASTNAME, this
.getLastname().trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_JOBTITLE, this
.getJobTitle().trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_EMAIL, this.getEmail());
contentValues.put(DatabaseHelper.PERSON_COMPANY, this.getCompany()
.trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_DEPARTMENT, this
.getDepartment().trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_BADGE, this
.getBadgeNumber().trim().toUpperCase());
// here we insert the data we have put in values
this.setID((int) db.insert(DatabaseHelper.TABLE_PERSON,
contentValues));
} else {
// Person already existing into Db => SQL UPDATE
ContentValues updateTrainee = new ContentValues();
updateTrainee.put(DatabaseHelper.PERSON_FIRSTNAME, this
.getFirstname().trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_LASTNAME, this
.getLastname().trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_JOBTITLE, this
.getJobTitle().trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_EMAIL, this.getEmail());
updateTrainee.put(DatabaseHelper.PERSON_COMPANY, this.getCompany()
.trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_DEPARTMENT, this
.getDepartment().trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_BADGE, this
.getBadgeNumber().trim().toUpperCase());
db.update(DatabaseHelper.TABLE_PERSON, updateTrainee,
DatabaseHelper.PERSON_ID+"= ?", new String[]{Integer.toString(this.getId())});
System.out.println("Data updated");
}
}
You should call traineeListAdapter.notifyDataSetChanged() whenever you update your ArrayList representing the items in the ListView.
There's a similar question here that can give you some help.
Although I've accomplished something similar using
yourlistview.invalidateViews()
after changing the data to show in the listview
when notifyDataSetChanged() didn't work.
EDIT:
After making all the operations in the data that I want to show i just set the adapter and try to refresh my listview by calling invalidateViews().
selectedStrings = new ArrayList<String>(typeFilterStrings);
adapter.setArrayResultados(selectedStrings);
listTypeFilter.invalidateViews();
It's not obligatory to set the adapter again in my case worked.
use like this:
Create an instance of your custom adapter, so you can use it anywhere you like...
public class ScoreList extends SherlockFragmentActivity {
private ListView listViewScore;
private ScoreListAdapter adapter;
static List<Score> listScore = new ArrayList<Score>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.score_list);
ctx = this;
listScore = dbh.getAllScores();
listViewScore = (ListView) findViewById(R.id.score_list);
adapter = new ScoreListAdapter(ctx, R.layout.score_row_item, listScore);
listViewScore.setAdapter(adapter);
((BaseAdapter) listViewScore.getAdapter()).notifyDataSetChanged();
}
}
By the way, if your listScore array is already loaded, then you do not need to use
adapter.notifyDatasetChanged();
I want to get edit text value into database in Andorid, right now it is giving blank and in list it is printing my project path and string value #4100dd00.
here is my code.
public class Add_Task_List extends Activity {
EditText edt_addtasklist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_task_list);
SaveTaskList();
}
public void SaveTaskList(){
edt_addtasklist = (EditText)findViewById(R.id.edt_addtasklist);
String taskliststitle = edt_addtasklist.getText().toString();
//how to get edittext value and store in database. right now it is creating field in db but not showing any value when I am checking in data/data/project path/database/.
edt_addtasklist.setText(taskliststitle);
System.out.println(taskliststitle);
TaskManager_Database db = new TaskManager_Database(this);
db.AddTaskLists(taskliststitle); //database method
}
}
List Adapter:
ListView list_tasklistname = (ListView)findViewById(R.id.list_tasklistname);
TaskManager_Database db = new TaskManager_Database(getApplicationContext());
list = db.GetAddTaskLists();
ArrayAdapter<TaskDetailsActivity> adapter = new ArrayAdapter<TaskDetailsActivity>(getApplicationContext(), android.R.layout.simple_list_item_1, list);
list_tasklistname.setAdapter(adapter);
//it is showing list on task added in database but value is like this in one row "com.android.todotask.taskdetailsActivity#4100dee86".
I want when user enter edit text value then it store in sql database table db.AddTaskLists(taskliststitle); and show in a list where I will call db.GetAddTaskLists(); method from database.
Please let me know how to store value in sqlite db, thanks
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))
}
I have a neat, working SQLite database on Android that records species observations. I am then using JSON (successfully) to verify observations entered against a set of parameters on a remote database. On verification, a flag in the database is updated to say that this process has been done. But, when I view my main activity (Text, the values for observations with flags after verification don't update.
My activity order is:
Main activity (obs = 0 from database)
Obs Entry activity
Main activity (obs = 1 with flag A from db)
Data management activity, verify button
Verify done activity, main button
Main activity (obs = 1 with flag A from db)
If I exit, or leave it for a while, then come back in to Main activity, the database is being polled correctly and obs = 1 with flag B from db.
So I know my database is right and the SQL is correct too. Could it be that I'm declaring my buttons at the wrong point for the Activity to correctly resume()?
My code:
final Button verifySightingsButton = (Button) findViewById(R.id.uploadprocess);
if (verifies == 0) {
verifySightingsButton.setTextColor(getResources().getColor(R.color.red));
} else {
verifySightingsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// do stuff
}
});
}
where 'verifies' is the number of flag A records. The button is being called with the onCreate() method. Would it make any difference if I instantiated it as a class variable?
Thanks in advance - bugging me senseless!
UPDATE: This is the code (actually using XML, not JSON which is used for other queries) that handles the verification and update of flag:
// Get details for an observation within loop
ArrayList d = (ArrayList) allVerifyRows.get(i);
// Build the URL to verify the data
String aURL = buildVerifyURL(d);
// Parse the XML
aValid = ParseVerificationXML.verifyXMLdata(aURL);
db.open();
Long bouCode = new Long((String) speciesList.get((String) d.get(3)));
boolean insert = db.updateNote(
((Long) d.get(0)).longValue(),
((Long) d.get(1)).longValue(),
// and some other variables being updated
db.close();
and the code to check the database for records that are and are not verified:
NotesDbAdapter db = new NotesDbAdapter(this);
db.open();
Cursor c = db.fetchAllNotes();
species = new ArrayList<String>();
while (c.moveToNext()) {
String str1 = c.getString(2); // Date
species.add(str1);
}
c.close();
Cursor v = db.performNullCountForVerification();
if (v.moveToFirst()) {
stillToVerify = v.getInt(0); // Non-Verified records
readyForUpload = stillToVerify;
}
v.close();
stillToVerify = species.size() - stillToVerify;
db.close();
You might use the onResume method of your main activity to update the shown values. The onResume method is called every time the activity appears on the screen in contrast to onCreate, which is only called when the activity gets created.
I am basically trying to get information from an sqlite db in another class. I've done this without any problems inside the onCreate method, but when I try to use it inside an onClickListener which is inside that onCreate I cannot find the right context to use. My code is as follows:
private AutoCompleteTextView search;
private Button showInfoButton;
private TextView courseInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_courses);
final Context baseContext = getBaseContext();
courseInfo = (TextView) this.findViewById(R.id.text);
DataBase db = new DataBase(this.getApplicationContext());
db.openDataBase();
final ArrayList<String> aCourses = db.getCoursesArr();
db.close();
search = (AutoCompleteTextView) findViewById(R.id.autocomplete_course);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_courses, aCourses);
search.setAdapter(adapter);
showInfoButton = (Button) this.findViewById(R.id.show_info_button);
showInfoButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (aCourses.toString().contains(search.getText()) == false ) {
courseInfo.setText("Please select a course from the drop-down menu and click on the \"Show course information\" button");
}
else{
String selectedCourse = search.toString();
DataBase db1 = new DataBase(baseContext);
db1.openDataBase();
ArrayList<String> courseAttributes = db1.getCourseAttributes();
ArrayList<String> attributeValues = db1.getAttributeValues(selectedCourse);
db1.close();
String courseInformation = "";
for (int i=0; i < courseAttributes.size(); i++){
courseInformation = courseInformation + courseAttributes.get(i) + ": " + attributeValues.get(i) + System.getProperty("line.separator");
}
courseInfo.setText(courseInformation);
}
}
});
}
the problem comes with
DataBase db1 = new DataBase(baseContext);
I've tried changing it to
DataBase db = new DataBase(this.getApplicationContext());
and
DataBase db = new DataBase(null);
and every way I try it, the program does run, but when it get's in the else case it throws an error and shuts down. Could anyone tell me what context should I use in order to make it run?
As you may need the database connection more than once, I recommend to open and close the database connection in your own application class which extends Application.
There you have onCreate and onDestroy methods where you can open and close the database (because it has a context). If you make the database object as a class variable (public static) you should be able to use this like MyApplication.mDatabase.