I am here again to ask for help, now i will give details on my problem hoping someone can solve it : in the first activity onClick the method insert is executed
public class ActivityUn extends Activity {
final String PREFS_NAME = "MyPrefsFile";
final String ID = "id";
DBAdapter db = new DBAdapter(this);
public void ajouter(View v) {
db.open();
Toast.makeText(getApplicationContext(), "Données enregistrées", Toast.LENGTH_LONG).show();
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
long id = db.insertMENAGE(rm_1ts,rm_2ts,rm_3ts);
prefs.edit().putLong(ID, id).commit();
db.close();
}
the second activity code is :
public class ActivityDeux extends Activity {
SharedPreferences prefs2 = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
private SharedPreferences prefs;
long id = prefs.getLong(ID, 0);
DBAdapter db = new DBAdapter(this);
public void ajouter(View v) {
db.open();
db.insertMENAGE2(id,a16,b17,rm_18_1ts,rm_18_2ts,c19,d20,e21);
db.close();
}
and here the two methods insert and update ...
public long insertMENAGE(String Region, String Provence_prefecture ,StringCommune_Arrondissement) {
ContentValues initialValues = new ContentValues();
initialValues.put(col_Region,Region);
initialValues.put(col_Provence_prefecture ,Provence_prefecture);
initialValues.put(col_Commune_Arrondissement,Commune_Arrondissement);
return db.insert(MENAGE,null, initialValues);
}
In the second activity I will update the same table by completing remaining columns in the row :
public void insertMENAGE2(int id, int a16, int b17) {
ContentValues values = new ContentValues();
values.put(col_Type_habitat,a16);
values.put(col_Statut_occupation ,b17);
db.update(MENAGE,values,_id+"="+id, null);
}
Now , I want to indicates the id ( primary key ) of the row in table which is Inserted Last ,
I already looked for solutions but they are not adapted to my situation, since i have other activities updating the same table
And i need to indicates each time that the id concerned is the last one inserted.
Thanks
EDIT:
public class ActivityUn extends Activity {
final String PREFS_NAME = "MyPrefsFile";
final String ID = "id";
DBAdapter db = new DBAdapter(this);
public void ajouter(View v) {
db.open();
Toast.makeText(getApplicationContext(), "Données enregistrées", Toast.LENGTH_LONG).show();
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
long id = db.insertMENAGE(rm_1ts,rm_2ts,rm_3ts);
prefs.edit().putLong(ID, id).commit();
db.close();
}
}
public class ActivityDeux extends Activity {
final String PREFS_NAME = "MyPrefsFile";
final String ID = "id";
DBAdapter db = new DBAdapter(this);
public void ajouter(View v) {
db.open();
SharedPreferences prefs2 = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
long id = prefs.getLong(ID, 0);
//update the value in the table with the id you get from Sharedpreferences
db.insertMENAGE2(id,a16,b17,rm_18_1ts,rm_18_2ts,c19,d20,e21);
db.close();
}
}
You where usin 2 SharedPreferences variables in the second Activity. The second one (the one you were using) was not instantiated. This would throw a NullPointer Exception.
Please read the documentation about SQLite and SharedPreferences on developer.google.com and try to understand what the code does. Also try to avoid french words in your code, whenever someone from a non french speaking country has to read/edit your code it may not make sence to them.
Its just like doing an synchronization job you looking for.
I suggest you to use a new table with only one value as 'id'
use a method to update that value. say updatelastupdated(idofinsertedrow)
call this method while inserting the data in the table
public long insertMENAGE(String Region, String Provence_prefecture ,StringCommune_Arrondissement)
{
ContentValues initialValues = new ContentValues();
initialValues.put(col_Region,Region);
initialValues.put(col_Provence_prefecture ,Provence_prefecture);
initialValues.put(col_Commune_Arrondissement,Commune_Arrondissement);
updatelastupdated(id) //ADD this method here..
return db.insert(MENAGE,null, initialValues);
}
now the new table idoftheinsertedrow cell will always has the id(Primary key) you looking for use that for completing the updation in the table.
To explain you clearly
yourtable say x
activity 1 inserting a row of id 1
activity 2 inserting a row of id 2
activity 3 inserting a row of id 3
now you have another method update() which must update the row of id 3
for this i suggest keep another table say y
when ever you insert into the table x you update the value of idupdated in table y
so always the idupdated column will hold the last row updated in table x
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
Been trying to retrieve data from database, my database has values and I don't know which causes this error.
public void popList(String date, String time, String type, String game, String place){
Cursor data = databaseHelper.getReports(date, time, type, game, place);
while (data.moveToNext()) {
HashMap<String, String> datax = new HashMap<>();
datax.put("id", (data.getString(data.getColumnIndex("betid"))));
datax.put("betnumber", (data.getString(data.getColumnIndex("betnum"))));
datax.put("betamount", (data.getString(data.getColumnIndex("betamt"))));
mData3.add(datax);
}
bettorAdapter = new MyAdapter(mData3);
listViewx.setAdapter(bettorAdapter);
bettorAdapter.notifyDataSetChanged();
}
public Cursor getReports(String date, String time, String type, String game, String place){
Cursor data=null;
try {
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM reports WHERE date='"+date+"' AND time ='"+time+"' AND game='"+game+"' AND type='"+type+"' AND lugar='"+place+"'";
data = db.rawQuery(query,null);
}catch (Exception e){
System.out.println(e);
}
return data;
}
You need to instantiate/construct the databaseHelper object as it will be null if it is only declared. That is you need to use an equivalent of the line :-
databaseHelper = new DatabaseHelper(appropriate_values_for the_constructor);
Where appropriate_values_for the_constructor are as it says the appropriate value(s) for the constructor, typically just the context.
The above would be used before calling the poplist method. Typically databaseHelper would be declared at the class level and the above line would be set as soon as, or shortly after, the context were available. In an activity this would be in the onCreate method probably just after the ContentView has been set.
The following is an example where databaseHelper is named mDBHlpr and the constructor just needs the one value to be passed, a valid the Context (e.g. for an activity this). :-
public class MainActivity extends AppCompatActivity {
DatabaseHelper mDBHlpr; //<<<<<<<<<< Declares the mDBHlpr instance, it will be null until instantiated
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDBHlpr = new DatabaseHelper(this); //<<<<<<<<<<< Instantiates the Database Helper instance named mDBHlpr
.......... other code
}
.......... other code
}
updated my code. My issue happens when i back out of the activity. Listview items are lost. I checked the Sqlite database and all items are saved, just not showing up again on listView when I reStart-Activity.
MainActivity
private ListView lst;
private CustomeAdapter cv;
private EditText nameEd, middleEd, lastEd;
private ArrayList<People> peopleArrayList;
private DataHelper myData;
peopleArrayList = new ArrayList<>();
OnCreate.....
public void addPerosn(View view) {
String myName = nameed.getText().toString();
String myMiddle = middleed.getText().toString();
String myLast = lasted.getText().toString();
boolean insert = myData.addData(myName, myMiddle, myLast);
if (insert == true) {
peopleArrayList.add(new People(myName, myMiddle, myLast));
cv = new CustomeAdapter(this, peopleArrayList);
lst.setAdapter(cv);
nameed.setText("");
middleed.setText("");
lasted.setText("");
} else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
}
}
My DataHelper method i want to call to Show All
public Cursor showData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
Any suggestions are appreciated . Thanks
Make sure you have overridden getCount and it returns proper count.
#Override
public int getCount() {
return items.length;
}
Apart from above solution, I would recomment you to do it in proper way
a) Create a model/pojo class say Person which will have firstName,lastName and middleName
b) create a data set of Person, i.e list of person
c) create a method addPerson in adapter class, and call whenever you want to add new Person data into the list. addPerson method will also refresh the adapter by calling notifyDataSetChanged
d) In activity create adapter object only once, later on just use method of it say adapter.addPerson(person)
I want to declare an instance of SQLite Database globally as a private final variable.
1)why the way i used in the below posted code causes the logcat to generate erros and the app crashes.
2)is there any other way so I can define an instance of my DB globally and final?
Java_Code:
public class SQLiteTest00 extends Activity {
final MyDB myDB = new MyDB(this);
final SQLiteDatabase mySQLiteDB = myDB.getWritableDatabase();
final ContentValues myContVals = new ContentValues();
private final String TABLE_NAME = "MYDATA";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sqlite_test00);
myContVals.put("name", "loc00");
myContVals.put("lat", 33);
myContVals.put("lng", 53);
myContVals.put("time", "12:30");
myContVals.put("date", "11/05/2014");
lodgeIntoDB(myContVals);
}
private void lodgeIntoDB(ContentValues cv) {
long newID = mySQLiteDB.insert(TABLE_NAME, null, cv);
if (newID == -1) {
Toast.makeText(getBaseContext(), "Error Commiting Record(s)", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Data Commited Successfully", Toast.LENGTH_SHORT).show();
}
}
}
Is MyDB your extended version of SQLiteOpenHelper? Also, why are you creating a final version of a ContentValues? Could you explain why you need a final copy of the db? The db will be private to your app by default, that is the way Android does it. If you extend SQLiteOpenHelper, then you can call the getWritableDatabase() in the onCreate of your main activity and if your db variable is a member variable you will have it. Maybe I am missing something. Also, from what I have read, it is best to close the db if you are not using it and then to use the helper class later to get it again if you need to read from or write to it. Thanks. Ps. one other thing, anytime I have seen the helper class called to get a copy of the db, it is done inside onCreate or another method not at the top in the variable declartions. Try moving it into onCreate.
i am here to ask for help again, my problem is that in first activity i have values that i insert into database , in the second activity when i try to insert the values it creates a new row, what i want is the values of second activity completes the row of the first activity. And also how could i refer to the last row ??
i don't know how to do it! so, is there any ideas ?
public void updateMENAGE(int id, int a16, int b17, String rm_18_1ts,
String rm_18_2ts, int c19, int d20, int e21) {
ContentValues values = new ContentValues();
values.put(col_Type_habitat,a16);
values.put(col_Statut_occupation ,b17);
values.put(col_Nombre_ménages_habitant_logement,rm_18_1ts);values.put(col_Nombre_pièces_occupes_ménage,rm_18_2ts);
values.put(col_Mode_principal_approvisionnement_eau_potable, c19);
values.put(col_Mode_principal_éclairage,d20);
values.put(col_Mode_principal_assainissement,e21);
db.update(MENAGE,values,_id+"="+id, null);
}
public class ActivityDeux extends Activity {
DBAdapter db = new DBAdapter(this);
public void ajouter(View v) {
db.open();
db.updateMENAGE(1,a16,b17,rm_18_1ts,rm_18_2ts,c19,d20,e21);
db.close();
}
You don't need to insert new record. You need to update existing record. That is your solution
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.