I added ImageButton in CardView in RecyclerView and i made it to add item in favourite (i made sqlite to save favourite ) now i want to make when i open activity that RecyclerView on it show ImageButton with different image if it in Favourite and when pressed on it change image
simply i want to make favourite button (Star image ) like gmail app
RecyclerView Adapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<listitem_gib> getDataAdapter;
public RecyclerViewAdapter(List<listitem_gib> getDataAdapter, Context context){
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(v,context,getDataAdapter);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
listitem_gib getDataAdapter1 = getDataAdapter.get(position);
holder.name.setText(getDataAdapter1.getName());
holder.num.setText(getDataAdapter1.getnum());
Picasso.with(context).load("http://grassyhat.com/android/image/" + getDataAdapter1.getimg()).into(holder.img1);
holder.fav.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
fav(position);
}
});
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener{
public TextView name;
public TextView num;
public ImageView img1;
ImageButton fav;
Context context;
List<listitem_gib> getDataAdapter;
public ViewHolder(View itemView, Context context ,List<listitem_gib> getDataAdapter ) {
super(itemView);
itemView.setOnClickListener(this);
this.getDataAdapter = getDataAdapter;
this.context = context;
this.fav= (ImageButton) itemView.findViewById(R.id.btn_fav);
name = (TextView) itemView.findViewById(R.id.Main_Text) ;
num = (TextView) itemView.findViewById(R.id.Second_Text) ;
img1 = (ImageView) itemView.findViewById(R.id.img1) ;
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
listitem_gib getDataAdapter =this.getDataAdapter.get(position);
Intent intent = new Intent(this.context,Rewaya_info.class);
intent.putExtra("name",getDataAdapter.getName());
intent.putExtra("url",getDataAdapter.geturl());
intent.putExtra("img",getDataAdapter.getimg());
intent.putExtra("num",getDataAdapter.getnum());
intent.putExtra("size",getDataAdapter.getsize());
this.context.startActivity(intent);
}
}
public void fav(final int position) {
final DB_Sqlit db_sqlit = new DB_Sqlit(context);
final String name = getDataAdapter.get(position).name;
final String img = getDataAdapter.get(position).img;
final String url = getDataAdapter.get(position).url;
final String num = getDataAdapter.get(position).num;
final String size = getDataAdapter.get(position).size;
int count = db_sqlit.get_check_List_Favorite(name);
if (count > 0) {
Toast.makeText(context, "already exist", Toast.LENGTH_SHORT).show();
}else{
Boolean add = db_sqlit.Insert_to_favorite(name, img, url, num, size);
if (add) {
Toast.makeText(context, "added to favourite", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
}
}
}
Database
public class DB_Sqlit extends SQLiteOpenHelper {
public static final String BDname = "mdata.db";
public DB_Sqlit(Context context) {
super(context, BDname, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table favorite ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, img TEXT, url TEXT, num TEXT, size TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS favorite");
onCreate(db);
}
public Boolean Insert_to_favorite(String name, String img, String url, String num, String size) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("img", img);
contentValues.put("url", url);
contentValues.put("num", num);
contentValues.put("size", size);
long result = db.insert("favorite", null, contentValues);
if (result == -1)
return false;
else
return true;
}
public List getAllList_Favorite() {
List<listitem_gib> list = new ArrayList<listitem_gib>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor rs = db.rawQuery("select * from favorite", null);
if (rs.moveToFirst()){
do {
listitem_gib model = new listitem_gib();
model.setId(rs.getString(0));
model.setName(rs.getString(1));
model.seturl(rs.getString(3));
model.setimg(rs.getString(2));
model.setnum(rs.getString(4));
model.setsize(rs.getString(5));
list.add(model);
}while (rs.moveToNext());
}
Log.d("rewayat data", list.toString());
return list;
}
public int get_check_List_Favorite(String Title) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor rs = db.rawQuery("select * from favorite Where name like '"+ Title +"'", null);
rs.moveToFirst();
int count = rs.getCount();
return count;
}
public Integer DeleteFav(String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("favorite", "id = ?", new String[]{id});
}
CardLayout
<android.support.v7.widget.CardView
android:layout_width="130dp"
android:layout_height="225dp"
app:cardElevation="15dp"
app:cardBackgroundColor="#eae7cb7c"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
app:cardCornerRadius="8dp"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/img1"
android:layout_width="130dp"
android:layout_height="130dp"
android:layout_gravity="center"
android:scaleType="centerCrop"/>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/delete"
android:layout_gravity="end">
<ImageButton
android:id="#+id/btn_fav"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#android:drawable/btn_star"
android:background="#00ffffff"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"/>
</FrameLayout>
</FrameLayout>
<TextView
android:id="#+id/Main_Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label"
android:layout_gravity="right"
android:textSize="15sp"
android:padding="5dp"
android:layout_marginTop="5dp"
android:textColor="#6a9399"/>
<TextView
android:id="#+id/Second_Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LongerLabel"
android:layout_gravity="right"
android:textSize="12sp"
android:padding="5dp"
android:textStyle="bold"
android:textColor="#998c6a"/>
</LinearLayout>
</android.support.v7.widget.CardView>
In your onBindViewHolder,, you can just switch the image as needed.
holder.fav.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(holder.fav.getTag() == R.drawable.fav_icon) {
unfav(position);
holder.fav.setImageResource(R.drawable.unfav_icon);
holder.fav.setTag(R.drawable.unfav_icon);
}
else {
fav(position);
holder.fav.setImageResource(R.drawable.fav_icon);
holder.fav.setTag(R.drawable.fav_icon);
}
}
});
In your onBindViewHolder() method, you can add the initial state :
if(holder.fav.getTag() == R.drawable.fav_icon)
holder.fav.setImageResource(R.drawable.fav_icon);
else
holder.fav.setImageResource(R.drawable.unfav_icon);
Related
I am trying to build a listview which contains outlet address in 5 lines,along with a status indicator image and a button. The following is the functionality I am trying to build.
When the list text is clicked - I want to open a activity.
When the button (COMP) is clicked - I want to open a different activity.
The image (tickmark) is a status indicator to inform the user whether the activity in a outlet is complete or not.
The list is populated from a SqliteDatabase. On clicking the button, I want to take the reference of the outlet and show different attributes of the outlet.
How do I integrate the button into the list view.
I have written the following code so far:
LISTVIEW.XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="3dp"
android:background="#FFFFFF"
android:layout_marginLeft="2dp"
android:layout_marginBottom="2dp"
android:descendantFocusability="blocksDescendants"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/imageViewFlag"
android:layout_rowSpan="2"
android:layout_width="25dp"
android:layout_height="25dp"
android:scaleType="fitXY"
android:layout_marginTop="20dp"
android:foregroundGravity="center"
android:layout_gravity="center"
android:background="#drawable/compliance_foreground"
android:layout_row="0"
android:layout_column="0" />
<Button
android:id="#+id/complianceButton"
android:layout_width="70dp"
android:layout_height="35dp"
android:text="COMP"
android:textSize="12sp"
></Button>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="5dp"
>
<TextView
android:id="#+id/tvOutletNamealt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Outlet :"
android:textSize="15sp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#04031A"
android:textAllCaps="true"
android:layout_columnWeight="1"
android:layout_row="0"
android:layout_column="1" />
<TextView
android:id="#+id/tvOutletAddress1alt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address1 :"
android:textSize="12sp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:layout_columnWeight="1"
android:layout_row="1"
android:layout_column="1" />
<TextView
android:id="#+id/tvOutletAddress2alt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address2 :"
android:textSize="12sp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:layout_columnWeight="1"
android:layout_row="2"
android:layout_column="1" />
<TextView
android:id="#+id/tvOutletCityalt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="City :"
android:textSize="12sp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:layout_columnWeight="1"
android:layout_row="3"
android:layout_column="1" />
<TextView
android:id="#+id/tvOutletPhonealt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PhoneNumber :"
android:textSize="13sp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:layout_columnWeight="1"
android:layout_row="4"
android:layout_column="1" />
</LinearLayout>
</LinearLayout>
MainActivity.java
public class show_outlets_alt extends AppCompatActivity {
SQLiteHelper sqLiteHelper;
SQLiteDatabase sqLiteDatabase;
Cursor cursor;
AltOutletAdapter listAdapterOutlets ;
String lati;
String longi;
String projectName;
String usrname;
Button cButton;
ListView LISTVIEWOUTLETS;
ArrayList<String> Id_Array;
ArrayList<String> OutletName_Array;
ArrayList<String> OutletAddress1_Array;
ArrayList<String> OutletAddress2_Array;
ArrayList<String> City_Array;
ArrayList<String> Phone_Array;
ArrayList<String> ListViewClickItemArrayOutlets = new ArrayList<String>();
private String projectID;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_show_outlets_alt );
// Set toolbar for this screen
Toolbar sectoolbar = (Toolbar) findViewById( R.id.secondary_toolbar );
sectoolbar.setTitle("");
sectoolbar.setBackground(new ColorDrawable(getResources().getColor(R.color.primary_welcome_color)));
TextView main_title = (TextView) findViewById(R.id.secondary_toolbar_title);
main_title.setText("PROJECT LOCATIONS");
main_title.setTextColor( this.getResources().getColor( R.color.white ) );
setSupportActionBar( sectoolbar );
usrname = SaveSharedPreference.getUserName( show_outlets_alt.this );
projectID = SaveSharedPreference.getProjName( show_outlets_alt.this );
LISTVIEWOUTLETS = this.findViewById( R.id.listView2alt );
imageView = this.findViewById( R.id.imageViewFlag );
cButton = findViewById( R.id.complianceButton );
Id_Array = new ArrayList<>();
OutletName_Array = new ArrayList<>();
OutletAddress1_Array = new ArrayList<>();
OutletAddress2_Array = new ArrayList<>();
City_Array = new ArrayList<>();
Phone_Array = new ArrayList<>();
sqLiteHelper = new SQLiteHelper(this);
LISTVIEWOUTLETS.setOnItemClickListener( new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
projectName = SaveSharedPreference.getProjName( show_outlets_alt.this );
String outletName = ListViewClickItemArrayOutlets.get(position).toString();
SaveSharedPreference.setOutletName( getApplicationContext(),outletName );
Intent intent = new Intent(getApplicationContext(), ShowOutletParams.class);
startActivityForResult( intent,1 );
}
} );
} //end of oncreate
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult( requestCode, resultCode, data );
if (resultCode == RESULT_OK) {
Intent refresh = new Intent( this, ShowDataActivity.class );
startActivityForResult(refresh,1);
this.finish();
}
}
#Override
protected void onResume() {
ShowSQLiteOutletdata();
super.onResume();
}
private void ShowSQLiteOutletdata() {
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
projectID = SaveSharedPreference.getProjName( show_outlets_alt.this );
cursor = sqLiteDatabase.rawQuery("SELECT * FROM "+SQLiteHelper.TABLE_NAME1+" where pid = (select projectId from "+SQLiteHelper.TABLE_NAME+ " where ProjectName = '"+projectID+"'"+") and Status=1;", null);
Id_Array.clear();
OutletName_Array.clear();
OutletAddress1_Array.clear();
OutletAddress2_Array.clear();
City_Array.clear();
Phone_Array.clear();
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
Id_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_ID)));
ListViewClickItemArrayOutlets.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_OutletName)));
OutletName_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_OutletName)));
OutletAddress1_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_outletAddress1)));
OutletAddress2_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_outletAddress2)));
City_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_city)));
Phone_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_phone)));
} while (cursor.moveToNext());
}
}
listAdapterOutlets = new AltOutletAdapter(show_outlets_alt.this,
Id_Array,
OutletName_Array,
OutletAddress1_Array,
OutletAddress2_Array,
City_Array,
Phone_Array
);
LISTVIEWOUTLETS.setAdapter(listAdapterOutlets);
cursor.close();
} //end of ShowSqliteOutletData
#Override
public void onBackPressed() {
super.onBackPressed();
Intent backIntent = new Intent(getApplicationContext(), ShowDataActivity.class);
startActivity(backIntent);
}
}//end of public class
AltOutletAdapter.java
public class AltOutletAdapter extends BaseAdapter {
Context context;
ArrayList<String> ID;
ArrayList<String> O_Name;
ArrayList<String> O_Address1;
ArrayList<String> O_Address2;
ArrayList<String> City;
ArrayList<String> Phone;
ArrayList<String> iButton;
public AltOutletAdapter(Context context, ArrayList<String> ID, ArrayList<String> o_Name, ArrayList<String> o_Address1, ArrayList<String> o_Address2, ArrayList<String> city, ArrayList<String> phone) {
this.context = context;
this.ID = ID;
O_Name = o_Name;
O_Address1 = o_Address1;
O_Address2 = o_Address2;
City = city;
Phone = phone;
}
#Override
public int getCount() {
return ID.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View child, ViewGroup parent) {
AltOutletAdapter.Holder holder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.alt_list_view, null);
holder = new AltOutletAdapter.Holder();
holder.O_Name = (TextView) child.findViewById(R.id.tvOutletNamealt);
holder.O_Address1 = (TextView) child.findViewById(R.id.tvOutletAddress1alt);
holder.O_Address2 = (TextView) child.findViewById(R.id.tvOutletAddress2alt);
holder.City = (TextView) child.findViewById(R.id.tvOutletCityalt);
holder.Phone = (TextView) child.findViewById(R.id.tvOutletPhonealt);
child.setTag(holder);
} else {
holder = (AltOutletAdapter.Holder) child.getTag();
}
holder.O_Name.setText(O_Name.get(position));
holder.O_Address1.setText(O_Address1.get(position));
holder.O_Address2.setText(O_Address2.get(position));
holder.City.setText(City.get(position));
holder.Phone.setText(Phone.get(position));
return child;
}
private class Holder {
TextView O_Name;
TextView O_Address1;
TextView O_Address2;
TextView City;
TextView Phone;
Button iButton;
ImageView imageView;
}
}
first I have question.
why don't you make Model for Items?
Anyway if you want to make click event by element, just add click listener in your adapter.
so Example is here
add id in your whole layout.
( android:id="#+id/layout" )
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="3dp"
android:background="#FFFFFF"
android:layout_marginLeft="2dp"
android:layout_marginBottom="2dp"
android:descendantFocusability="blocksDescendants">
...
add click listener in your adapter
public class AltOutletAdapter extends BaseAdapter {
Context context;
ArrayList<String> ID;
ArrayList<String> O_Name;
ArrayList<String> O_Address1;
ArrayList<String> O_Address2;
ArrayList<String> City;
ArrayList<String> Phone;
ArrayList<String> iButton;
public LinearLayout linearLayout;
public AltOutletClickListener altOutletClickListener;
public AltOutletAdapter(Context context, ArrayList<String> ID, ArrayList<String> o_Name, ArrayList<String> o_Address1, ArrayList<String> o_Address2, ArrayList<String> city, ArrayList<String> phone, AltOutletClickListener listener) {
this.context = context;
this.ID = ID;
O_Name = o_Name;
O_Address1 = o_Address1;
O_Address2 = o_Address2;
City = city;
Phone = phone;
altOutletClickListener = listener;
}
#Override
public int getCount() {
return ID.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View child, ViewGroup parent) {
AltOutletAdapter.Holder holder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.alt_list_view, null);
holder = new AltOutletAdapter.Holder();
holder.O_Name = (TextView) child.findViewById(R.id.tvOutletNamealt);
holder.O_Address1 = (TextView) child.findViewById(R.id.tvOutletAddress1alt);
holder.O_Address2 = (TextView) child.findViewById(R.id.tvOutletAddress2alt);
holder.City = (TextView) child.findViewById(R.id.tvOutletCityalt);
holder.Phone = (TextView) child.findViewById(R.id.tvOutletPhonealt);
holder.linearLayout = (LinearLayout) child.findViewById(R.id.layout);
holder.iButton = (Button) child.findViewById(R.id.complianceButton);
child.setTag(holder);
} else {
holder = (AltOutletAdapter.Holder) child.getTag();
}
holder.O_Name.setText(O_Name.get(position));
holder.O_Address1.setText(O_Address1.get(position));
holder.O_Address2.setText(O_Address2.get(position));
holder.City.setText(City.get(position));
holder.Phone.setText(Phone.get(position));
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
altOutletClickListener.itemClickListener(v, position);
}
});
holder.iButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
altOutletClickListener.imageClickListener(v, position);
}
});
return child;
}
private class Holder {
TextView O_Name;
TextView O_Address1;
TextView O_Address2;
TextView City;
TextView Phone;
Button iButton;
ImageView imageView;
LinearLayout linearLayout;
}
public interface AltOutletClickListener {
void itemClickListener(View v, int position);
void imageClickListener(View v, int position);
}
}
when you call adapter in java, add click event as params.
ArrayList<String> test = new ArrayList<>();
AltOutletAdapter altOutletAdapter = new AltOutletAdapter(MainActivity.this, test, test, test, test, test, test, new AltOutletAdapter.AltOutletClickListener() {
#Override
public void itemClickListener(View v, int position) {
// when click layout
}
#Override
public void imageClickListener(View v, int position) {
// when click button
}
});
I just tested and use this.
But I think make Model is better.
ArrayList<String> test = new ArrayList<>();
ArrayList<Model> test = new ArrayList<>(); // it is better
**UPDATE : make Model **
simply, I make your Model Example.
make Model file.
public class AltOutlet {
private String name;
private String address1;
private String address2;
private String city;
private String phone;
public AltOutlet(String name, String address1, String address2, String city, String phone) {
this.name = name;
this.address1 = address1;
this.address2 = address2;
this.city = city;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
change your adapter
public class AltOutletAdapter extends BaseAdapter {
Context context;
ArrayList<AltOutlet> altOutletArrayList;
public LinearLayout linearLayout;
public AltOutletClickListener altOutletClickListener;
public AltOutletAdapter(Context context, ArrayList<AltOutlet> altOutletList, AltOutletClickListener listener) {
this.context = context;
altOutletArrayList = altOutletList;
altOutletClickListener = listener;
}
#Override
public int getCount() {
return altOutletArrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View child, ViewGroup parent) {
AltOutletAdapter.Holder holder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.alt_list_view, null);
holder = new AltOutletAdapter.Holder();
holder.O_Name = (TextView) child.findViewById(R.id.tvOutletNamealt);
holder.O_Address1 = (TextView) child.findViewById(R.id.tvOutletAddress1alt);
holder.O_Address2 = (TextView) child.findViewById(R.id.tvOutletAddress2alt);
holder.City = (TextView) child.findViewById(R.id.tvOutletCityalt);
holder.Phone = (TextView) child.findViewById(R.id.tvOutletPhonealt);
holder.linearLayout = (LinearLayout) child.findViewById(R.id.layout);
holder.iButton = (Button) child.findViewById(R.id.complianceButton);
child.setTag(holder);
} else {
holder = (AltOutletAdapter.Holder) child.getTag();
}
holder.O_Name.setText(altOutletArrayList.get(position).getName());
holder.O_Address1.setText(altOutletArrayList.get(position).getAddress1());
holder.O_Address2.setText(altOutletArrayList.get(position).getAddress2());
holder.City.setText(altOutletArrayList.get(position).getCity());
holder.Phone.setText(altOutletArrayList.get(position).getPhone());
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
altOutletClickListener.itemClickListener(v, position);
}
});
holder.iButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
altOutletClickListener.imageClickListener(v, position);
}
});
return child;
}
private class Holder {
TextView O_Name;
TextView O_Address1;
TextView O_Address2;
TextView City;
TextView Phone;
Button iButton;
ImageView imageView;
LinearLayout linearLayout;
}
public interface AltOutletClickListener {
void itemClickListener(View v, int position);
void imageClickListener(View v, int position);
}
}
when you add item in java file, use Model
AltOutlet altOutlet = new AltOutlet("test", "address1", "address2", "city", "phone");
altOutlets.add(altOutlet);
AltOutletAdapter altOutletAdapter = new AltOutletAdapter(MainActivity.this, altOutlets, new AltOutletAdapter.AltOutletClickListener() {
#Override
public void itemClickListener(View v, int position) {
// when click layout
}
#Override
public void imageClickListener(View v, int position) {
// when click button
}
});
When I change the color of a cardview which is inside a recyclerview, it changes color of other items also. How can I solve this problem.
Below is the part of the module where I am changing the background color :
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && mListener != null) {
mListener.onLongItemClick(child, recyclerView.getChildAdapterPosition(child));
int position = recyclerView.getChildLayoutPosition(child);
child.setBackgroundColor(mContext.getResources().getColor(R.color.blue_light));
Toast.makeText(mContext, "Id " + String.valueOf(position), Toast.LENGTH_SHORT).show();
deleteItems.add(position);
}
}
});
}
The code for the adapter is given below :
public class DiaryAdapter extends RecyclerView.Adapter<DiaryAdapter.ViewHolder>{
List <DiaryInfo> mItems;
SQLiteDatabase mydatabase;
public DiaryAdapter() {
super();
mItems = new ArrayList <DiaryInfo> ();
mItems = MainActivity.diaryinfo;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.content_main, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
mydatabase = (MainActivity.mContext).openOrCreateDatabase("remember", android.content.Context.MODE_PRIVATE, null);
// While changing database information here change at Itemadd's done button listener also!
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS memories_pics(id VARCHAR PRIMARY KEY, path VARCHAR)");
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
try {
DiaryInfo info = mItems.get(i);
viewHolder.desc.setText(Html.fromHtml((info.getDesc()).replaceAll("''", "\"")));
// Modifying date to readable format
String tempDate = info.getDate();
Locale locale = (MainActivity.mContext).getResources().getConfiguration().locale;
String[] temp = tempDate.split("/"); // Splitting date dd/mm/yyyy
int month = Integer.valueOf(temp[1]);
DateFormatSymbols symbols = new DateFormatSymbols(locale);
String[] monthNames = symbols.getMonths();
String currentMonth = monthNames[month - 1];
viewHolder.date.setText(currentMonth + " " + temp[0]);
String id = info.getThumbnail();
String path = ""; // Final path of the thumbnail
Cursor cursor = mydatabase.rawQuery("SELECT * FROM memories_pics WHERE id=\'" + id + "\' LIMIT 1", null);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
path = cursor.getString(cursor
.getColumnIndex("path"));
cursor.moveToNext();
break;
}
}
cursor.close();
File file = null;
// Either load image from user clicked images or a default image
if ((String.valueOf(path.split("=")[0])).equals("")) {
Glide.with(MainActivity.mContext).load(R.drawable.default_pic).centerCrop().into(viewHolder.imgThumbnail);
} else {
file = new File(String.valueOf(path.split("=")[0])); // Load path in file
Glide.with(MainActivity.mContext).load(file).centerCrop().into(viewHolder.imgThumbnail);
}
}
catch (Exception e) {
}
}
#Override
public int getItemCount() {
return mItems.size();
}
public Object getItem(int pos) { return mItems.get(pos); }
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imgThumbnail;
public TextView date, desc;
public ViewHolder(View itemView) {
super(itemView);
imgThumbnail = (ImageView) itemView.findViewById(R.id.thumbnail);
date = (TextView)itemView.findViewById(R.id.date);
desc = (TextView)itemView.findViewById(R.id.description);
}
}
}
Below is the cardview layout :
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/thumbnail"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_alignParentTop="true"
android:scaleType="centerCrop"
android:src="#drawable/default_pic"/>
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/thumbnail"
android:maxLines="1"
android:padding="4dp"
android:text="Title"
android:textColor="#222"
android:textStyle="bold"
android:textSize="22sp"/>
<TextView
android:id="#+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/date"
android:maxLines="3"
android:padding="4dp"
android:text="Description"
android:textColor="#666"
android:textSize="14sp"
android:ellipsize="end"/>
</RelativeLayout>
Please help!
i am creating a app that allows users to select the food they want and displaying the ordered food.
My listview has a checkbox, 3 textview and a numberpicker. I am now trying to get the selected items and quantity from the numberpicker and displaying on the next activity. I have tried some codes but unsure whether it works.
I am kinda new with android studio.How should i approach it from now on? Below are my codes
Listview row :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView1"
android:id="#+id/txt1"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
style="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView2"
android:id="#+id/txt2"
android:textStyle="bold"
android:layout_below="#+id/txt1"
android:layout_alignStart="#+id/txt1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView3"
android:id="#+id/txt3"
android:textStyle="bold"
android:layout_below="#+id/txt2"
android:layout_alignStart="#+id/txt2" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ckBox"
android:checked="false"
android:layout_below="#+id/txt3"
android:layout_alignStart="#+id/txt3" />
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:gravity="left"
android:layout_alignBottom="#+id/ckBox"
android:layout_toStartOf="#+id/txt1"
android:layout_alignParentEnd="false"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/numberPicker"
android:layout_toEndOf="#+id/txt2"
android:layout_marginStart="23dp"
android:layout_alignParentTop="true"
android:layout_alignBottom="#+id/ckBox" />
customadapter :
public class CustomLVAdapter extends BaseAdapter {
private Context context;
LayoutInflater inflater;
private ArrayList<CustomItem> objectList;
private int[] imageId;
private class ViewHolder {
TextView txt1,txt2,txt3;
CheckBox ckBox;
ImageView image;
NumberPicker np;
}
public CustomLVAdapter(Context context, ArrayList<CustomItem> objectList,int[]prgmImages){
this.context = context;
this.inflater = LayoutInflater.from(context);
this.objectList = objectList;
this.imageId = prgmImages;
}
public int getCount(){
return objectList.size();
}
public CustomItem getItem (int position) {
return objectList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row_checkbox_textview, null);
holder.txt1 = (TextView) convertView.findViewById(R.id.txt1);
holder.txt2 = (TextView) convertView.findViewById(R.id.txt2);
holder.txt3 = (TextView) convertView.findViewById(R.id.txt3);
holder.image=(ImageView) convertView.findViewById(R.id.image);
holder.ckBox = (CheckBox) convertView.findViewById(R.id.ckBox);
holder.np = (NumberPicker) convertView.findViewById(R.id.numberPicker);
holder.np.setMinValue(0);
holder.np.setMaxValue(10);
convertView.setTag(holder);
holder.ckBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
CustomItem object = (CustomItem) cb.getTag();
Toast.makeText(context,
"You have selected: " + object.getItem() +
"Price: " + object.getPrice() +
"Qty: " + object.getQty(),
Toast.LENGTH_LONG).show();
object.setSelected(cb.isChecked());
}
}
);
holder.np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
NumberPicker p = picker;
CustomItem object = (CustomItem) p.getTag();
object.setQty(String.valueOf(newVal));
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
CustomItem object = objectList.get(position);
holder.txt1.setText(object.getItem());
holder.txt2.setText(object.getDesc());
holder.txt3.setText(object.getPrice());
holder.np.setTag(object);
holder.image.setImageResource(imageId[position]);
holder.ckBox.setChecked(object.isSelected());
holder.ckBox.setTag(object);
return convertView;
} }
menu activity :
public class MenuActivity extends Activity {
private String server = "http://172.16.156.56";
private String sql_table = "orders";
private ListView list;
private TextView txtOrder, txtMember, txtPrice;
private Button btnAdd;
ArrayList<String> rows;
ListView listView1;
Button btnSubmit;
ArrayList<CustomItem> itemList, selectedList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
txtOrder=(TextView) findViewById(R.id.txt1);
txtMember=(TextView) findViewById(R.id.txt2);
txtPrice=(TextView) findViewById(R.id.txt3);
list=(ListView) findViewById(R.id.listView);
btnAdd = (Button)findViewById(R.id.button);
rows = new ArrayList<String>();
itemList=new ArrayList<CustomItem>();
itemList.add(new CustomItem("Fried Rice","description","1","Quantity"));
itemList.add(new CustomItem("Fried Noodle","description","2","Quantity"));
itemList.add(new CustomItem("Prawn noodle","description","3","Quantity"));
itemList.add(new CustomItem("Chicken Rice","description","4","Quantity"));
int[] prgmImages={R.drawable.friedrice,R.drawable.friednoodle,R.drawable.pnoodle,R.drawable.chickenrice};
listView1 = (ListView) findViewById(R.id.listView);
CustomLVAdapter customLVAdapter = new CustomLVAdapter(this, itemList,prgmImages);
listView1.setAdapter(customLVAdapter);
btnSubmit = (Button) findViewById(R.id.button);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
selectedList = new ArrayList<CustomItem>();
int total = 0;
for (int i = 0; i < itemList.size(); i++) {
CustomItem object = itemList.get(i);
if (object.isSelected()) {
responseText.append(object.getItem() + "," + object.getQty() + ",");//item
selectedList.add(object);
//calculate price
total = total + Integer.parseInt(object.getQty()) * Integer.parseInt(object.getPrice());
}
}
Add(responseText.toString(), "5565", String.valueOf(total));
String strOrder = txtOrder.getText().toString();
String strMember = txtMember.getText().toString();
String strPrice = txtPrice.getText().toString();
Intent i = new Intent(v.getContext(), ReceiptActivity.class);
startActivity(i);
i.putExtra("Order", strOrder);
i.putExtra("Member", strMember);
i.putExtra("Price", strPrice);
Toast.makeText(getApplicationContext(), responseText + " $" + total,
Toast.LENGTH_SHORT).show();
SelectAll();
//store in database
//go to ReceiptActivity - membership, item, totalprice
}
});
}
public void Add(final String item, final String membership, final String price)
{
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = server + "/insertorder.php";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("item",item );
MyData.put("membership",membership );
MyData.put("price",price );
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
SelectAll();
}
public void SelectAll()
{
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = server + "/fetchorder.php";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray jsonMainNode = jsonResponse.optJSONArray(sql_table);
rows.clear();
for(int i=0; i < jsonMainNode.length(); i++)
{
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String order = jsonChildNode.optString("item").toString();
String membership = jsonChildNode.optString("membership").toString();
String price = jsonChildNode.optString("price").toString();
rows.add(order + ", " + membership + ", " + price );
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MenuActivity.this,
android.R.layout.simple_list_item_1, rows);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
});
MyRequestQueue.add(MyStringRequest);
}
}
reciept activity (the codes of the selected items will be displayed here):
public class ReceiptActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receipt);
Bundle extras = getIntent().getExtras();
String strOrder = extras.getString("Order");
String strMember = extras.getString("Member");
String strPrice = extras.getString("Price");
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText("Order:" +strOrder+" ");
}
}
Receipt xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#drawable/background2"
tools:context="com.example.android.cardemulation.ReceiptActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txt4"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txt5"
android:layout_below="#+id/txt4"
android:layout_centerHorizontal="true"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="74dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView2"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView3"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true" />
CustomItem
public class CustomItem {
private int id;
private String item;
private String price;
private String desc;
private String qty;
private Boolean selected = false;
public CustomItem(){
}
public CustomItem(String item,String desc, String price,String qty){
this.item=item;
this.desc=desc ;
this.price=price;
this.qty=qty;
}
public CustomItem(int id, String item,String desc, String price,String qty){
this.id=id;
this.item=item;
this.desc=desc;
this.price=price;
this.qty=qty;
}
public int getId(){
return id;
}
public void setId (int id) {
this.id=id;
}
public String getItem(){
return item;
}
public void setItem(String item){
this.item=item;
}
public String getDesc()
{
return desc;
}
public void setDesc(String desc) {
this.desc=desc;
}
public String getPrice()
{
return price;
}
public void setPrice(String price) {
this.price=price;
}
public String getQty()
{
return qty;
}
public void setQty(String qty) {
this.qty=qty;
}
public boolean isSelected(){
return selected;
}
public void setSelected(boolean selected){
this.selected=selected;
}
}
I am assuming your CustomItem class has a boolean variable whose value can be retrieved by a getSelected() method.
Create a public static ArrayList like this in your Adapter class
public static ArrayList<CustomItem> arl_food=new ArrayList<>();
Inside your CustomLVAdapter() constructor add this
this.objectList=objectList;
arl_food.clear();
for(int i=0;i<this.objectList.size();i++)
{
arl_food.add(this.objectList.get(i));
}
Instead of creating a new CustomItem object, you should save the data to the particular object inside your ArrayList.
Add this code inside your CheckBox click event :
arl_food.get(position).setSelected(cb.isChecked());
Then inside your NumberPicker valueChanged event :
arl_food.get(position).setQty(String.valueOf(newVal));
In your Next Activity use this list like this :
for(int i=0;i<CustomLVAdapter.arl_food.size();i++)
{
if(CustomLVAdapter.arl_food.get(i).getSelected())
{
//Show the food item from your list and do your stuff here
}
}
In my custom listview, when i try to scroll down to view a new list item (either bottom or top) the scroll is becoming laggy. Im kinda new in android developement and database so i dunno what is the cause of this.
This is my MainActivity
public class MainActivity extends AppCompatActivity implements CustomAdapter.passing{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_loading);
db = new DBHandler(this,null,null,1);
namaDoctor = this.getResources().getStringArray(R.array.namaDokter);
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
setContentView(R.layout.activity_main);
searchSpesIcon = (ImageView) findViewById(R.id.buttonSearchSpesial);
searchRsIcon = (ImageView) findViewById(R.id.buttonSearchRs);
searchField = (EditText) findViewById(R.id.searchField);
searchDocIcon = (ImageView) findViewById(R.id.buttonSearchDoctor);
help = (LinearLayout) findViewById(R.id.help_view);
searchDocIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
keyword = searchField.getText().toString();
query = "SELECT * FROM doctor WHERE nama LIKE '%"+keyword+"%';";
namaDoctor = db.searchDoctor(query);
id = db.getDoctorId();
lokasia = db.getDoctorLokasiA();
lokasib = db.getDoctorLokasiB();
lokasic = db.getDoctorLokasiC();
alamata = db.getDoctorAlamatA();
alamatb = db.getDoctorAlamatB();
alamatc = db.getDoctorAlamatC();
if(tes != namaDoctor.length){
change();
Toast.makeText(getApplicationContext(),"Hasil pencarian nama dokter " +keyword,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"Tidak ada hasil",Toast.LENGTH_SHORT).show();
}
}
});
searchSpesIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
keyword = searchField.getText().toString();
query = "SELECT * FROM doctor WHERE spesialisasi LIKE '%"+keyword+"%';";
namaDoctor = db.searchDoctor(query);
id = db.getDoctorId();
lokasia = db.getDoctorLokasiA();
lokasib = db.getDoctorLokasiB();
lokasic = db.getDoctorLokasiC();
alamata = db.getDoctorAlamatA();
alamatb = db.getDoctorAlamatB();
alamatc = db.getDoctorAlamatC();
if(tes != namaDoctor.length){
change();
Toast.makeText(getApplicationContext(),"Hasil pencarian dokter spesialisasi " +keyword,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"Tidak ada hasil",Toast.LENGTH_SHORT).show();
}
}
});
searchRsIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
keyword = searchField.getText().toString();
query = "SELECT * FROM doctor " +
"WHERE lokasia LIKE '%"+keyword+"%' OR lokasib LIKE '%"+keyword+"%' OR lokasic LIKE '%"+keyword+"%';";
namaDoctor = db.searchDoctor(query);
id = db.getDoctorId();
lokasia = db.getDoctorLokasiA();
lokasib = db.getDoctorLokasiB();
lokasic = db.getDoctorLokasiC();
alamata = db.getDoctorAlamatA();
alamatb = db.getDoctorAlamatB();
alamatc = db.getDoctorAlamatC();
if(tes != namaDoctor.length){
change();
Toast.makeText(getApplicationContext(),"Hasil pencarian dokter di rumah sakit " +keyword,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"Tidak ada hasil",Toast.LENGTH_SHORT).show();
}
}
});
}
},milis);
}
void change(){
if(help.getVisibility()==View.VISIBLE){help.setVisibility(View.GONE);}
cAdapter = new CustomAdapter(this,namaDoctor,id);
//use callback
cAdapter.setPass(this);
list = (ListView) findViewById(R.id.listContatiner);
list.setAdapter(cAdapter);
cAdapter.notifyDataSetChanged();
}
#Override
public void getTag1(int t){
p1=t;
}
#Override
public void getTag2(int t2) {
p2=t2;
setNewAct(p1,p2);
}
public void setNewAct(int x, int y){
//some method
}
My CustomAdapter class
public class CustomAdapter extends ArrayAdapter {
Context c1;
String s1[];
Integer id[];
String spesialisasi[] ;
String daerahPraktek[];
int arrayImageDoctor[] = {R.drawable.doctor_1...};
public CustomAdapter(Context c, String s[], Integer i[]) {
super(c,R.layout.item_doctor,s);
this.c1=c;
this.s1=s;
this.id=i;
}
private passing pass;
#Override
public View getView(final int position, View v, ViewGroup parent) {
final LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.item_doctor,null);
spesialisasi= c1.getResources().getStringArray(R.array.spesialiasiDokter);
daerahPraktek = c1.getResources().getStringArray(R.array.daerahDokter);
final TextView nama = (TextView) v.findViewById(R.id.namaDoctor);
TextView spesial = (TextView) v.findViewById(R.id.spesialisasiDoctor);
TextView daerah = (TextView) v.findViewById(R.id.daerahPraktekDoctor);
ImageView ImageDoc = (ImageView) v.findViewById(R.id.imageListDoctor);
Button lokasi = (Button) v.findViewById(R.id.lokasiPraktek);
nama.setText(s1[position]);
spesial.setText("Dokter " + spesialisasi[id[position]]);
daerah.setText(daerahPraktek[id[position]]);
ImageDoc.setImageResource(arrayImageDoctor[id[position]]);
lokasi.setTag(R.id.tag1,id[position]);
lokasi.setTag(R.id.tag2,position);
lokasi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int tag = (int) v.getTag(R.id.tag1);
int pos = (int) v.getTag(R.id.tag2);
pass.getTag1(tag);
pass.getTag2(pos);
}
});
return v;
}
public void setPass(passing pass){
this.pass=pass;
}
public interface passing{
void getTag1(int t1);
void getTag2(int t2);
}
My DBHandler class
public class DBHandler extends SQLiteOpenHelper {
public DBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
c=context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_DOCTOR + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAMA + " TEXT, " +
COLUMN_DAERAH + " TEXT, " +
COLUMN_SPESIALISASI + " TEXT, " +
COLUMN_LOKASI_A + " TEXT, " +
COLUMN_LOKASI_B + " TEXT, " +
COLUMN_LOKASI_C + " TEXT, " +
COLUMN_ALAMAT_A + " TEXT, " +
COLUMN_ALAMAT_B + " TEXT, " +
COLUMN_ALAMAT_C + " TEXT " +");";
db.execSQL(query);
arrayNama = c.getResources().getStringArray(R.array.namaDokter);
arrayDaerah = c.getResources().getStringArray(R.array.daerahDokter);
arraySpesialisasi = c.getResources().getStringArray(R.array.spesialiasiDokter);
arrayLokasiA = c.getResources().getStringArray(R.array.lokasiA);
arrayLokasiB = c.getResources().getStringArray(R.array.lokasiB);
arrayLokasiC = c.getResources().getStringArray(R.array.lokasiC);
arrayAlamatA = c.getResources().getStringArray(R.array.alamatA);
arrayAlamatB = c.getResources().getStringArray(R.array.alamatB);
arrayAlamatC = c.getResources().getStringArray(R.array.alamatC);
ContentValues cv = new ContentValues();
for (int i = 0; i < arrayNama.length; i++) {
cv.put(COLUMN_NAMA, arrayNama[i]);
cv.put(COLUMN_DAERAH, arrayDaerah[i]);
cv.put(COLUMN_SPESIALISASI, arraySpesialisasi[i]);
cv.put(COLUMN_LOKASI_A, arrayLokasiA[i]);
cv.put(COLUMN_LOKASI_B, arrayLokasiB[i]);
cv.put(COLUMN_LOKASI_C, arrayLokasiC[i]);
cv.put(COLUMN_ALAMAT_A, arrayAlamatA[i]);
cv.put(COLUMN_ALAMAT_B, arrayAlamatB[i]);
cv.put(COLUMN_ALAMAT_C, arrayAlamatC[i]);
db.insert(TABLE_DOCTOR, null, cv);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DOCTOR);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PATIENT);
onCreate(db);
}
public String[] searchDoctor(String qdoc){
SQLiteDatabase db = getWritableDatabase();
Cursor c= db.rawQuery(qdoc,null);
String selectedDoc[] = new String[c.getCount()];
Integer selectedId[] = new Integer[c.getCount()];
String selectedLokasiA[] = new String[c.getCount()];
String selectedLokasiB[] = new String[c.getCount()];
String selectedLokasiC[] = new String[c.getCount()];
String selectedAlamatA[] = new String[c.getCount()];
String selectedAlamatB[] = new String[c.getCount()];
String selectedAlamatC[] = new String[c.getCount()];
int i = 0;
while(c.moveToNext()){
String doc = c.getString(c.getColumnIndex(COLUMN_NAMA));
Integer id = c.getInt(c.getColumnIndex(COLUMN_ID));
String lokasia = c.getString(c.getColumnIndex(COLUMN_LOKASI_A));
String lokasib = c.getString(c.getColumnIndex(COLUMN_LOKASI_B));
String lokasic = c.getString(c.getColumnIndex(COLUMN_LOKASI_C));
String alamata = c.getString(c.getColumnIndex(COLUMN_ALAMAT_A));
String alamatb = c.getString(c.getColumnIndex(COLUMN_ALAMAT_B));
String alamatc = c.getString(c.getColumnIndex(COLUMN_ALAMAT_C));
selectedDoc[i]= doc;
selectedId[i] = id-1;
selectedLokasiA[i]= lokasia;
selectedLokasiB[i] = lokasib;
selectedLokasiC[i] = lokasic;
selectedAlamatA[i]= alamata;
selectedAlamatB[i]=alamatb;
selectedAlamatC[i]= alamatc;
i++;
}
this.doctorId=selectedId;
this.doctorLokasiA=selectedLokasiA;
this.doctorLokasiB=selectedLokasiB;
this.doctorLokasiC=selectedLokasiC;
this.doctorAlamatA=selectedAlamatA;
this.doctorAlamatB=selectedAlamatB;
this.doctorAlamatC=selectedAlamatC;
return selectedDoc;
}
public Integer[] getDoctorId(){
return doctorId;
}
public static String[] getDoctorLokasiA() {
return doctorLokasiA;
}
public static String[] getDoctorLokasiB() {
return doctorLokasiB;
}
public static String[] getDoctorLokasiC() {
return doctorLokasiC;
}
public static String[] getDoctorAlamatA() {
return doctorAlamatA;
}
public static String[] getDoctorAlamatB() {
return doctorAlamatB;
}
public static String[] getDoctorAlamatC() {
return doctorAlamatC;
}
And my Item_doctor.xml
<RelativeLayout
android:id="#+id/itemCLick"
android:background="#0E9EA1"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="15dp">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/doctor_1"
android:id="#+id/imageListDoctor"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/imageListDoctor"
android:layout_toEndOf="#+id/imageListDoctor"
android:id="#+id/linearLayout">
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nama"
android:id="#+id/namaDoctor"/>
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Spesialis"
android:id="#+id/spesialisasiDoctor"/>
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Daerah"
android:id="#+id/daerahPraktekDoctor"/>
</LinearLayout>
<Button
android:layout_width="115dp"
android:layout_height="wrap_content"
android:text="Lihat lokasi praktek"
android:layout_alignBottom="#+id/linearLayout"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/lokasiPraktek"
android:onClick="LokasiPraktek"/>
Can someone tell me :
1.Does cursor inserting to array and Sqlite Query can cause big performance issue if not done correctly ?
2.Does the amount of view in the item of an list can affect the performance ?
3.What other things that affect listview performance ?
It will be good if someone tell me in which part of my code that i must change to increase the scroll speed.
Performance of list view can be increased if you use custom ViewHolder and implement in adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
spesialisasi = c1.getResources().getStringArray(R.array.spesialiasiDokter);
daerahPraktek = c1.getResources().getStringArray(R.array.daerahDokter);
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.item_doctor, parent, false);
viewHolder = new ViewHolder();
viewHolder.nama = (TextView) v.findViewById(R.id.namaDoctor);
viewHolder.spesial = (TextView) v.findViewById(R.id.spesialisasiDoctor);
viewHolder.daerah = (TextView) v.findViewById(R.id.daerahPraktekDoctor);
viewHolder.ImageDoc = (ImageView) v.findViewById(R.id.imageListDoctor);
viewHolder.lokasi = (Button) v.findViewById(R.id.lokasiPraktek);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.nama.setText(s1[position]);
viewHolder.spesial.setText("Dokter " + spesialisasi[id[position]]);
viewHolder.daerah.setText(daerahPraktek[id[position]]);
viewHolder.ImageDoc.setImageResource(arrayImageDoctor[id[position]]);
viewHolder.lokasi.setTag(R.id.tag1, id[position]);
viewHolder.lokasi.setTag(R.id.tag2, position);
viewHolder.lokasi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int tag = (int) v.getTag(R.id.tag1);
int pos = (int) v.getTag(R.id.tag2);
pass.getTag1(tag);
pass.getTag2(pos);
}
});
return convertView;
}
private class ViewHolder {
private ImageView ImageDoc;
private Button lokasi;
private TextView nama;
private TextView spesial;
private TextView daerah;
}
Your adapter class's getView method is not properly implemented.
Change it to
#Override
public View getView(final int position, View v, ViewGroup parent) {
View row;
if (v == null) {
final LayoutInflater li = (LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = li.inflate(R.layout.item_doctor, null);
} else {
row = v;
}
spesialisasi = c1.getResources().getStringArray(R.array.spesialiasiDokter);
daerahPraktek = c1.getResources().getStringArray(R.array.daerahDokter);
final TextView nama = (TextView) row.findViewById(R.id.namaDoctor);
TextView spesial = (TextView) row.findViewById(R.id.spesialisasiDoctor);
TextView daerah = (TextView) row.findViewById(R.id.daerahPraktekDoctor);
ImageView ImageDoc = (ImageView) row.findViewById(R.id.imageListDoctor);
Button lokasi = (Button) row.findViewById(R.id.lokasiPraktek);
nama.setText(s1[position]);
spesial.setText("Dokter " + spesialisasi[id[position]]);
daerah.setText(daerahPraktek[id[position]]);
ImageDoc.setImageResource(arrayImageDoctor[id[position]]);
lokasi.setTag(R.id.tag1, id[position]);
lokasi.setTag(R.id.tag2, position);
lokasi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int tag = (int) v.getTag(R.id.tag1);
int pos = (int) v.getTag(R.id.tag2);
pass.getTag1(tag);
pass.getTag2(pos);
}
});
return row;
}
getView function in adapter will called when you scrolled to make a item visible. As you write:
final LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.item_doctor,null);
View v will be relayout while you scroll so that it make bad performace. You need check to reuse this view by:
if(v==null) {
final LayoutInflater li = (LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v= li.inflate(R.layout.item_doctor, null);
}
I recommend you use ViewHolder class with Adapter.
try the below adapter,and set the Tag for you each View of Listview.
public class CustomAdapter extends ArrayAdapter {
Context c1;
String s1[];
Integer id[];
String spesialisasi[] ;
String daerahPraktek[];
int arrayImageDoctor[] = {R.drawable.doctor_1...};
public CustomAdapter(Context c, String s[], Integer i[]) {
super(c,R.layout.item_doctor,s);
this.c1=c;
this.s1=s;
this.id=i;
}
private passing pass;
#Override
public View getView(final int position, View v, ViewGroup parent) {
ViewHolder viewHolder = null;
if(v==null){
LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.item_doctor,null);
viewHolder = new ViewHolder();
viewHolder.nama = (TextView) v.findViewById(R.id.namaDoctor);
viewHolder.spesial = (TextView) v.findViewById(R.id.spesialisasiDoctor);
viewHolder.daerah = (TextView) v.findViewById(R.id.daerahPraktekDoctor);
viewHolder.ImageDoc = (ImageView) v.findViewById(R.id.imageListDoctor);
viewHolder.lokasi = (Button) v.findViewById(R.id.lokasiPraktek);
convertView.setTag(viewHolder);
}else{
iewHolder = (ViewHolder) convertView.getTag();
}
spesialisasi= c1.getResources().getStringArray(R.array.spesialiasiDokter);
daerahPraktek = c1.getResources().getStringArray(R.array.daerahDokter);
viewHolder.nama.setText(s1[position]);
viewHolder.spesial.setText("Dokter " + spesialisasi[id[position]]);
viewHolder.daerah.setText(daerahPraktek[id[position]]);
viewHolder.ImageDoc.setImageResource(arrayImageDoctor[id[position]]);
viewHolder.lokasi.setTag(R.id.tag1,id[position]);
viewHolder.lokasi.setTag(R.id.tag2,position);
viewHolder.lokasi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int tag = (int) v.getTag(R.id.tag1);
int pos = (int) v.getTag(R.id.tag2);
pass.getTag1(tag);
pass.getTag2(pos);
}
});
return v;
}
class ViewHolder {
TextView nama,spesial,daerah;
Button lokasi;
ImageView ImageDoc;
}
public void setPass(passing pass){
this.pass=pass;
}
public interface passing{
void getTag1(int t1);
void getTag2(int t2);
}
I want to add quantity when the add button is clicked and subtract quantity when sub button is clicked here i am not showing my setter/getter class(RowItem) and my xml files
(main.xml,item_details_view)
This is my Adapter class
public class ItemListBaseAdapter extends ArrayAdapter<RowItem> {
Context context;
public ItemListBaseAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
Button add,sub;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_details_view, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
holder.add = (Button) convertView
.findViewById(R.id.button1);
holder.sub = (Button) convertView
.findViewById(R.id.button2);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
holder.add.setTag(position);
holder.sub.setTag(position);
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Adds 1 to the counter
int counter=0;
counter = counter + 1;
}
});
holder.sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Subtract 1 from counter
int counter=0;
counter = counter - 1;
}
});
return convertView;
}
}
Thisi is my Activity class
public class ListViewImagesActivity extends Activity implements
OnItemClickListener {
public static final String[] titles = new String[] { "EggBurger",
"cheesBurger", "KingBurger", "Mixed" };
public static final String[] descriptions = new String[] {"Select 0 Item"
};
public static final Integer[] images = { R.drawable.burger1,
R.drawable.burger2, R.drawable.burger3, R.drawable.burger4 };
ListView listView;
List<RowItem> rowItems;
Button add,sub;
int counter=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i], descriptions[0]);
rowItems.add(item);
}
listView = (ListView) findViewById(R.id.list);
ItemListBaseAdapter adapter = new ItemListBaseAdapter(this,
R.layout.item_details_view, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
this is my RowItem class
public class RowItem {
private int imageId;
private String title;
private String desc;
public RowItem(int imageId, String title, String desc) {
this.imageId = imageId;
this.title = title;
this.desc = desc;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return title + "\n" + desc;
}
}
this is my main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
this is my item_details_view
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/icon"
android:layout_width="80dp"
android:layout_height="80dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/icon"
android:paddingBottom="10dp"
android:textColor="#CC0033"
android:textSize="16dp" />
<TextView
android:id="#+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/title"
android:layout_toRightOf="#+id/icon"
android:paddingLeft="10dp"
android:textColor="#3399FF"
android:textSize="14dp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button2"
android:layout_marginRight="16dp"
android:layout_toLeftOf="#+id/button2"
android:text="Add" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/desc"
android:layout_alignParentRight="true"
android:text="Sub" />
</RelativeLayout>
First of all, if you want to change the quantity value, you should have a variable representing quantity which you can change. You have included quantity value in the description text, which is bad design. What you should do is have a quantity variable int in the RowItem class as shown. You desc should just return a string from the quantity value as shown:
public class RowItem {
private int imageId;
private String title;
private int quantity = 0;
public RowItem(int imageId, String title, int quantity) {
this.imageId = imageId;
this.title = title;
this.quantity = quantity;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getDesc() {
return "Select " + quantity + " Item";
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
#Override
public String toString() {
return title + "\n" + quantity;
}
}
In your activity, instead of storing descriptions, store quantities:
public static final int[] quantities = new int[]{ 0 };
In onCreate initialize the rowItems as follows
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i], quantities[0]);
rowItems.add(item);
}
Finally, in your OnClickListener, get the quantity value, update it and set the new description.
final ViewHolder viewHolderFinal = holder;
final RowItem finalRowItem = rowItem;
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int quantity = finalRowItem.getQuantity(); // get the quantity for this row item
finalRowItem.setQuantity(quantity + 1); // update it by adding 1
viewHolderFinal.txtDesc.setText(finalRowItem.getDesc()); // set the new description (that uses the updated qunatity)
}
});
holder.sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int quantity = finalRowItem.getQuantity(); // get the quantity for this row item
finalRowItem.setQuantity(quantity - 1); // update it by subtracting 1
viewHolderFinal.txtDesc.setText(finalRowItem.getDesc()); // set the new description (that uses the updated qunatity)
}
});
*Note: * I have compiled and run this code. So if you do everything as I mentioned it will work.