listview-SQLite updating the wrong row - android

When I update the selected row it updates the wrong row for example if I select second row, it will update the first row.
Here is my code inside db controller
Public boolean updateContact (String id, String category, String code, String description, String unit, String quantity) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.Col_2 , category);
values.put(FeedReaderContract.FeedEntry.Col_3 , code);
values.put(FeedReaderContract.FeedEntry.Col_4 , description);
values.put(FeedReaderContract.FeedEntry.Col_5 , unit);
values.put(FeedReaderContract.FeedEntry.Col_6 , quantity);
// updating row
database.update(TABLE_NAME ,values , FeedReaderContract.FeedEntry.Col_1 + " = ?" , new String[]{id} );
return true;
}
public ArrayList<HashMap<String, String>> getAllProducts() {
ArrayList<HashMap<String, String>> proList;
proList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM Countsheet";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor != null && cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("Category", cursor.getString(1));
map.put("Code", cursor.getString(2));
map.put("Description", cursor.getString(3));
map.put("Unit", cursor.getString(4));
map.put("Quantity", cursor.getString(5));
proList.add(map);
} while (cursor.moveToNext());
cursor.close();
}
return proList;
}
Here is my button onclick to update the listview:
Public void adddata(){
btnadddata.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v) {
boolean i = myDb.updateContact(passid , passedVar , passcode, passdesc, passunit , quantitys.getText().toString());
if (i == true)
Toast.makeText(Main2Activity.this , "Data Inserted" , Toast.LENGTH_SHORT).show();
else
Toast.makeText(Main2Activity.this , "Data Not Inserted" , Toast.LENGTH_SHORT).show();
}
}
);
}

I think you are missing 'passid' .
put 'passid' in your HashMap while fetching from database and then retrieve.

HEY GUYSSSS THANK YOU FOR ANSWERING I APPRECIATE YOU ALL , I JUST SUDDENLY GOT THE ANSWER WICH IS I JUST ADD 1 TO THE STRING.VALUEOF(ID) AND IT JUST WORKED OUT THANKS YOU GUYSSS!
//here is my code
intent.putExtra(ID_EXTRA1 , String.valueOf(id + 1));
startActivity(intent);

Related

how to overcome android sqlite where clause problem?

I am trying to read data from students table where semester column is equal to an item which is selected from spinner. listener is spinner.setOnItemSelectedListener. the problem is it stops the activity when I select the spinner item.
It runs okay when I remove the WHERE CLAUSE. but I have to use WHERE CLAUSE.
Please Help.
public ArrayList<HashMap<String, String>> GetAllStudents(){
ArrayList<HashMap<String, String>> userList = new ArrayList<>();
try{
SQLiteDatabase db = MyDB.getInstance(this).getReadableDatabase();
String query = "SELECT * FROM Students WHERE semester="+selected;
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()) {
while (cursor.moveToNext()) {
HashMap<String, String> user = new HashMap<>();
user.put("name", cursor.getString(0));
user.put("roll", cursor.getString(1));
user.put("semester", cursor.getString(2));
user.put("pass", cursor.getString(3));
userList.add(user);
}
}
}
catch (Exception e){
Toast.makeText(this, "Error "+selected, Toast.LENGTH_SHORT).show();
}
return userList;
}
EDIT
(code taken from comments to show where selected is comming from)
String selected;
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selected=parent.getItemAtPosition(position).toString();
loadStudents();
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
loadStudents();
I have solved this problem , I just missed ' ' around the selected variable
This is the solution
String query = "SELECT * FROM Students WHERE semester='"+selected+"'";

SQLite Database does't update listview item and inserts new instead

When item of listview is clicked, it gets opened in another activity which has edittext. After editing an item, when I save it, item does not get updated in the listview but it inserts a new entry in listview.
How can I update existing item without inserting new?
Here is my code
Activity: TRList.class
ArrayList<HashMap<String, String>> items = new ArrayList<>();
List<TRListFormat> list = trDb.getAllReminders();
for (TRListFormat val : list) {
HashMap<String, String> map = new HashMap<>();
map.put("title",val.getTitle());
map.put("description", val.getDes());
map.put("date", val.getDate());
map.put("time", val.getTime());
items.add(map);
}
adapter = new SimpleAdapter(this, items, R.layout.tr_list_format,
new String[] { "title", "description", "date", "time" },
new int[] {R.id.tbr_title, R.id.tbr_des, R.id.tbr_date, R.id.tbr_time });
lv = (ListView)findViewById(R.id.tbr_list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(TRList.this, TRTimeReminder.class);
intent.putExtra("remId", (int)id);
startActivity(intent);
}
});
When listView item is clicked, it opens another activity
TRTimeReminder.class I have set save button in menu
case R.id.menu_tbr_done:
String title = edTitle.getText().toString();
String des = edDes.getText().toString();
String time = timeView.getText().toString();
String date = dateView.getText().toString();
Bundle extras = getIntent().getExtras();
if(extras != null) {
int value = extras.getInt("remId");
if (value > 0) {
trDb.updateReminder(new TRListFormat(value, title, des, date, time));
}
}
else{
trDb.addReminder(new TRListFormat(title, des, date, time));
}
Intent i = new Intent(getApplicationContext(), TRList.class);
startActivity(i);
edTitle.getText().clear();
edDes.getText().clear();
dateView.setText(currDate);
timeView.setText(currTime);
return true;
TRDBHelper.class
//Add new reminder
void addReminder(TRListFormat format){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_TITLE, format.getTitle());
values.put(COLUMN_DES, format.getDes());
values.put(COLUMN_DATE, format.getDate());
values.put(COLUMN_TIME, format.getTime());
db.insert(TABLE_NAME, null, values);
db.close();
}
//Update single reminder
public void updateReminder(TRListFormat format){
SQLiteDatabase db = this.getWritableDatabase();
int id = format.getId();
ContentValues values = new ContentValues();
values.put(COLUMN_ID, format.getId());
values.put(COLUMN_TITLE, format.getTitle());
values.put(COLUMN_DES, format.getDes());
values.put(COLUMN_DATE, format.getDate());
values.put(COLUMN_TIME, format.getTime());
db.update(TABLE_NAME, values, COLUMN_ID+ " = " +id, null);
db.close();
}
I think there's problem with your adapter. There are 2 possible issues.
Data of adapter are not updated. You're saying opposite, new value is added to ListView. Are you really sure?
You haven't called your adapter's method notifyDataSetChanged() after you've changed values.

Key value pairs from sqlite to spinner

Could someone show me the correct way to achieve this.
I have setup a hashmap from a sqlite query as follows
public HashMap<String, String> getData(){
HashMap<String,String> user = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_DEVICES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount() > 0){
user.put("device_name", cursor.getString(1));
user.put("id", cursor.getString(3));
}
cursor.close();
db.close();
// return user
return user;
}
I then want a spinner where the device names are displayed but when selected its the id that is then used for the next action
I was thinking something like this , but I am not sure exactly how.
private void loadLockScreenSpinner() {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String,String> hm = db.getData();
String device_name = hm.get("device_name");
String id = hm.get("id");
ArrayAdapter<HashMap<String, String>> adapter = new ArrayAdapter<HashMap<String,String>>(this, android.R.layout.simple_spinner_item);
adapter.add(hm);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
devicesSpinner.setAdapter(adapter);
devicesSpinner.setWillNotDraw(false);
}
Not sure what to put in the onItemSelected

cannot able to insert more than one row in android SQLite DB

I am working on a project where 6 edittext fields are inserted into the the database when i click the save button and it will be viewed in a list... I can able to achieve those things but problem is that i could not able to insert multiple rows into the DB. The listview is showing only the first inserted values always eventhough if i insert again. Please help me for this solution.... My code for table creation and insertion is as follows for your reference
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_TABLE_QUERY = null;
// Used
CREATE_TABLE_QUERY = "CREATE TABLE IF NOT EXISTS userMaster(Bar CHAR(25),Product CHAR(15), Name TEXT,Mrp CHAR(15),Quantity CHAR(15), Tax CHAR(15));";
db.execSQL(CREATE_TABLE_QUERY);
L.i("userMaster Table created");
}
public void insertDetails(String bar, String mrp, String quantity,
String tax, String product, String name) {
SQLiteDatabase dbase = this.getReadableDatabase();
ContentValues cv = new ContentValues();
cv.put("bar", bar);
cv.put("product", product);
cv.put("name", name);
cv.put("mrp", mrp);
cv.put("quantity", quantity);
cv.put("tax", tax);
dbase.insert("userMaster", null, cv);
dbase.close();
} <br>
public void insertUserMaster(String bar, String mrp, String quantity,
String tax, String product, String name) {
SQLiteDatabase SqlDB = getWritableDatabase();
SqlDB.delete("userMaster", null, null);
String INSERT = "insert into userMaster (Bar,Product,Name,Mrp,Quantity,Tax) values (?,?,?,?,?,?)";
SQLiteStatement insertstatment = SqlDB.compileStatement(INSERT);
insertstatment.bindString(1, bar);
insertstatment.bindString(2, product);
insertstatment.bindString(3, name);
insertstatment.bindString(4, quantity);
insertstatment.bindString(5, mrp);
insertstatment.bindString(6, tax);
insertstatment.executeInsert();
SqlDB.close();
close();
} <br>
The array list representation is as follows
public ArrayList<HashMap<String, String>> getdata() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query("userMaster", null, null, null, null, null,
null, null);
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
if (cursor != null) {
if (cursor.getCount() > 0 && cursor.moveToFirst()) {
do {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("bar", cursor.getString(0));
hm.put("product", cursor.getString(1));
hm.put("name", cursor.getString(2));
hm.put("mrp", cursor.getString(3));
hm.put("quantity", cursor.getString(4));
hm.put("tax", cursor.getString(5));
arraylist.add(hm);
} while (cursor.moveToNext());
}
}
cursor.close();
db.close();
return arraylist;
}
Use proper query to avoid those issue. Before inserting check whether you are deleting the existing table..
In method insertUserMaster you delete all data before insert.
Remove this line:
SqlDB.delete("userMaster", null, null);

Put the data from sqlite into hashmap in list form

public class ABC extends ListActivity {
static final ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.abc_list);
SimpleAdapter adapter = new SimpleAdapter(
this,
list,
R.layout.abc_list_row,
new String[] {"AAA","BBB","CCC"},
new int[] {R.id.aa,R.id.bb, R.id.cc,}
);
add();
setListAdapter(adapter);
}
private void add() {
DatabaseA databaseHelper = new DatabaseA(this);
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor c= db.rawQuery("select * from data", null);
HashMap<String,String> temp = new HashMap<String,String>();
while(c.moveToNext()){
Log.d("Debug", c.getString(2));
temp.put("AAA", c.getString(1));
temp.put("BBB", c.getString(2));
temp.put("CCC", c.getString(3));
list.add(temp);
}
c.close();
db.close();
for (Map.Entry<String, String> entry : temp.entrySet()) {
String xx= entry.getKey();
String yy = entry.getValue();
Log.d("data", xx+" : "+yy);
}
}
My Logcat:
D/Debug(657): New york
D/Debug(657): New moon
D/data(657): AAA : Aug 20, 2012 3:57:02 PM
D/data(657): BBB : New moon
D/data(657): CCC : Title
My problem is it always left out the first data from sqlite in this list. Besides, everytime i press a button to view this list, it will add those data into this list although they are already exist. I just want to view those data in sqlite in list form. Any way to solve this. Thanks.
You need to create your Map inside your while loop
while(c.moveToNext()){
Map<String,String> temp = new HashMap<String,String>();
Log.d("Debug", c.getString(2));
temp.put("AAA", c.getString(1));
temp.put("BBB", c.getString(2));
temp.put("CCC", c.getString(3));
list.add(temp);
}
Add cursor moveToFirst() like this:
Cursor c= db.rawQuery("select * from data", null);
HashMap<String,String> temp = new HashMap<String,String>();
c.moveToFirst();
while(c.moveToNext()){
Log.d("Debug", c.getString(2));
temp.put("AAA", c.getString(1));
temp.put("BBB", c.getString(2));
temp.put("CCC", c.getString(3));
list.add(temp);
}
And please post the source code when the button is clicked!

Categories

Resources