Can someone tell me what is wrong with coding below. Why I can not update next positions?
public static void deleteItemsFromProduct(long nomer) {
cursor_child = DataSourceChild.queryAllinChild();
if (cursor_child != null) {
par = new String[]{String.valueOf(nomer)};
db_child.delete(DBHelperChild.TABLE_ITEMS_AND_PRICES, DBHelperChild.COLUMN_NOMER + "=?", par);
Prod.setProdId(nomer);
cv_child = new ContentValues();
cv_child.put(DBHelperChild.COLUMN_NOMER, Prod.getProdId());
par = new String[]{String.valueOf(nomer+1)};
int updCount = db_child.update(DBHelperChild.TABLE_ITEMS_AND_PRICES, cv_child, DBHelperChild.COLUMN_NOMER + "=?", par);
Log.d(LOG_TAG, "updated rows count = " + updCount);
if (cursor_child.moveToFirst()) {
Log.d(LOG_TAG, "--- Left in the table for items and prices: ---");
do {
Log.d(LOG_TAG,
"item id = " + cursor_child.getInt(item_and_price_idColIndex)
+ ", item name = " + cursor_child.getString(item_ColIndex)
+ ", item price = " + cursor_child.getInt(price_ColIndex)
+ ", product nomer = " + cursor_child.getInt(nomer_ColIndex));
} while (cursor_child.moveToNext());
} else {
}
} else {
Log.d(LOG_TAG, "Cursor is null");
// закрываем курсор
cursor_child.close();
}
}
The idea is to delete set of items in the list while getting id (nomer) from another list. This code updates only the next id nomer after deleted but not others down the list.
Thank you.
Related
I am trying to repeat certain data from a table in a ListView with one row changing each iteration of the item. I want to have a user input an int of the times to repeat and press a button to update the list.
I am working with dates as the updating item. So if a user inputs '3', I want 3 rows added to the list, and inserted into the table, adding 1 month to the date for the 3 months.
Main Activity
planAheadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (planAheadMonths.getText().toString().trim().isEmpty()) {
Toast.makeText(getBaseContext(), "Add months to plan by", Toast.LENGTH_SHORT).show();
} else {
int plan = Integer.parseInt(planAheadMonths.getText().toString());
mDBHelper.updateCheckingPlanner(plan, mChecking.getCheckingId());
planAheadMonths.setText("");
mDBHelper.getTransRepeater(plan, mChecking.getCheckingId());
}
}
});
DBHelper
public void getTransactionRepeater(int repeat, int id) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = TRANSACTION_DATE + " BETWEEN " + getCurrentMonth() + " AND " + getFutureMonth() + " AND " +
TRANSACTION_CHECKING_ID + " = " + id + " AND " + TRANSACTION_REPEAT + " != 'NONE' ";
String[] whereargs = new String[1];
Cursor res = db.query(TABLE_TRANSACTIONS, null, whereclause, null, null, null, TRANSACTION_DATE + " ASC, " + TRANSACTION_ID);
db.beginTransaction();
while (res.moveToNext()) {
if (res.getString(res.getColumnIndex(TRANSACTION_REPEAT)).equals("MONTH")) {
for (int i = 0; i < repeat; i++) {
+ i);
ContentValues cv = new ContentValues();
cv.put(TRANSACTION_NAME, res.getString(res.getColumnIndex(TRANSACTION_NAME)));
cv.put(TRANSACTION_TYPE, res.getString(res.getColumnIndex(TRANSACTION_TYPE)));
cv.put(TRANSACTION_DATE, sdf.format(cFuture.getTime()) + res.getString(res.getColumnIndex(TRANSACTION_NAME)) + i);
cv.put(TRANSACTION_AMOUNT, res.getInt(res.getColumnIndex(TRANSACTION_AMOUNT)));
cv.put(TRANSACTION_NOTES, res.getString(res.getColumnIndex(TRANSACTION_NOTES)));
cv.put(TRANSACTION_REPEAT, res.getString(res.getColumnIndex(TRANSACTION_REPEAT)));
cv.put(TRANSACTION_CHECKING_ID, res.getInt(res.getColumnIndex(TRANSACTION_CHECKING_ID)));
cv.put(TRANSACTION_NEW_BALANCE, res.getInt(res.getColumnIndex(TRANSACTION_NEW_BALANCE)));
cv.put(TRANSACTION_CREDIT_ID, res.getString(res.getColumnIndex(TRANSACTION_CREDIT_ID)));
whereargs[0] = res.getString(res.getColumnIndex(TRANSACTION_DATE));
db.insert(TABLE_TRANSACTIONS, null, cv);
}
}
}
res.close();
db.setTransactionSuccessful();
db.endTransaction();
}
I have a list of Buttons in RecycleView. I have implemented OnClickListener on every Button in list:
#Override
public void onClick(View v) {
int position = getAdapterPosition(); // gets item position
if (position != RecyclerView.NO_POSITION) { // Check if an item was deleted, but the user clicked it before the UI removed it
// We can access the data within the views
Toast.makeText(context, position + " " + washLocations.get(position), Toast.LENGTH_SHORT).show();
Log.d("myTag", "This is my message");
Integer isFav = washLocations.get(position).getFav();
WashLocation w = washLocations.get(position);
Integer id = w.getId();
List<WashLocation> washLocation = dataBaseHelper.getWashLocation();
for(WashLocation wash : washLocation){
if(wash.getId().equals(w.getId())){
dataBaseHelper.updateWashLocation(w);
return;
}
}
w.setFav(isFav == 1 ? 0 : 1);
dataBaseHelper.addWashLocationToFav(w);
favorite.setText(w.getFav() == 1 ? "Usuń z ulubionych" : "Dodaj do ulubionych");
}
}
The case is whenever I want to compare wash Id from Wash object which has been already clicked I always get that id is null. But when I print every object from DB every wash object has their own unique ID.
While creating table I add autoincrement:
String CREATE_TABLE = "CREATE TABLE " + TABLE_WASH_LOCATION + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + COL_WASH_NAME + " TEXT,"
+ COL_WASH_CITY + " TEXT," + COL_WASH_STREET + " TEXT," + COL_LAT + " TEXT," + COL_LNG + " TEXT," + COL_FAV + " INTEGER" + ")";
db.execSQL(CREATE_TABLE);
Example:
UPDATE:
The list of washLocation in adapter is popualted:
washLocations = new ArrayList<>();
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mAdapter = new MyAdapter(washLocations, this);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
MyAsyncTask myAsyncTask = new MyAsyncTask();
try {
JSONObject jsonObject = myAsyncTask.execute(latitude, longitude, radius).get();
String lat;
String lng;
String name = "";
String city = "";
if (jsonObject.has("results")) {
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int n = 0; n < jsonArray.length(); n++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(n);
lat = jsonObject1.getJSONObject("geometry").getJSONObject("location").get("lat").toString();
lng = jsonObject1.getJSONObject("geometry").getJSONObject("location").get("lng").toString();
JSONObject oName = jsonArray.getJSONObject(n);
if (oName.has("name")) {
name = oName.getString("name");
}
JSONObject oVicinity = jsonArray.getJSONObject(n);
if (oVicinity.has("vicinity")) {
city = oVicinity.getString("vicinity");
}
WashLocation w = new WashLocation(name, lat, lng, 0, getCity(city), null);
washLocations.add(w);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
I'm not really sure that I understand what you are trying to do, i cleaned up your code a bit and added comments starting with a Q, can you answer those questions ?
#Override
public void onClick(View v) {
int position = getAdapterPosition(); // gets item position
if (position != RecyclerView.NO_POSITION) { // Check if an item was deleted, but the user clicked it before the UI removed it
WashLocation w = washLocations.get(position);
// We can access the data within the views
// Q: Does this show the right WashLocation ?
Toast.makeText(context, position + " " + w, Toast.LENGTH_SHORT).show();
Log.d("myTag", "This is my message");
Integer isFav = w.getFav();
Integer id = w.getId();
// Q: Will this list be different from washLocations ?
List<WashLocation> washLocation = dataBaseHelper.getWashLocation();
for(WashLocation wash : washLocation){
if(wash.getId().equals(id)){
// Q: Why can't you execute this line immediately ?
// Q: What does this line actually do ?
dataBaseHelper.updateWashLocation(w);
return;
}
}
w.setFav(isFav == 1 ? 0 : 1);
dataBaseHelper.addWashLocationToFav(w);
favorite.setText(w.getFav() == 1 ? "Usuń z ulubionych" : "Dodaj do ulubionych");
}
}
I am trying to delete a row in sqlite database from recyclerview adapter. Based on the position of the adapter, I am deleting my row in sqlite like this :
helper = new DBHelper(v.getContext());
database = helper.getWritableDatabase();
//statement = database.compileStatement("update result set ANS =? where SNO ='" + pos + "'");
// statement = database.compileStatement("delete result where SNO ='" + pos + "'");
//statement.bindString(1, ANS);
// statement.executeInsert();
database.delete("result",
"SNO = ? ",
new String[]{Integer.toString(pos)});
Log.d("pos", "" + pos);
// helper.Delete(pos);
database.close();
but it is not deleting in my table, and I am not getting any error. What am I doing wrong?
db = this.getWritableDatabase();
int l;
l = db.delete("result", SNO = ? " , new String[]{pos+1});
if (l > 0) {
Toast.makeText(context, "Removed "+(pos+1), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
}
db.close();
Here you have pass "pos" so you have not passed right SNO(pos).
Please check SNO is passes on delete query
Try this method ,
public int deleteItem(String id) {
open();
int b = 0;
try {
b = db.delete(DATABASE_TABLE_POST_ITEMS, TAG_PLUS + " = '" + id + "'", null);
} catch (Exception e) {
e.printStackTrace();
}
close();
return b;
}
call this by using this sentence,
holder.img_plus.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
dbhelper.deleteItem((chatMessageList.get((int) v.getTag()).getListid()));
chatMessageList.remove(position);
notifyDataSetChanged();
}
});
I'm new to android, and I don't know why I am getting CursorIndexOutOfBoundsException: Index 0 requested with a size of 0. I'm trying to display it on another class using listview. Here are my codes:
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
// TODO Auto-generated method stub
position = position + 1;
Cursor a = MainActivity.sqldb
.rawQuery("Select name from " + MainActivity.tblpb
+ " where _pid = " + position + ";", null);
String aa = a.getString(a.getColumnIndex("name"));
Cursor b = MainActivity.sqldb
.rawQuery("Select phone from " + MainActivity.tblpb
+ " where _pid = " + position + ";", null);
String bb = b.getString(b.getColumnIndex("phone"));
Intent next = new Intent (this, ThirdActivity.class);
startActivity(next);
}
I know that there's something really wrong here. And I wonder what it is.
Create Table:
sqldb = this.openOrCreateDatabase(dbpb, MODE_PRIVATE, null);
sqldb.execSQL("CREATE TABLE IF NOT EXISTS "
+ tblpb
+ " (_pid INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, phone INTEGER);");
Insert Table:
sqldb.execSQL("Insert into " + tblpb
+ " (name, phone) Values ('" + x + "' , '"
+ y + "' );");
Try doing this:
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
// TODO Auto-generated method stub
String aa = null;
String bb = null;
// do not alter the position, DB starts the same position as ItemClick for
// adapter view
// position = position + 1;
Cursor a = MainActivity.sqldb
.rawQuery("Select name from " + MainActivity.tblpb
+ " where _pid = " + position + ";", null);
if(a != null){
// Force cursor to position 0
if(a.moveToFirst()){
// make sure the column actually exists
aa = a.getString(a.getColumnIndexOrThrow("name"));
Log.d("Cursor A - Name", "name column val: "+ aa);
}else{
Log.d("Cursor A", "cursor A failed to move to first");
}
}else{
Log.d("Cursor A null", "cannot access cursor A");
}
Cursor b = MainActivity.sqldb.rawQuery("Select phone from " + MainActivity.tblpb + " where _pid = " + position + ";", null);
if(b != null){
// Force cursor to position 0
if(b.moveToFirst()){
// make sure the column actually exists
bb = b.getString(b.getColumnIndexOrThrow("phone"));
Log.d("Cursor B - Phone", "phone column val: "+ bb);
}else{
Log.d("Cursor B", "cursor B failed to move to first");
}
}else{
Log.d("Cursor B null", "cannot access cursor B");
}
Intent next = new Intent (this, ThirdActivity.class);
next.putExtra("NAME", aa);
next.putExtra("PHONE", bb);
startActivity(next);
}
Then in your second Activity do:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.content_file);
Bundle extras = getIntent().getExtras();
if(extras != null){
String aa = extras.getString("NAME");
String bb = extras.getString("PHONE");
// Since you cannot tell if these are null check them
if(aa != null){
// ... Use on your TextView
}
// Since you cannot tell if these are null check them
if(bb != null){
// ... Use on your TextView
}
}
}
The error indicates that you are trying to access the first element (index 0) of an empty list (size 0) meaning your queries are returning no results. Make sure your queries are correct.
EDIT:
It's also a good idea to call cursor.moveToFirst() and check its result before doing any operations on the data from a query.
http://developer.android.com/reference/android/database/Cursor.html#moveToFirst%28%29
I am retrieving all records from database and saving all records in array list.when i show array list records ,repeated data displayed,i don't know what's the prolblem??
Calling this function in view_record class:
public ArrayList<tuple> getdata() { // TODO Auto-generated method stub
tuple obj=new tuple();
Cursor c = ourDatabase.query(DATABASE_TABLE, PROJECTION_ALL, null, null, null, null, null);
if(c == null) {
return null;
}
ArrayList <tuple> data = new ArrayList<tuple>();
// String result = " ";
int i=0;
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
obj.ROWID= c.getString(c.getColumnIndexOrThrow(KEY_ROWID));
obj.CNAME= c.getString(c.getColumnIndexOrThrow(KEY_CNAME));
obj.SNAME= c.getString(c.getColumnIndexOrThrow(KEY_SNAME));
obj.FAMILY= c.getString(c.getColumnIndexOrThrow(KEY_FAMILY));
obj.LOCATION= c.getString(c.getColumnIndexOrThrow(KEY_LOCATION));
obj.IMAGE1= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE1));
obj.IMAGE2= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE2));
obj.IMAGE3= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE3));
data.add(i, obj);
i++;
}
c.close();
return data; }
My view_record class
public class view_record extends Activity {
#Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.db_view);
TextView tv=(TextView) findViewById(R.id.tvSqlinfo);
ImageView img=(ImageView) findViewById(R.id.img_view);
db_handler info=new db_handler(this);
info.open();
// Log.d("abc", "adb");
ArrayList <tuple> data=info.getdata();
Log.d("abc", "adb");
String result="";
for(int i=0;i<data.size();i++){
result +=" " + data.get(i).ROWID + " " + data.get(i).CNAME + " " + data.get(i).SNAME + " " + data.get(i).FAMILY + " " + data.get(i).LOCATION + "\n";
tv.setText(result);
img.setImageBitmap(Utilities.getImage(data.get(0).IMAGE2));
}
info.close(); } }
I want to view as follows :
" 1 cname sname family location "
" 2 cname sname family location "
But i am getting
" 2 cname sname family location "
" 2 cname sname family location "
Means last record displayed two times.
and one more thing ,i want to get all records where cname=something,getting error while doing it so
you are not making a new project in your for loop. That is whay you are getting same results. just do...
on start of for loop add this line obj=new tuple();
Answer to your Second Question
for(int i=0;i<data.size();i++){
result +=" " + data.get(i).ROWID + " " + data.get(i).CNAME + " " + data.get(i).SNAME + " " + data.get(i).FAMILY + " " + data.get(i).LOCATION + "\n";
img.setImageBitmap(Utilities.getImage(data.get(0).IMAGE2));
}
tv.setText(Html.fromHtml(result));