RecyclerView inside RecyclerView made wrong getItemCount() - java

So its to looks like this:
SCREENSHOT
But when I click add or less button its returning the size of the whole list.
In this case its returns 2(because the otitles.size() returns 2) Like under the item that I clicked appears another item from the list.
PARENT RecyclerView Adapter:
public class recyclercart extends RecyclerView.Adapter<recyclercart.myViewHolder> {
Context context;
ArrayList<String> list;
public static View.OnClickListener onclickup;
public static View.OnClickListener onclickdown;
public static ArrayList<String> otitles = new ArrayList<>();
public static ArrayList<String> oimages = new ArrayList<>();
public static ArrayList<String> oingridients = new ArrayList<>();
public static ArrayList<String> odependencies = new ArrayList<>();
public static ArrayList<String> oquantities = new ArrayList<>();
public static ArrayList<String> oprices = new ArrayList<>();
public static ArrayList<String> ostartprices = new ArrayList<>();
public static ArrayList<String> obrand = new ArrayList<>();
public static ArrayList<String> oid = new ArrayList<>();
Cursor gettitle, getimage, getingridients, getdependencies,getquantities, getprices, getstartprice, getbrand, getid;
ArrayList<Integer> postoremove= new ArrayList<>();
ProgressBar progressBar;
SQLiteDatabase database;
public recyclercart(Context c, ProgressBar progressBar){
context=c;
this.progressBar=progressBar;
SQLHelper helper = new SQLHelper(context);
database = helper.getWritableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM "+SQLHelper.DATABASE_TABLE, null);
list =new ArrayList<>();
cursor.moveToFirst();
do {
String lol = cursor.getString(cursor.getColumnIndex(SQLHelper.BRAND_NAME));
list.add(lol.substring(0,lol.length()-5));
}while (cursor.moveToNext());
if(cursor.moveToLast()) {
postoremove.clear();
Log.d("glavniy", "LIST: " + list.toString());
list = new ArrayList<>(removeDuplicates(list));
}
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.templatecart, parent, false );
return new myViewHolder(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, int position) {
otitles.clear();
oimages.clear();
oingridients.clear();
odependencies.clear();
oprices.clear();
oquantities.clear();
ostartprices.clear();
obrand.clear();
oid.clear();
Cursor cur = database.rawQuery("SELECT "+SQLHelper.TITLE_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "+SQLHelper.BRAND_NAME+" LIKE '%"+
list.get(position)+"%'", null);
SQLHelper helper = new SQLHelper(context);
SQLiteDatabase database = helper.getWritableDatabase();
gettitle = database.rawQuery("SELECT "+SQLHelper.TITLE_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getimage = database.rawQuery("SELECT "+SQLHelper.IMAGESRC_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getingridients = database.rawQuery("SELECT "+SQLHelper.INGRIDIENTS_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getdependencies = database.rawQuery("SELECT "+SQLHelper.DEPENDENCIES_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getprices = database.rawQuery("SELECT "+SQLHelper.PRICE_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getquantities = database.rawQuery("SELECT "+SQLHelper.QUANTITY_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getstartprice = database.rawQuery("SELECT "+SQLHelper.START_PRICE+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getbrand = database.rawQuery("SELECT "+SQLHelper.BRAND_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getid = database.rawQuery("SELECT "+SQLHelper.KEY_ID+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
if (gettitle.moveToFirst() && getimage.moveToNext() && getingridients.moveToFirst() && getdependencies.moveToFirst()
&& getprices.moveToFirst() && getquantities.moveToFirst() && getstartprice.moveToFirst() && getbrand.moveToFirst() && getid.moveToFirst()) {
do {
otitles.add(gettitle.getString(gettitle.getColumnIndex(SQLHelper.TITLE_NAME)));
oimages.add(getimage.getString(getimage.getColumnIndex(SQLHelper.IMAGESRC_NAME)));
oingridients.add(getingridients.getString(getingridients.getColumnIndex(SQLHelper.INGRIDIENTS_NAME)));
odependencies.add(getdependencies.getString(getdependencies.getColumnIndex(SQLHelper.DEPENDENCIES_NAME)));
oprices.add(getprices.getString(getprices.getColumnIndex(SQLHelper.PRICE_NAME)));
oquantities.add(getquantities.getString(getquantities.getColumnIndex(SQLHelper.QUANTITY_NAME)));
ostartprices.add(getstartprice.getString(getstartprice.getColumnIndex(SQLHelper.START_PRICE)));
obrand.add(getbrand.getString(getbrand.getColumnIndex(SQLHelper.BRAND_NAME)));
oid.add(getid.getString(getid.getColumnIndex(SQLHelper.KEY_ID)));
Log.d("glavniy", String.valueOf(ostartprices));
} while (gettitle.moveToNext() && getimage.moveToNext() && getingridients.moveToNext() && getdependencies.moveToNext()
&& getprices.moveToNext() && getquantities.moveToNext() && getstartprice.moveToNext() && getbrand.moveToNext() && getid.moveToNext());
}
if(gettitle.moveToLast()) {
Log.d("glavniy", "MOVETOLAST");
holder.recyclerView.setLayoutManager(new LinearLayoutManager(context));
holder.recyclerView.setAdapter(new recyclerOrdersAdapter(context, otitles, oimages, oingridients, oquantities, oprices, ostartprices
, obrand, odependencies, oid));
}
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("resources");
reference.child(list.get(position)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
holder.title.setText(snapshot.child("nameBrand").getValue().toString());
Glide.with(context).load(snapshot.child("imageBrand").getValue().toString()).into(holder.imageView);
try {
if(recyclerSearchRecycler.timeCheck(snapshot.child("times").child("startTime").getValue().toString(),
snapshot.child("times").child("closeTime").getValue().toString())){
holder.open.setText("OPEN");
}else {holder.open.setText("CLOSED");}
} catch (ParseException e) {
e.printStackTrace();
}
reference.child(list.get(position)).child("addresses").addListenerForSingleValueEvent(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
ArrayList<String> addresses = new ArrayList<>();
addresses.add(dataSnapshot.getValue().toString());
Log.d("glavniy", dataSnapshot.getValue().toString());
if(addresses.size()==snapshot.getChildrenCount()) {
try {
float distance = activityBrandPage.getNearestRest(addresses, context);
Log.d("glavniy", "DIST: " + distance);
if (distance <= 1000) {
progressBar.setVisibility(View.INVISIBLE);
holder.delivery.setText("Delivery: 400 AMD");
} else if (distance > 1000 && distance <= 2000) {
holder.delivery.setText("Delivery: 500 AMD");
progressBar.setVisibility(View.INVISIBLE);
} else if (distance > 2000 && distance <= 3000) {
holder.delivery.setText("Delivery: 600 AMD");
} else if (distance > 3000 && distance <= 4000) {
holder.delivery.setText("Delivery: 700 AMD");
progressBar.setVisibility(View.INVISIBLE);
}
if (search.prog != null) {
search.prog.setVisibility(View.INVISIBLE);
}
} catch (IOException e) {
e.printStackTrace();
progressBar.setVisibility(View.VISIBLE);
Toast.makeText(context, "Failed, please restart", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public static class myViewHolder extends RecyclerView.ViewHolder {
TextView title, delivery, open;
ImageView imageView;
public static RecyclerView recyclerView;
public myViewHolder(#NonNull View itemView) {
super(itemView);
imageView=itemView.findViewById(R.id.ivBrandCart);
recyclerView=itemView.findViewById(R.id.recyclerMainCart);
title=itemView.findViewById(R.id.tvBrandCart);
delivery=itemView.findViewById(R.id.tvdelivery);
open=itemView.findViewById(R.id.opentv);
}
}
CHILD RecyclerView Adapter:
public class recyclerOrdersAdapter extends RecyclerView.Adapter<recyclerOrdersAdapter.myViewHolder> {
public static Context context;
SQLiteDatabase database;
public static int pos;
public static ArrayList<String> otitles = new ArrayList<>();
public static ArrayList<String> oimages = new ArrayList<>();
public static ArrayList<String> oingridients = new ArrayList<>();
public static ArrayList<String> odependencies = new ArrayList<>();
public static ArrayList<String> oquantities = new ArrayList<>();
public static ArrayList<String> oprices = new ArrayList<>();
public static ArrayList<String> ostartprices = new ArrayList<>();
public static ArrayList<String> obrand = new ArrayList<>();
public static ArrayList<String> oids = new ArrayList<>();
#SuppressLint("Recycle")
public recyclerOrdersAdapter(Context c, ArrayList<String> titles, ArrayList<String> images, ArrayList<String> ingridients,
ArrayList<String> quantities, ArrayList<String> prices, ArrayList<String> startprices, ArrayList<String> brands,
#Nullable ArrayList<String> dependencies, ArrayList<String> ids){
System.out.println("hi");
otitles=new ArrayList<>(titles);
oimages= new ArrayList<>(images);
oingridients=new ArrayList<>(ingridients);
oquantities=new ArrayList<>(quantities);
oprices=new ArrayList<>(prices);
ostartprices=new ArrayList<>(startprices);
obrand=new ArrayList<>(brands);
oids=new ArrayList<>(ids);
assert dependencies != null;
odependencies=new ArrayList<>(dependencies);
context = c;
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.templateorders, parent, false );
return new myViewHolder(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, int position) {
System.out.println("hello n");
if(obrand.size()!=0) {
String title = otitles.get(position);
String image = oimages.get(position);
String ingridient = oingridients.get(position);
String dependencie = odependencies.get(position);
String priceik = oprices.get(position);
String quanik = oquantities.get(position);
ingridient = ingridient.replaceAll("[^a-zA-Z0-9, ]", "");
if (ingridient.contains("null, ")) {
ingridient = ingridient.replaceAll("null, ", "");
} else if (ingridient.contains("null,")) {
ingridient = ingridient.replaceAll("null,", "");
} else {
ingridient = ingridient.replaceAll("null", "");
}
dependencie = dependencie.replaceAll("[^a-zA-Z0-9, ]", "");
System.out.println("ingridients " + ingridient);
holder.title.setText(title);
Glide.with(context).load(image).placeholder(R.drawable.elipsis).into(holder.imageView);
holder.ingridients.setText(ingridient);
if(odependencies.get(position)!=null) {
holder.dependencies.setText(dependencie);
}
if(!priceik.contains("$")) {
holder.price.setText(priceik + "$");
}else {
holder.price.setText(priceik);
}
holder.quantity.setText(quanik);
holder.startprice.setText(ostartprices.get(position));
holder.id.setText(oids.get(position));
SQLHelper helper = new SQLHelper(context);
database = helper.getWritableDatabase();
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("glavniy", "TITLE: "+holder.title.getText().toString());
Log.d("glavniy", "position is" + String.valueOf(position));
SQLHelper helper = new SQLHelper(context);
SQLiteDatabase database = helper.getWritableDatabase();
database.execSQL("DELETE FROM " + SQLHelper.DATABASE_TABLE + " WHERE (" + SQLHelper.KEY_ID +
"='" + holder.id.getText().toString() + "')");
notifyItemRemoved(position);
Log.d("glavniy", DatabaseUtils.dumpCursorToString(database.rawQuery("SELECT * FROM " + SQLHelper.DATABASE_TABLE, null)));
}
});
holder.up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("glavniy", "TITLE: "+holder.title.getText().toString());
int o = Integer.parseInt(holder.quantity.getText().toString())+1;
holder.quantity.setText(String.valueOf(o));
int o1 = Integer.parseInt(holder.startprice.getText().toString()) * Integer.parseInt(holder.quantity.getText().toString());
holder.price.setText(o1 + "$");
Log.d("glavniy", "UPDATED");
database.execSQL("UPDATE " + SQLHelper.DATABASE_TABLE + " SET " + SQLHelper.QUANTITY_NAME + "='" + holder.quantity.getText() + "' WHERE ("
+ SQLHelper.KEY_ID + "='" + holder.id.getText() + "')");
database.execSQL("UPDATE " + SQLHelper.DATABASE_TABLE + " SET " + SQLHelper.PRICE_NAME + "='" + holder.price.getText() + "' WHERE ("
+ SQLHelper.KEY_ID + "='" + holder.id.getText() + "')");
Log.d("glavniy", DatabaseUtils.dumpCursorToString(database.rawQuery("SELECT * FROM " + SQLHelper.DATABASE_TABLE, null)));
}
});
holder.down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Integer.parseInt(holder.quantity.getText().toString()) != 1) {
holder.quantity.setText(String.valueOf(Integer.parseInt(holder.quantity.getText().toString())-1));
int o1 = Integer.parseInt(holder.price.getText().toString().replace("$","")) - Integer.parseInt(holder.startprice.getText().toString());
holder.price.setText(o1 + "$");
database.execSQL("UPDATE " + SQLHelper.DATABASE_TABLE + " SET " + SQLHelper.QUANTITY_NAME + "='" + holder.quantity.getText() + "' WHERE ("
+ SQLHelper.KEY_ID + "='" + holder.id.getText() + "')");
database.execSQL("UPDATE " + SQLHelper.DATABASE_TABLE + " SET " + SQLHelper.PRICE_NAME + "='" + holder.price.getText() + "' WHERE ("
+ SQLHelper.KEY_ID + "='" + holder.id.getText() + "')");
Log.d("glavniy", DatabaseUtils.dumpCursorToString(database.rawQuery("SELECT * FROM " + SQLHelper.DATABASE_TABLE, null)));
}
}
});
}
}
#Override
public int getItemCount() {
return otitles.size();
}
#SuppressLint("StaticFieldLeak")
public class myViewHolder extends RecyclerView.ViewHolder {
public TextView title, price, ingridients, dependencies, up,down, quantity, startprice, id;
public ImageView imageView;
public ImageView delete;
public myViewHolder(#NonNull View itemView) {
super(itemView);
id=itemView.findViewById(R.id.textView7);
startprice=itemView.findViewById(R.id.textView6);
quantity = itemView.findViewById(R.id.ordersQuanity);
up=itemView.findViewById(R.id.upBtn);
down=itemView.findViewById(R.id.downBtn);
delete=itemView.findViewById(R.id.removeButton);
title = itemView.findViewById(R.id.titleOfOrder);
price = itemView.findViewById(R.id.priceOfOrder);
imageView=itemView.findViewById(R.id.imageOfOrde);
ingridients = itemView.findViewById(R.id.ingridientsOfOrder);
dependencies = itemView.findViewById(R.id.dependenciesOfOrder);
}
}
}
How can I make to return exactly size of list that PARENT RecyclerView sends (of that position)?

Oh... This is really hard to read.
I will try to give you some tips for better architecture. I hope you are fine with it.
Why are you using so many lists? Why you don't make one list of custom madr classes with all the data like title, image, ingredient itp.
Why you name the type of class recyclercart instead of RecyclerCard. In Kotlin and in Java programmers have not written rule that classes should be named from big letter and in camelCase stale.
The other thing is that you melted together using database and uploadung data into the view processes. It is not good. It would be better to have other class like DatabaseManager or something like this, which will make the job of taking data from the database etc. If you will do that your RecyclerViewAdapter will get list of ready items in the constructor and the only responsibility of this class will be to show the data in the views. The code will be simplified and maybe the mistake will be more visible. If you want to upload children data dynamically (during scrolling) you cab, but the code for it should be places in the DatabaseManager or Helper, too. If number of data is not big- it could be better to upload it before adapter is created even and just put Map<Item,List instead.
I would also check the way of using SQLiteHelper. I am not sure, but something tells me that you are creating few databases in one program. It can be damgerous. Please, just check it. Remember to create database once and just connect to it few times. About this one I am not sure. I have to less time to investigate yourt code.
About my tips: checkout SOLID; you will have a lot more clear architecture.

Ok finally I found solution. Thats pretty funny but problem was that ArrayLists were static. So I just removed static field and everything works fine now.

Related

how to add another column in another spinner of same or other table in android studio

how to add second column value of same or other table in another spinner from sqlite database using button click in android studio
retrievebtn.setOnClickListener(arg0 -> {
// TODO Auto-generated method stub
nos.clear();
names.clear();
//OPEN
db.openDB();
//RETRIEVE
Cursor c = db.getAllValues();
c.moveToFirst();
while(!c.isAfterLast())
{
String no = c.getString(0);
nos.add(no);
String name = c.getString(1);
names.add(name);
c.moveToNext();
}
//CLOSE
c.close();
db.close();
//SET IT TO SPINNER
sp1.setAdapter(adapter);
sp2.setAdapter(adapter);
});
Perhaps consider the following working example.
This consists of 2 spinners and 3 buttons. The buttons controlling from which of the 3 tables the data is extracted for the 2nd spinner.
The trick, as such, used is to use AS to utilise a standard column name, irrespective of the actual column name. The one difference is that this rather than using a normal adapter, it utilises a CursorAdapter (SimpleCursorAdapter as it's quite flexible) and thus you can extract the data directly.
First the SQLite side i.e. the class that extends SQLiteOpenHelper :-
class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "the_database.db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE1_TABLE = "_table1";
public static final String TABLE1_ID_COL = BaseColumns._ID;
public static final String TABLE1_NAME_COL = "_name";
public static final String TABLE1_DESC_COL = "_desc";
private static final String TABLE1_CREATE_SQL =
"CREATE TABLE IF NOT EXISTS " + TABLE1_TABLE + "(" +
TABLE1_ID_COL + " INTEGER PRIMARY KEY" +
"," + TABLE1_NAME_COL + " TEXT UNIQUE" +
"," + TABLE1_DESC_COL + " TEXT " +
");";
public static final String TABLE2_TABLE = "_table2";
public static final String TABLE2_ID_COL = BaseColumns._ID;
public static final String TABLE2_TABLE1_ID_MAP_COL = "_table1_id_map";
public static final String TABLE2_NAME_COL = "_name";
private static final String TABLE2_CREATE_SQL =
"CREATE TABLE IF NOT EXISTS " + TABLE2_TABLE + "(" +
TABLE2_ID_COL + " INTEGER PRIMARY KEY" +
"," + TABLE2_TABLE1_ID_MAP_COL + " INTEGER " +
"," + TABLE2_NAME_COL + " TEXT" +
");";
public static final String TABLE3_TABLE = "_table3";
public static final String TABLE3_ID_COL = BaseColumns._ID;
public static final String TABLE3_TABLE2_ID_MAP_COL = "_table2_id_map";
public static final String TABLE3_NAME_COL = "_name";
private static final String TABLE3_CREATE_SQL =
"CREATE TABLE IF NOT EXISTS " + TABLE3_TABLE +"(" +
TABLE3_ID_COL + " INTEGER PRIMARY KEY" +
"," + TABLE3_TABLE2_ID_MAP_COL + " INTEGER " +
"," + TABLE3_NAME_COL + " TEXT " +
");";
private static volatile DBHelper INSTANCE;
private SQLiteDatabase db;
public static final String SPINNER_COLUMN1 = "_spc1";
public static final String SPINNER_COLUMN2 = "_spc2";
private DBHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
db = this.getWritableDatabase();
}
public static DBHelper getInstance(Context context) {
if (INSTANCE==null) {
INSTANCE = new DBHelper(context);
}
return INSTANCE;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE1_CREATE_SQL);
db.execSQL(TABLE2_CREATE_SQL);
db.execSQL(TABLE3_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public long insertTable1Row(String name,String description) {
ContentValues cv = new ContentValues();
cv.put(TABLE1_NAME_COL,name);
cv.put(TABLE1_DESC_COL,description);
return db.insert(TABLE1_TABLE,null,cv);
}
public long insertTable2Row(String name, long table1_id) {
ContentValues cv = new ContentValues();
cv.put(TABLE2_NAME_COL,name);
cv.put(TABLE2_TABLE1_ID_MAP_COL,table1_id);
return db.insert(TABLE2_TABLE,null,cv);
}
public long insertTable3Row(String name, long table2_id) {
ContentValues cv = new ContentValues();
cv.put(TABLE3_NAME_COL,name);
cv.put(TABLE3_TABLE2_ID_MAP_COL,table2_id);
return db.insert(TABLE3_TABLE,null,cv);
}
public Cursor getSpinnerData(String table, long map) {
String[] columns = new String[]{};
String whereClause = "";
String[] whereArgs = new String[]{String.valueOf(map)};
switch (table) {
case TABLE1_TABLE:
columns = new String[]{TABLE1_ID_COL,TABLE1_NAME_COL + " AS " + SPINNER_COLUMN1,TABLE1_DESC_COL + " AS " + SPINNER_COLUMN2};
whereClause = "";
break;
case TABLE2_TABLE:
columns = new String[]{TABLE2_ID_COL ,TABLE2_NAME_COL + " AS " + SPINNER_COLUMN1,"'-' AS " + SPINNER_COLUMN2};
whereClause = TABLE2_TABLE1_ID_MAP_COL + "=?";
break;
case TABLE3_TABLE:
columns = new String[]{TABLE3_ID_COL, TABLE3_NAME_COL + " AS " + SPINNER_COLUMN1,"'~' AS " + SPINNER_COLUMN2};
whereClause = TABLE3_TABLE2_ID_MAP_COL + "=?";
break;
}
if (map < 0) {
whereClause="";
whereArgs = new String[]{};
}
if (columns.length > 0) {
return db.query(table,columns,whereClause,whereArgs,null,null,null);
} else {
return db.query(TABLE1_TABLE,new String[]{"0 AS " + TABLE1_ID_COL + ",'ooops' AS " + SPINNER_COLUMN1,"'ooops' AS " + SPINNER_COLUMN2},null,null,null,null,null,"1");
}
}
}
as said there are three tables
a singleton approach has been utilised for the DBHelper
the most relevant aspect in regards to switching spinner data is the getSpinnerData function, which takes two parameters, the most relevant being the first the tablename which drives the resultant query.
Note the use of BaseColumns._ID ALL Cursor adapters must have a column name _id (which is what BaseColumns._ID resolves to). The column should be an integer value that uniquely identifies the row.
the 2nd parameter caters for the selection of only related data, but a negative is used to ignore this aspect.
The Activity "MainActivity" used to demonstrate is :-
public class MainActivity extends AppCompatActivity {
Button btn1, btn2, btn3;
Spinner sp1,sp2;
String[] spinnerColumns = new String[]{DBHelper.SPINNER_COLUMN1,DBHelper.SPINNER_COLUMN2};
SimpleCursorAdapter sca1,sca2;
String sp1_table_name = DBHelper.TABLE1_TABLE;
String sp2_table_name = DBHelper.TABLE2_TABLE;
Cursor csr1, csr2;
DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = this.findViewById(R.id.button1);
btn2 = this.findViewById(R.id.button2);
btn3 = this.findViewById(R.id.button3);
sp1 = this.findViewById(R.id.spinner1);
sp2 = this.findViewById(R.id.spinner2);
dbHelper = DBHelper.getInstance(this);
Cursor test4Data = dbHelper.getWritableDatabase().query(DBHelper.TABLE1_TABLE,null,null,null,null,null,null, "1");
if (test4Data.getCount() < 1) {
addSomeData();
}
test4Data.close();
sp1_table_name = DBHelper.TABLE1_TABLE;
sp2_table_name = DBHelper.TABLE2_TABLE;
setUpButtons();
setOrRefreshSpinner1();
setOrRefreshSpinner2();
}
void setUpButtons() {
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sp2_table_name = DBHelper.TABLE1_TABLE;
setOrRefreshSpinner2();
setOrRefreshSpinner1();
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sp2_table_name = DBHelper.TABLE2_TABLE;
setOrRefreshSpinner2();
setOrRefreshSpinner1();
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sp2_table_name = DBHelper.TABLE3_TABLE;
setOrRefreshSpinner2();
setOrRefreshSpinner1();
}
});
}
void setOrRefreshSpinner1() {
csr1 = dbHelper.getSpinnerData(sp1_table_name,-1);
if (sca1==null) {
sca1 = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
csr1,
spinnerColumns,
new int[]{android.R.id.text1, android.R.id.text2},0
);
sp1.setAdapter(sca1);
} else {
sca1.swapCursor(csr1);
}
}
void setOrRefreshSpinner2() {
csr2 = dbHelper.getSpinnerData(sp2_table_name,-1);
if (sca2==null) {
sca2 = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
csr2,
spinnerColumns,
new int[]{android.R.id.text1, android.R.id.text2},0
);
sp2.setAdapter(sca2);
} else {
sca2.swapCursor(csr2);
}
}
private void addSomeData() {
long n1 = dbHelper.insertTable1Row("NAME001","The first name.");
long n2 = dbHelper.insertTable1Row("NAME002","The second name.");
long n3 = dbHelper.insertTable1Row("NAME003","The third name");
long t2n1 = dbHelper.insertTable2Row("CHILDNAME001",n1);
long t2n2 = dbHelper.insertTable2Row("CHILDNAME002",n2);
long t2n3 = dbHelper.insertTable2Row("CHILDNAME003", n3);
dbHelper.insertTable3Row("GRANDCHILDNAME001",t2n1);
dbHelper.insertTable3Row("GRANDCHILDNAME002",t2n1);
dbHelper.insertTable3Row("GRANDCHILDNAME003",t2n1);
dbHelper.insertTable3Row("GRANDCHILDNAME004",t2n2);
dbHelper.insertTable3Row("GRANDCHILDNAME005",t2n3);
}
}
Result
The above when run starts of with :-
With the first spinner dropdown shown :-
With the second spinner dropdown shown :-
If Button1 is clicked then both spinners (i.e. spinner2 has been changed to select data from Table1 rather than Table2) show data from Table1 (useless but for demonstration) :-
If Button3 is clicked then data from Table3 is displayed in the second spinner:-
Clicking Button2 shows data from Table2.
Of course the principle could be applied in many different ways.
My adapters were not set so I made below changes and got expected result.
// RETRIEVE
retrievebtn.setOnClickListener(arg0 -> {
// TODO Auto-generated method stub
nos.clear();
names.clear();
//OPEN
db.openDB();
//RETRIEVE
Cursor c = db.getAllValues();
c.moveToFirst();
while(!c.isAfterLast())
{
String no = c.getString(0);
nos.add(no);
String name = c.getString(1);
names.add(name);
c.moveToNext();
}
//CLOSE
c.close();
db.close();
//SET IT TO SPINNER
ArrayAdapter<String> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, nos);
ArrayAdapter<String> adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, names);
sp1.setAdapter(adapter1);
sp2.setAdapter(adapter2);
});

android:Store data in Sqlite from List<HashMap>

In my project there is a list of category and every category has multiple item .I want to store these category with its multiple items.My question is can i store it in sqlite and i want retrieve it in recycle view.
[![In the screenshot every category is given with the selection number.i want to insert it with category with its multiple items and also want to show as given in screenshots][1]][1]
[1]: https://i.stack.imgur.com/9WaKm.png `public class ViewAllAdapter extends RecyclerView.Adapter {
private ArrayList<StringMenuListBean> dataList;
private Context mContext;
private TextView itemText;
private List<String> itemList;
public ViewAllAdapter(Context context, ArrayList<StringMenuListBean> dataList) {
this.dataList = dataList;
this.mContext = context;
}
#Override
public ItemRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rowitem_viewall, null);
v.setLayoutParams(new RecyclerView.LayoutParams(
RecyclerView.LayoutParams.MATCH_PARENT,
RecyclerView.LayoutParams.WRAP_CONTENT
));
ItemRowHolder mh = new ItemRowHolder(v, mContext);
return mh;
}
#Override
public void onBindViewHolder(ItemRowHolder itemRowHolder, int position) {
itemList = new ArrayList<>();
final StringMenuListBean model = dataList.get(position);
String str = model.getName();
String category = str.substring(0, str.indexOf("-"));
String item = str.substring(str.indexOf("-") + 1, str.length());
itemList.add(item);
itemRowHolder.linear.removeAllViews();
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayoutCompat.LayoutParams.WRAP_CONTENT);
llp.setMargins(50, 0, 0, 0); // llp.setMargins(left, top, right, bottom);
Log.e("category", category);
Log.e("remainder", item);
itemRowHolder.tv_category_item.setText(category + " :");
for (int k = 0; k < itemList.size(); k++) {
itemText = new TextView(mContext);
itemText.setText((position + 1) + " ." + item);
itemText.setTextColor(Color.parseColor("#43A047"));
itemText.setLayoutParams(llp);
itemRowHolder.linear.addView(itemText);
}
}
#Override
public int getItemCount() {
return (null != dataList ? dataList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder {
protected TextView tv_category_item;
protected LinearLayout linear;
public ItemRowHolder(View view, final Context mContextv) {
super(view);
tv_category_item = (TextView) view.findViewById(R.id.tv_category_item);
linear = (LinearLayout) view.findViewById(R.id.linear);
}
}
}
here is my Activitypublic class ViewAllActivity extends AppCompatActivity implements View.OnClickListener {
RecyclerView viewall_recycleview;
ViewAllAdapter viewallAdapter;
TextView tv_ID;
TextView tv_PACKID;
TextView tv_PACKAGENAME;
TextView tv_USERID;
TextView tv_USER_NAME;
TextView tv_CATID;
TextView tv_CATNAME;
TextView tv_MENUITEMS;
TextView tv_MEMBER;
TextView tv_DATE;
TextView tv_TIME;
TextView tv_TOTAL_PRICE;
TextView tv_ORDER_TYPE;
TextView tv_DISCOUNT;
TextView tv_CITY;
TextView tv_PROMOCODE;
TextView tv_PAYMENT_STATUS;
TextView tv_PRICE;
TextView tv_MENUID;
TextView tv_SUBPACKAGENAME;
TextView tv_CURRENT_DATE;
Button btn_download;
MenuDetailBean menuDetailBean;
Bundle activitybundle;
String subpackage_id, pack_id;
String menuitem;
ArrayList<StringMenuListBean> stringMenuList;
StringMenuListBean stringMenu;
List<String> menulist;
List<String> arraylist1;
File imagePath;
RecyclerView rcyView_mymenu;
Bitmap bitmap;
View view;
ByteArrayOutputStream bytearrayoutputstream;
File file;
FileOutputStream fileoutputstream;
boolean boolean_save;
LinearLayout ll_linear;
MenuAdapter menuAdapter;
public static Bitmap loadBitmapFromView(View v, int width, int height) {
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
return b;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewall);
init();
setTextAndList();
btn_download.setOnClickListener(this);
}
private void init() {
activitybundle = getIntent().getExtras();
pack_id = activitybundle.getString("pack_id");
subpackage_id = activitybundle.getString("sub_package_id");
// Log.e("subpackage_id",subpackage_id);
bytearrayoutputstream = new ByteArrayOutputStream();
rcyView_mymenu = (RecyclerView) findViewById(R.id.rcyView_mymenu);
rcyView_mymenu.setNestedScrollingEnabled(false);
tv_SUBPACKAGENAME = (TextView) findViewById(R.id.tv_SUBPACKAGENAME);
tv_PRICE = (TextView) findViewById(R.id.tv_PRICE);
tv_TOTAL_PRICE = (TextView) findViewById(R.id.tv_TOTAL_PRICE);
tv_DATE = (TextView) findViewById(R.id.tv_DATE);
tv_TIME = (TextView) findViewById(R.id.tv_TIME);
tv_MEMBER = (TextView) findViewById(R.id.tv_MEMBER);
tv_ORDER_TYPE = (TextView) findViewById(R.id.tv_ORDER_TYPE);
btn_download = (Button) findViewById(R.id.btn_download);
ll_linear = (LinearLayout) findViewById(R.id.ll_linear);
}
private void setTextAndList() {
menuDetailBean = DbUtils.getMenuDetail(getApplicationContext(), pack_id);
tv_SUBPACKAGENAME.setText(menuDetailBean.getSUBPACKAGE_NAME());
tv_PRICE.setText(menuDetailBean.getPRICE() + "/-");
tv_TOTAL_PRICE.setText(menuDetailBean.getTOTAL_PRICE() + "Rs.");
tv_DATE.setText(menuDetailBean.getDATE());
tv_TIME.setText(menuDetailBean.getTIME());
tv_MEMBER.setText(menuDetailBean.getMEMBER());
tv_ORDER_TYPE.setText(menuDetailBean.getORDER_TYPE());
menuitem = menuDetailBean.getMENUITEMS();
menulist = Arrays.asList(menuitem.split(","));
Log.e("meuitem", "" + menulist.size());
stringMenuList = new ArrayList<>();
for (int i = 0; i < menulist.size(); i++) {
StringMenuListBean stringMenu = new StringMenuListBean();
stringMenu.setName(menulist.get(i));
stringMenuList.add(stringMenu);
}
viewallAdapter = new ViewAllAdapter(getApplication(), stringMenuList);
rcyView_mymenu.setHasFixedSize(true);
rcyView_mymenu.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
rcyView_mymenu.setAdapter(viewallAdapter);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_download:
Bitmap bitmap1 = loadBitmapFromView(ll_linear, ll_linear.getWidth(), ll_linear.getHeight());
saveBitmap(bitmap1);
break;
}
}
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File("/sdcard/screenshotdemo.jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
Toast.makeText(getApplicationContext(), imagePath.getAbsolutePath() + "", Toast.LENGTH_SHORT).show();
boolean_save = true;
btn_download.setText("Check image");
Log.e("ImageSave", "Saveimage");
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
}
this is my Activity and below is my Database Utility code in which i saved all cart item . i want every added item is shown in different activity with its whole information.public class DbUtils {
public static void saveCart(Context context, CartItemBean data) {
ContentValues value = new ContentValues();
// for (CartItemBean data : data1) {
value.put(DbConstants.COLUMN_PACKID, data.getCOLUMN_PACKID());
value.put(DbConstants.COLUMN_PACKAGENAME, data.getCOLUMN_PACKAGENAME());
value.put(DbConstants.COLUMN_SUBPACKAGEID, data.getCOLUMN_SUBPACKAGE_ID());
value.put(DbConstants.COLUMN_SUBPACKAGENAME, data.getCOLUMN_SUBPACKAGE_NAME());
value.put(DbConstants.COLUMN_USERID, data.getCOLUMN_USERID());
value.put(DbConstants.COLUMN_USER_NAME, data.getCOLUMN_USER_NAME());
value.put(DbConstants.COLUMN_CATID, data.getCOLUMN_CATID());
value.put(DbConstants.COLUMN_CATNAME, data.getCOLUMN_CATNAME());
value.put(DbConstants.COLUMN_MENUITEMS, data.getCOLUMN_MENUITEMS());
value.put(DbConstants.COLUMN_MENUID, data.getCOLUMN_MENUID());
value.put(DbConstants.COLUMN_MEMBER, data.getCOLUMN_MEMBER());
value.put(DbConstants.COLUMN_DATE, data.getCOLUMN_DATE());
value.put(DbConstants.COLUMN_TIME, data.getCOLUMN_TIME());
value.put(DbConstants.COLUMN_TOTAL_PRICE, data.getCOLUMN_TOTAL_PRICE());
value.put(DbConstants.COLUMN_ORDER_TYPE, data.getCOLUMN_ORDER_TYPE());
value.put(DbConstants.COLUMN_DISCOUNT, data.getCOLUMN_DISCOUNT());
value.put(DbConstants.COLUMN_CITY, data.getCOLUMN_CITY());
value.put(DbConstants.COLUMN_CURRENTDATE, data.getCOLUMN_CURRENT_DATE());
value.put(DbConstants.COLUMN_PRICE, data.getCOLUMN_PRICE());
value.put(DbConstants.COLUMN_PROMOCODE, data.getCOLUMN_PROMOCODE());
value.put(DbConstants.COLUMN_PAYMENT_STATUS, data.getCOLUMN_PAYMENT_STATUS());
DbAccesser.getInstance(context).insertIntoTable(value,
DbConstants.TABLE_CART);
// }
}
// get product list
public static ArrayList<CartItemBean> getCartItems(Context context) {
ArrayList<CartItemBean> offlineDataList = new ArrayList<CartItemBean>();
Cursor cursor = DbAccesser.getInstance(context).query(DbConstants.TABLE_CART, null, null,
null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
CartItemBean data = new CartItemBean();
data.setCOLUMN_ID((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_ID))));
data.setCOLUMN_CATID((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_CATID))));
data.setCOLUMN_PAYMENT_STATUS((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_PAYMENT_STATUS))));
data.setCOLUMN_USER_NAME(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_USER_NAME)))));
data.setCOLUMN_USERID((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_USERID))));
data.setCOLUMN_PACKAGENAME((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_PACKAGENAME))));
data.setCOLUMN_CATNAME((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_CATNAME))));
data.setCOLUMN_CITY((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_CITY))));
data.setCOLUMN_CURRENT_DATE((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_CURRENTDATE))));
data.setCOLUMN_DATE((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_DATE))));
data.setCOLUMN_DISCOUNT(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_DISCOUNT)))));
data.setCOLUMN_MEMBER((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_MEMBER))));
data.setCOLUMN_MENUITEMS((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_MENUITEMS))));
data.setCOLUMN_ORDER_TYPE((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_ORDER_TYPE))));
data.setCOLUMN_PACKID((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_PACKID))));
data.setCOLUMN_PROMOCODE((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_PROMOCODE))));
data.setCOLUMN_TIME(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_TIME)))));
data.setCOLUMN_PRICE(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_PRICE)))));
data.setCOLUMN_MENUID(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_MENUID)))));
data.setCOLUMN_TOTAL_PRICE(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_TOTAL_PRICE)))));
data.setCOLUMN_SUBPACKAGE_ID(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_SUBPACKAGEID)))));
data.setCOLUMN_SUBPACKAGE_NAME(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_SUBPACKAGENAME)))));
offlineDataList.add(data);
cursor.moveToNext();
}
}
return offlineDataList;
}
public static MenuDetailBean getMenuDetail(Context context, String packId) {
DbHelper dbHelper = new DbHelper(context);
SQLiteDatabase database;
database = dbHelper.getReadableDatabase();
String selectQuery = "SELECT * FROM " + DbConstants.TABLE_CART + " WHERE "
+ DbConstants.COLUMN_PACKID + " = " + packId;
Cursor c = database.rawQuery(selectQuery, null);
if (c != null)
c.moveToFirst();
MenuDetailBean menuDetailBean = new MenuDetailBean();
menuDetailBean.setTIME(((c.getString(c.getColumnIndex(DbConstants.COLUMN_TIME)))));
menuDetailBean.setDATE(((c.getString(c.getColumnIndex(DbConstants.COLUMN_DATE)))));
menuDetailBean.setSUBPACKAGE_NAME(((c.getString(c.getColumnIndex(DbConstants.COLUMN_SUBPACKAGENAME)))));
menuDetailBean.setPRICE(((c.getString(c.getColumnIndex(DbConstants.COLUMN_PRICE)))));
menuDetailBean.setTOTAL_PRICE(((c.getString(c.getColumnIndex(DbConstants.COLUMN_TOTAL_PRICE)))));
menuDetailBean.setMEMBER(((c.getString(c.getColumnIndex(DbConstants.COLUMN_MEMBER)))));
menuDetailBean.setORDER_TYPE(((c.getString(c.getColumnIndex(DbConstants.COLUMN_ORDER_TYPE)))));
menuDetailBean.setMENUITEMS(((c.getString(c.getColumnIndex(DbConstants.COLUMN_MENUITEMS)))));
menuDetailBean.setCURRENT_DATE(((c.getString(c.getColumnIndex(DbConstants.COLUMN_CURRENTDATE)))));
return menuDetailBean;
}
public static int deteteTableData(Context context, String tableName) {
int status = 0;
status = DbAccesser.getInstance(context).deleteTable(tableName);
return status;
}
public static void deleteOrderAfterTEnDays(Context context) {
Cursor cursor = DbAccesser.getInstance(context).raw_query("delete from new_order where current_datetime < default current_timestamp - INTERVAL 10 DAY", null);
Log.e("CURSOR", "" + cursor);
}
// get bill by particular date and outletId
public static CartItemBean getOrderBillByOutlet(Context context, CartItemBean bean) {
CartItemBean cartItemBean = new CartItemBean();
String[] params = new String[]{bean.getCOLUMN_PACKID(), bean.getCOLUMN_MEMBER(), bean.getCOLUMN_DATE(), bean.getCOLUMN_TIME()};
Cursor cursor = DbAccesser.getInstance(context).raw_query("select column_id,name,SUM(order_billing) from cart where order_date=? AND outlets_id=?", params);
if (cursor != null) {
if (cursor.moveToFirst()) {
}
}
return cartItemBean;
}
public static void updateRetailerList(Context context, CartItemBean cartItemBean) {
ContentValues values = new ContentValues();
DbHelper dbHelper = new DbHelper(context);
SQLiteDatabase database;
database = dbHelper.getWritableDatabase();
values.put(DbConstants.COLUMN_MEMBER, cartItemBean.getCOLUMN_MEMBER());
values.put(DbConstants.COLUMN_DATE, cartItemBean.getCOLUMN_DATE());
values.put(DbConstants.COLUMN_TIME, cartItemBean.getCOLUMN_TIME());
values.put(DbConstants.COLUMN_TIME, cartItemBean.getCOLUMN_ORDER_TYPE());
values.put(DbConstants.COLUMN_TIME, cartItemBean.getCOLUMN_TOTAL_PRICE());
values.put(DbConstants.COLUMN_TIME, cartItemBean.getCOLUMN_ORDER_TYPE());
values.put(DbConstants.COLUMN_TIME, cartItemBean.getCOLUMN_TOTAL_PRICE());
values.put(DbConstants.COLUMN_SUBPACKAGEID, cartItemBean.getCOLUMN_SUBPACKAGE_ID());
values.put(DbConstants.COLUMN_SUBPACKAGENAME, cartItemBean.getCOLUMN_SUBPACKAGE_NAME());
values.put(DbConstants.COLUMN_CURRENTDATE, cartItemBean.getCOLUMN_CURRENT_DATE());
String sql2 = "UPDATE " + DbConstants.TABLE_CART + " SET " +
DbConstants.COLUMN_MEMBER + " = '" + cartItemBean.getCOLUMN_MEMBER() + "', "
+ DbConstants.COLUMN_DATE + " = '" + cartItemBean.getCOLUMN_DATE() + "', "
+ DbConstants.COLUMN_TIME + " = '" + cartItemBean.getCOLUMN_TIME() + "', "
+ DbConstants.COLUMN_SUBPACKAGEID + " = '" + cartItemBean.getCOLUMN_SUBPACKAGE_ID() + "', "
+ DbConstants.COLUMN_SUBPACKAGENAME + " = '" + cartItemBean.getCOLUMN_SUBPACKAGE_NAME() + "', "
+ DbConstants.COLUMN_CURRENTDATE + " = '" + cartItemBean.getCOLUMN_CURRENT_DATE() + "', "
+ DbConstants.COLUMN_TOTAL_PRICE + " = '" + cartItemBean.getCOLUMN_TOTAL_PRICE() + "' "
+ " WHERE " +
DbConstants.COLUMN_PACKID + " = '" + cartItemBean.getCOLUMN_PACKID() + "' AND "
+ DbConstants.COLUMN_USERID + " = '" + cartItemBean.getCOLUMN_USERID() + "'";
database.execSQL(sql2);
Log.e("UPDATE", sql2);
}
public static void deleteCartItem(Context context, String packId, String userId) {
DbHelper dbHelper = new DbHelper(context);
SQLiteDatabase database;
database = dbHelper.getWritableDatabase();
database.delete(DbConstants.TABLE_CART, DbConstants.COLUMN_PACKID + "=? AND "+ DbConstants.COLUMN_USERID + "=?", new String[]{packId, userId});
database.close();
}`
You can associate multiple items to each category, by creating a table with entries which each reflect an association.
For example, assuming you have a toy database like quoted at the end of this answer (see "MCVE foundation").
Create the table and add a few associations:
create table associations (id int, iid int);
insert into associations values (1, 1);
insert into associations values (1, 2);
insert into associations values (1, 3);
insert into associations values (2, 4);
insert into associations values (2, 5);
insert into associations values (3, 6);
insert into associations values (3, 7);
Then you can retrieve items for all categories:
select cat, name from cats inner join associations using(id) inner join items using (iid);
Output:
cat name
----------- ----------
soup tomato
soup sour
soup corn
namkeen katchori
namkeen aloo
stall tikija
stall patties
Or for more compact output:
select cat, group_concat(name, ', ')
from cats inner join
associations using(id) inner join
items using (iid)
group by cat
order by id;
Output:
cat group_concat(name, ', ')
----------- ------------------------
soup tomato, sour, corn
namkeen katchori, aloo
stall tikija, patties
I am not sure what you mean by "recycle view", maybe because I am working within pure SQLite (no other language, like you obviously use).
I hope one of the two representations suits you - or gets you on the way to achieve your goal.
MCVE foundation
(I did a .dump on my test environment, which I roughly cobbled together to demonstrate the idea. Please consider doing something like this for your next question involving SQLite. That makes it easier for the answerer and thereby faster for you. It also probably gets you a tighter fit of solution and often prevents misunderstandings.
Read Why should I provide an MCVE for what seems to me to be a very simple SQL query? if you like.):
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE table_1 (a int, b int, c int);
INSERT INTO table_1(a,b,c) VALUES(1,5,7);
INSERT INTO table_1(a,b,c) VALUES(2,10,14);
CREATE TABLE table_2 (a int, c int);
INSERT INTO table_2(a,c) VALUES(3,11);
INSERT INTO table_2(a,c) VALUES(6,22);
CREATE TABLE cats (id int, cat varchar(20));
INSERT INTO cats(id,cat) VALUES(1,'soup');
INSERT INTO cats(id,cat) VALUES(2,'namkeen');
INSERT INTO cats(id,cat) VALUES(3,'stall');
CREATE TABLE items (iid int, name varchar(20));
INSERT INTO items(iid,name) VALUES(1,'tomato');
INSERT INTO items(iid,name) VALUES(2,'sour');
INSERT INTO items(iid,name) VALUES(3,'corn');
INSERT INTO items(iid,name) VALUES(4,'katchori');
INSERT INTO items(iid,name) VALUES(5,'aloo');
INSERT INTO items(iid,name) VALUES(6,'tikija');
INSERT INTO items(iid,name) VALUES(7,'patties');
COMMIT;

How to send the Clicked Item Latitude to javascript from MainActivity.java

Here is my MainActivity.java
public class MainActivity extends AppCompatActivity{
CountriesDbAdapter myDB = new CountriesDbAdapter(this);
ListView listView;
public String lat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB.open();
myDB.deleteBank();
myDB.insertBank();
listView = (ListView) findViewById(R.id.listView);
toggleView();
WebView webView = (WebView) this.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebViewJavaScriptInterface(this), "android");
webView.requestFocusFromTouch();
webView.setWebViewClient(new WebViewClient());
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl("file:///android_asset/www/bank.html");
}
public void toggleView() {
final Cursor cursor = myDB.fetchBank();
final String[] arr = new String[cursor.getCount()];
int i = 0;
if (cursor.moveToFirst()) {
do {
String data = cursor.getString(cursor.getColumnIndex("banks"));
arr[i] = data;
i++;
} while (cursor.moveToNext());
}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, arr);
listView.setAdapter(adapter);
final StringBuffer buffer = new StringBuffer();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(MainActivity.this, arr[position], Toast.LENGTH_SHORT).show();
Cursor res = myDB.answerRequest(arr[position]);
if (res.moveToFirst()) {
do {
lat=res.getString(2);
//buffer.append("lat: " + lat + "\n");
// buffer.append("long: " + res.getString(3) + "\n\n");
// showMessage("Data", buffer.toString());
//showMessage();
} while (res.moveToNext());
}
}
});
}
class WebViewJavaScriptInterface {
private Activity activity;
public WebViewJavaScriptInterface(Activity activity) {
this.activity = activity;
}
#JavascriptInterface
public String getData() {
//From Here how can i Return my Updated latitude to javascript file
}
}
CountriesDbAdapter.java
package com.example.student.finalone;
public class CountriesDbAdapter {
public static final String COLUMN_BANK = "banks";
public static final String COLUMN_BANKL = "banksl";
public static final String COLUMN_BANKLG = "bankslg";
private static final String TAG = "CountriesDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
public static final String KEY_ROWID = "id";
private static final String DATABASE_NAME = "Vijayawada";
private static final String BANK_TABLE = "Bank";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_BANK = "CREATE TABLE if not exists " + BANK_TABLE + " (" + KEY_ROWID + " integer PRIMARY KEY autoincrement," + COLUMN_BANK + "," + COLUMN_BANKL + "," + COLUMN_BANKLG + ");";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_BANK);
db.execSQL(DATABASE_BANK);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + BANK_TABLE);
}
}
public CountriesDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public CountriesDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public long createBank(String b, double blat,double blong) {
ContentValues initialValues = new ContentValues();initialValues.put(COLUMN_BANK, b);initialValues.put(COLUMN_BANKL, blat);initialValues.put(COLUMN_BANKLG, blong);
return mDb.insert(BANK_TABLE, null, initialValues);
}
public boolean deleteBank() {
int doneDelete = 0;
doneDelete = mDb.delete(BANK_TABLE, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
public void insertBank()
{
createBank("ServicebranchSBI",16.5109,80.651);createBank("StateBankofIndia",16.5011,80.6559);createBank("StateBankOfHyderabad",16.4966,80.6569);
createBank("BankOfBaroda",16.4974,80.6546);createBank("AndhraBank",16.5028,80.6396);createBank("AndhraBank",16.5062,80.648);
}
public Cursor fetchBank() {
String SelectQuery="select * from "+BANK_TABLE;
Cursor mCursor = mDb.rawQuery(SelectQuery,null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor answerRequest(String position) {
String SelectQuery= "SELECT * FROM " + BANK_TABLE + " WHERE " + COLUMN_BANK + "='" + position + "'";
Cursor mCursor = mDb.rawQuery(SelectQuery,null);
// String result="";
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
index.html
<html>
<head>
<script>
var showData = function() {
var data = android.getData();
window.alert("Hello! Data are: " + data + "; first = " + data);
}
</script>
</head>
<body>
<p>Lorem ipsem dolor et ceteris.</p>
<input type="button" value="Display data" onclick="showData()">
</body>
</html>
Iam trying to access the database from MainActivity.java and push it to the html file, Whenever i click on the html button it shows 0's in some cases iam getting error near the double lat declaration
You can achieve it in two ways:
1. Implement the Activity from OnItemClickListener and override onItemClick parallel to onCreate. Define double array a class variable and update that inside onItemClick
public class MainActivity extends Activity implements OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Your code here
}
}
2.Create a class MyItemClickListener and implement it from OnItemClickListener. Define double array a class variable
class MyItemClickListener implements OnItemClickListener
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Your code here
//Update the class member a1dToJson(lat).toString();//Here it returns all 0's
}
}
Change setOnItemClickListener to:
listView.setOnItemClickListener(new MyItemClickListener());

Get height of listview cells to ease scrolling upwards

An activity with a listview has a problem that is, the listview will have different amount of content in each cell. When the user scrolls down, the listview is smooth and things work as expected. But, when the user scrolls up, the cached data of the listview is reloaded. This redraw is making the listview scrolling up jumpy. What I figured out is that, if I calculate the height of each cell while scrolling down and save it in an ArrayList and apply the same height when the user scrolls up against the visible listitem then the jumpy scroll can be fixed. I have tested the same by setting a static height for every post, the scrollbar was not jumpy. But, I have to make it dynamic according to each cell height. The listview code might look to be a little complex!
The activity:
public class PostListActivity extends Activity implements OnScrollListener {
TableLayout html_output_table;
int id = 0;
List<String> dataFromParse = new ArrayList<String>();
LazyObjectDrawingAdapter adapter;
ListView listView;
List<RichPost> richPostArrayList = new ArrayList<RichPost>();
private int currentScrollState;
private int currentVisibleItemCount;
private int skipParam = 0;
private boolean flag_loading = false;
int mLastFirstVisibleItem = 0;
HashMap<integer, String> hashMap = new HashMap<integer, String>();
int initialHeight = 0;
ArrayList<Integer> heightList = new ArrayList<Integer>();
int position;
boolean scrolling = false;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_list_list);
listView = (ListView) findViewById(R.id.listView);
// Need to create the adapter constructor
listView.setOnScrollListener(this);
adapter = new LazyObjectDrawingAdapter(PostListActivity.this, dataFromParse, richPostArrayList);
listView.setAdapter(adapter);
setContent();
// cityListBody("Hello");
}
public void setContent(){
// Pull data from Parse
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("userid", ParseUser.getCurrentUser().getObjectId());
params.put("skip", skipParam);
ParseCloud.callFunctionInBackground("studentsPosts", params, new FunctionCallback<List<List<ParseObject>>>() {
#Override
public void done(List<List<ParseObject>> data, com.parse.ParseException arg1){
if (data == null) {
} else {
Log.e("size ", "RUNNING Size : " + data.size());
if (data.size() > 0) {
flag_loading = false;
for (int i = 0; i < data.size(); i++) {
RichPost rc = new RichPost();
//if (heightList.size()>i){
Log.e("heightList.size()", ""+heightList.size());
//}
if (data.get(0).get(0).get("htmlContent") != null) {
// Switch i to 1 to force just 1 additon.
dataFromParse.add(data.get(i).get(0).getString("htmlContent"));
rc.setHtmlCode(data.get(i).get(0).getString("htmlContent"));
Log.i("Calling notifiyDataSetchanged", "now");
}
if (data.get(i).get(0).get("photos") != null) {
List<ParseFile> pFileList;
pFileList = (List<ParseFile>) data.get(i).get(0).get("photos");
rc.setPhotosArray(pFileList);
}
if (data.get(i).get(0).getParseFile("photo") != null) {
// Time to retrieve the photo
ParseFile getParseFile;
getParseFile = (ParseFile) data.get(i).get(0).get("photo");
rc.setPhoto(getParseFile);
}
richPostArrayList.add(rc);
adapter.notifyDataSetChanged();
}
}
}
}
});
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState){
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
private void isScrollCompleted(){
if (this.currentVisibleItemCount >= 5 && this.currentScrollState == SCROLL_STATE_IDLE) {
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount){
this.currentVisibleItemCount = visibleItemCount;
if (firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount != 0) {
if (flag_loading == false) {
flag_loading = true;
Log.d("IN ON SCROLL", "NOW: " + skipParam);
skipParam = skipParam + 10;
setContent();
}
}
// to determine scroll up or down
if (mLastFirstVisibleItem < firstVisibleItem) {
Log.i("SCROLLING DOWN", "TRUE");
// View c = listView.getChildAt(0);
// int scrolly = -c.getTop() + listView.getFirstVisiblePosition() * c.getHeight();
// Log.e("scrolly", "" + scrolly);
int scrolly = getItemHeightofListView(listView, firstVisibleItem);
Log.e("scrolly down", "" + scrolly);
//setting the cell height from total height - initial height
heightList.add(scrolly-initialHeight);
ArrayListGetterSetter test = new ArrayListGetterSetter();
test.setList(scrolly-initialHeight);
initialHeight = scrolly;
//hashMap.put(firstVisibleItem, "" + scrolly);
//Log.e("Item show",""+heightList.get(firstVisibleItem));
scrolling = true;
}
if (mLastFirstVisibleItem > firstVisibleItem) {
Log.i("SCROLLING UP", "TRUE");
// View c = listView.getChildAt(0);
// int scrolly = -c.getTop() + listView.getFirstVisiblePosition() * c.getHeight();
// Log.e("scrolly", "" + scrolly);
// int scrolly = getItemHeightofListView(listView, firstVisibleItem);
// Log.e("scrolly up", "" + scrolly);
if (firstVisibleItem <= heightList.size()) {
//getting the heights from the arraylist while scrolling up
//Log.e("Item show",""+heightList.get(firstVisibleItem));
position = firstVisibleItem;
}
}
mLastFirstVisibleItem = firstVisibleItem;
}
public static int getItemHeightofListView(ListView listView, int items) {
ListAdapter mAdapter = listView.getAdapter();
int listviewElementsheight = 0;
// for listview total item height
// items = mAdapter.getCount();
for (int i = 0; i < items; i++) {
View childView = mAdapter.getView(i, null, listView);
childView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
listviewElementsheight+= childView.getMeasuredHeight();
}
return listviewElementsheight;
}
}
The adapter:
public class LazyObjectDrawingAdapter extends BaseAdapter {
PostListActivity postList = new PostListActivity();
RichPost rc = new RichPost();
Context mContext;
List<String> randomItems = new ArrayList<String>();
List<RichPost> richPostArrayList = new ArrayList<RichPost>();
private LayoutInflater inflater = null;
ArrayList<Integer> heightList = new ArrayList<Integer>();
public LazyObjectDrawingAdapter(Context context, List<String> contentComingIn, List<RichPost> richPostArrayList) {
this.mContext = context;
this.inflater = LayoutInflater.from(mContext);
this.randomItems = contentComingIn;
this.richPostArrayList = richPostArrayList;
}
// public LazyObjectDrawingAdapter(Context context, List<String> contentComingIn, List<RichPost> richPostArrayList, ArrayList<Integer> heightList) {
// this.mContext = context;
// this.inflater = LayoutInflater.from(mContext);
// this.randomItems = contentComingIn;
// this.richPostArrayList = richPostArrayList;
// this.heightList = heightList;
//
// }
#Override
public int getCount() {
//return 1;
//Log.i("GetCount size : ", " " + randomItems.size());
//return 1;
return randomItems.size();
}
#Override
public Object getItem(int position) {
return randomItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.lazy_adapter, null);
holder = new ViewHolder();
setIds(vi, holder);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
ArrayListGetterSetter test = new ArrayListGetterSetter();
Log.e("test.getSize()", ""+test.getSize());
//test.getListValues(position);
tryingNewClass(holder, vi, mContext, (String) randomItems.get(position), richPostArrayList.get(position));
return vi;
}
private void step1(String fromActivity) {
Log.d("Html output", "" + fromActivity);
}
private void step2(String html){
Document doc = Jsoup.parse(html);
Element element = doc.body();
Elements elements = element.select("img");
Log.w("Size of the elements ", " " + elements.size());
for(Element e : elements){
Log.d("step 2: ", "img: " + e.toString());
}
}
private void step2PicksUpWorks(String html){
Document doc = Jsoup.parse(html);
Elements imgs = doc.body().select("p");
for (Element e : imgs){
if(!e.toString().contentEquals("")){
Log.i("Img sources ", ": " + e.ownText());
}
}
}
private void tryingNewClass(ViewHolder holder, View view, Context context, String source, RichPost richPost){
//setting static height for testing, feel free to remove it anytime
int heightValue = 500;
holder.textToDraw.setMinHeight(heightValue + 200);
TestDrawableClass tdc = new TestDrawableClass(source, holder.textToDraw, context, holder.imageToDraw, richPost);
}
private void URLCombinedTest(int position, ViewHolder holder, View view, Context context, String source){
ImageView iv = new ImageView(context);
TextView tv = new TextView(context);
URLCombined uip = new URLCombined(position, iv, context, tv);
Spanned spanned = Html.fromHtml(source, uip, null);
tv.setText(spanned);
//holder.linearLayoutForImages.addView(iv);
holder.linearLayoutForImages.addView(tv);
}
/*
* Time to do the on draw
*/
private void lineByLine(int position, ViewHolder holder, View view, Context context, String source){
//Need to get line by line and then run it via the test parsers and add it to the layout dynmically via the ViewGrou parpent
Document doc = Jsoup.parse(source);
Element element = doc.body();
Elements ele = element.select("img");
for (int i = 0; i < ele.size(); i++) {
/* Log.w("For loop ", " " + i + " "+ ele.get(i).html());
Log.d("For loop ", " " + i + " "+ ele.get(i).text());
Log.i("For loop ", " " + i + " "+ ele.get(i));*/
addURLImageParser(position, holder, view, context, ""+ele.get(i));
}
Elements all = doc.select("b");
for (int i = 0; i < all.size(); i++) {
Log.i("For loop ", " " + i + " "+ all.get(i));
addURLTextParser(position, holder, view, context, ""+all.get(i));
}
Log.w("About to start a loop to check everything ", "now");
int imgValue = 0;
for (Element el:doc.select("body").select("*")) {
imgValue++;
// loop over all textnodes of these children
Log.i("Element siblings ", " " + el.nextElementSibling() + " " +imgValue);
Element tempElement = el.nextElementSibling();
if(el.nextElementSibling() == null){
Log.w("Element is null", "value is : " + el + " " + imgValue);
}
if(el.nextElementSibling() != null){
//Loop through the siblings.
if(el.nextElementSibling().hasText()){
//Log.d("Can we check any text after the fact ? ", " " + el);
//Log.e("Element has text: ", " " + el.nextElementSibling());
}
if(el.nextElementSibling().hasText() == false){
Elements elements = tempElement.select("img");
if(elements.isEmpty() == false){
//Log.e("Element text is false ", " " + elements);
}
}
}
imgValue = 0;
}
}
private void addURLTextParser(int position, ViewHolder holder, View view, Context context, String source){
Log.w("in add text url", "now");
TextView tv = new TextView(context);
URLTextParser utp = new URLTextParser(tv, context, 0);
Spanned spanned = Html.fromHtml(source, utp, null);
tv.setText(spanned);
holder.linearLayoutForImages.addView(tv);
//Now attach it the layout
}
private void addURLImageParser(int position, ViewHolder holder, View view, Context context, String source){
//Log.w("in add image url", "now");
ImageView iv = new ImageView(context);
URLImageParser uip = new URLImageParser(position, iv, context);
Spanned spanned = Html.fromHtml(source, uip, null);
holder.linearLayoutForImages.setId(position);
holder.linearLayoutForImages.addView(iv);
}
private void testURLTextParser(int position, ViewHolder holder, View view, Context context, String source){
//Lets just get text only
Document doc = Jsoup.parse(source);
Elements img = doc.body().select("p");
for (int i = 0; i < img.size(); i++) {
//Log.w("Checking null ", " " + img.get(i).text().contentEquals(""));
if( img.get(i).text().contentEquals("") == false){
Log.i("output : ", " " + img.get(i).text());
Log.d("Output2 ", " " + img.get(i).html());
URLTextParser utp = new URLTextParser(holder.textToDraw, context, 0);
Spanned spanned = Html.fromHtml(img.get(i).html(), utp, null);
holder.textToDraw.setText(spanned);
}
}
}
private void testURLImageParser(int position, ViewHolder holder, View view, Context context, String source){
//Log.d("In step 3 ", " Position : " + position);
//Lets do some crazy work right now. So lets start with just images. Make them 3 seperate ImageViews to draw
//Pos 0 has three images, but lets cycle throgh the mfirst
Document doc = Jsoup.parse(source);
Elements img = doc.body().select("img");
//Now we have all possible image 'source links'
for (int i = 0; i < img.size(); i++) {
//Lets loop through them one by one
Log.w("checking the output of the img ", "" + img.get(i).toString());
ImageView iv = new ImageView(context); //Create a holder for the images
URLImageParser uip = new URLImageParser(position, iv, context);
Spanned spanned = Html.fromHtml(img.get(i).toString(), uip, null);
holder.linearLayoutForImages.addView(iv);
}
}
private void setIds(View vi, ViewHolder holder) {
holder.textToDraw = (TextView) vi.findViewById(R.id.textOnly);
holder.imageToDraw = (ImageView) vi.findViewById(R.id.imageOnly);
holder.linearLayoutForImages = (LinearLayout) vi.findViewById(R.id.linearForImages);
}
static class ViewHolder {
TextView textToDraw;
ImageView imageToDraw;
Object objectCouldBeAnything;
Canvas toTry;
LinearLayout linearLayoutForImages;
}
}
Class ArrayListGetterSetter:
public class ArrayListGetterSetter {
ArrayList<Integer> heightList = new ArrayList<Integer>();
int valueFromList;
int size;
public int getListValues(int itemIndex) {
valueFromList = heightList.get(itemIndex);
return valueFromList;
}
public void setList(int value) {
heightList.add(value);
}
public int getSize(){
size = heightList.size();
return size;
}
}
Class TestDrawableClass:
Click to see the code
The
ArrayListGetterSetter test = new ArrayListGetterSetter();
Log.e("test.getSize()", ""+test.getSize());
in the LazyObjectDrawingAdapter is always returning 0. Thus querying the elements are causing null pointer exception. How can I get the height values?
in getItemId you should have returned position instead of zero.
#Override
public long getItemId(int position) {
return 0;
}
it should be :
#Override
public long getItemId(int position) {
return position;
}
i think this might help.

Android sqllite cannot remove item by position

I am working with sqllite. I have successfully create a database and I can input some values in my database. I can also show all values in listview.
Now I want to delete values by position (for example, if i click listview's 4th item i would to delete full this items)
This is my code:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "lvstone_2";
private static final String TABLE_CONTACTS = "CardTable1";
private static final String KEY_ID = "id";
private static final String KEY_Tittle = "name";
private static final String KEY_Description = "description";
private static final String KEY_Price = "price";
private static final String KEY_Counter = "counter";
private static final String KEY_Image = "image";
private final ArrayList<Contact> contact_list = new ArrayList<Contact>();
public static SQLiteDatabase db;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_Tittle + " TEXT,"
+ KEY_Description + " TEXT,"
+ KEY_Price + " TEXT,"
+ KEY_Counter + " TEXT,"
+ KEY_Image + " TEXT"
+ ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void Add_Contact(Contact contact) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
if (!somethingExists(contact.getTitle())) {
values.put(KEY_Tittle, contact.getTitle()); // Contact title
values.put(KEY_Description, contact.getDescription()); // Contact//
// description
values.put(KEY_Price, contact.getPrice()); // Contact price
values.put(KEY_Counter, contact.getCounter()); // Contact image
values.put(KEY_Image, contact.getImage()); // Contact image
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
Log.e("Table Result isss", String.valueOf(values));
db.close(); // Closing database connection
}
}
public void deleteUser(String userName)
{
db = this.getWritableDatabase();
try
{
db.delete(DATABASE_NAME, "username = ?", new String[] { userName });
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}
// Getting single contact
Contact Get_Contact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS,
new String[] { KEY_ID, KEY_Tittle, KEY_Description, KEY_Price,
KEY_Counter, KEY_Image }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(cursor.getString(0), cursor.getString(1),
cursor.getString(2), cursor.getString(4), cursor.getString(5));
// return contact
cursor.close();
db.close();
return contact;
}
public boolean somethingExists(String x) {
Cursor cursor = db.rawQuery("select * from " + TABLE_CONTACTS
+ " where name like '%" + x + "%'", null);
boolean exists = (cursor.getCount() > 0);
Log.e("Databaseeeeeeeee", String.valueOf(cursor));
cursor.close();
return exists;
}
public ArrayList<Contact> Get_Contacts() {
try {
contact_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setTitle(cursor.getString(1));
contact.setDescription(cursor.getString(2));
contact.setPrice(cursor.getString(3));
contact.setCounter(cursor.getString(4));
contact.setImage(cursor.getString(5));
contact_list.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return contact_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return contact_list;
}
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
}
My Adapter Code:
public class StradaSQLAdapter extends BaseAdapter {
Activity activity;
int layoutResourceId;
Contact user;
ArrayList<Contact> data = new ArrayList<Contact>();
public ImageLoader imageLoader;
UserHolder holder = null;
public int itemSelected = 0;
public StradaSQLAdapter(Activity act, int layoutResourceId,
ArrayList<Contact> data) {
this.layoutResourceId = layoutResourceId;
this.activity = act;
this.data = data;
imageLoader = new ImageLoader(act.getApplicationContext());
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(activity);
holder = new UserHolder();
row = inflater.inflate(layoutResourceId, parent, false);
holder.Title = (TextView) row.findViewById(R.id.smalltitle1);
holder.counter = (TextView) row.findViewById(R.id.smallCounter1);
holder.dbcounter = (TextView) row
.findViewById(R.id.DBSliderCounter);
holder.Description = (TextView) row.findViewById(R.id.smallDesc1);
holder.layout = (RelativeLayout) row
.findViewById(R.id.DBSlideLayout);
holder.layoutmain = (RelativeLayout) row
.findViewById(R.id.DBSlideLayoutMain);
holder.Price = (TextView) row.findViewById(R.id.smallPrice1);
holder.pt = (ImageView) row.findViewById(R.id.smallthumb1);
holder.close = (ImageView) row.findViewById(R.id.DBSliderClose);
holder.c_minus = (ImageView) row.findViewById(R.id.counter_minus);
holder.c_plus = (ImageView) row.findViewById(R.id.counter_plus);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
user = data.get(position);
holder.Title.setText(user.getTitle());
holder.Description.setText(user.getDescription());
holder.Price.setText(user.getPrice() + " GEL");
holder.counter.setText(user.getCounter());
holder.dbcounter.setText(user.getCounter());
Log.e("image Url is........", data.get(position).toString());
imageLoader.DisplayImage(user.getImage(), holder.pt);
return row;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public class UserHolder {
public TextView Price, counter, Description, Title, dbcounter;
public ImageView pt,close,c_plus,c_minus;
public RelativeLayout layout, layoutmain;
}
}
and my Main Java code:
public class StradaChartFragments extends Fragment {
public static ListView list;
ArrayList<Contact> contact_data = new ArrayList<Contact>();
StradaSQLAdapter cAdapter;
private DatabaseHandler dbHelper;
UserHolder holder;
private RelativeLayout.LayoutParams layoutParams;
int a;
private ArrayList<Contact> contact_array_from_db;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.strada_chart_fragment,
container, false);
dbHelper = new DatabaseHandler(getActivity());
list = (ListView) rootView.findViewById(R.id.chart_listview);
cAdapter = new StradaSQLAdapter(getActivity(),
R.layout.listview_row_db, contact_data);
contact_array_from_db = dbHelper.Get_Contacts();
Set_Referash_Data();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
holder = (UserHolder) view.getTag();
a = Integer.parseInt(holder.counter.getText().toString());
layoutParams = (RelativeLayout.LayoutParams) holder.layoutmain
.getLayoutParams();
if (holder.layout.getVisibility() != View.VISIBLE) {
ValueAnimator varl = ValueAnimator.ofInt(0, -170);
varl.setDuration(1000);
varl.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
layoutParams.setMargins(
(Integer) animation.getAnimatedValue(), 0,
0, 0);
holder.layoutmain.setLayoutParams(layoutParams);
}
});
varl.start();
holder.layout.setVisibility(View.VISIBLE);
}
holder.close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ValueAnimator var2 = ValueAnimator.ofInt(-170, 0);
var2.setDuration(1000);
var2.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(
ValueAnimator animation) {
dbHelper.deleteUser(contact_array_from_db.get(position).getTitle());
dbHelper.close();
cAdapter.notifyDataSetChanged();
layoutParams.setMargins(0, 0,
(Integer) animation.getAnimatedValue(),
0);
holder.layoutmain.setLayoutParams(layoutParams);
holder.layout.setVisibility(View.INVISIBLE);
}
});
var2.start();
}
});
}
});
return rootView;
}
public void Set_Referash_Data() {
contact_data.clear();
for (int i = 0; i < contact_array_from_db.size(); i++) {
String title = contact_array_from_db.get(i).getTitle();
String Description = contact_array_from_db.get(i).getDescription();
String Price = contact_array_from_db.get(i).getPrice();
String Counter = contact_array_from_db.get(i).getCounter();
String image = contact_array_from_db.get(i).getImage();
Contact cnt = new Contact();
cnt.setTitle(title);
cnt.setDescription(Description);
cnt.setPrice(Price);
cnt.setCounter(Counter);
cnt.setImage(image);
contact_data.add(cnt);
}
dbHelper.close();
cAdapter.notifyDataSetChanged();
list.setAdapter(cAdapter);
Log.e("Adapter issss ...", String.valueOf(cAdapter));
}
I found one example about how to delete title but it's not working.
How could I delete user by position in listview 'onclick' listener?
Any help would be great, thanks
db.delete(DATABASE_NAME, "username = ?", new String[] { userName });
You'll need to use the table name here, if all else is correct.

Categories