Android ListView with Image, text and button - android

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
}
});

Related

Change imagebutton when pressed in RecyclerView

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);

getting the selected item with checkbox in listview along side with the quantity number picker

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
}
}

Multiple TextView in ListView?

I have a ListView with two TextView that fill from DataBase but show me just one row :
MainActivity.java :
public class MainActivity extends ActionBarActivity {
public static final String DIR_SDCARD =Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String DIR_DATABASE = DIR_SDCARD +"/Android/data/";
EditText editText;
DB db = new DB(MainActivity.this);
public String Titel_Drawer;
public String Titel_Drawert;
public String messageCursor;
public SQLiteDatabase sql;
public Cursor cursor;
public Cursor cursort;
public ArrayList<String> array;
public ArrayList<String> arrayt;
public static String PACKAGE_NAME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PACKAGE_NAME = getApplicationContext().getPackageName();
File file= new File(DIR_DATABASE + PACKAGE_NAME + "/DB");
file.mkdirs();
db.GetPackageName(PACKAGE_NAME);
db.CreateFile();
try {
db.CreateandOpenDataBase();
} catch (IOException e) {
e.printStackTrace();
}
sql = db.openDataBase();
cursor = sql.rawQuery("SELECT Comment FROM WebSite_MetaDataDBBack", null);
cursort = sql.rawQuery("SELECT Title FROM WebSite_CategoryBack", null);
array = new ArrayList<String>();
if(cursor!=null)
{
if(cursor.moveToFirst())
{
do {
Titel_Drawer = cursor.getString(cursor.getColumnIndex("Comment"));
array.add(Titel_Drawer);
} while (cursor.moveToNext());
}
}
cursor.close();
arrayt = new ArrayList<String>();
if(cursort!=null)
{
if(cursort.moveToFirst())
{
do {
Titel_Drawert = cursort.getString(cursort.getColumnIndex("Title"));
arrayt.add(Titel_Drawert);
} while (cursort.moveToNext());
}
}
cursort.close();
final List<Contact> listOfContact = new ArrayList<Contact>();
listOfContact.add(new Contact(Titel_Drawert,Titel_Drawer));
ContactAdapter ConAdapter = new ContactAdapter(this,listOfContact);
ListView list = (ListView) findViewById(R.id.mainListView);
list.setAdapter(ConAdapter);
}
}
Here is my get and set in Contact.java:
public class Contact {
private String title;
private String description;
public Contact(String title, String description) {
super();
this.title = title;
this.description = description;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
And here is ContactAdapter.java :
public class ContactAdapter extends BaseAdapter implements OnClickListener {
private Context context;
private List<Contact> listContact;
public ContactAdapter(Context context, List<Contact> listContact) {
this.context = context;
this.listContact = listContact;
}
public int getCount() {
return listContact.size();
}
public Object getItem(int position) {
return listContact.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup viewGroup) {
Contact entry = listContact.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.drawer_layout_main, null);
}
TextView tvContact = (TextView) convertView.findViewById(R.id.rowTextView_Main);
tvContact.setText(entry.getTitle());
TextView tvPhone = (TextView) convertView.findViewById(R.id.rowTextView_Main2);
tvPhone.setText(entry.getDescription());
return convertView;
}
#Override
public void onClick(View view) {
}
}
My activity_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/mainListView"
android:layout_width="fill_parent"
android:layout_height="300dp">
</ListView>
</LinearLayout>
My drawer_layout_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/rowTextView_Main"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
<TextView
android:id="#+id/rowTextView_Main2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
</LinearLayout>
Your listOfContact only has 1 item:
final List<Contact> listOfContact = new ArrayList<Contact>();
listOfContact.add(new Contact(Titel_Drawert,Titel_Drawer));
ContactAdapter ConAdapter = new ContactAdapter(this,listOfContact);
So your getCount() returns 1.
public int getCount() {
return listContact.size();
}
Replace your listContact in the adapter with a List that has one element for each item you want a row for.

How to add/remove quantity in a list view

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.

Unable to refresh the ListView

After i click "more" button, it suppose will extend the listview from 10 to 20.
However after clicked, the list view did not extend and remain original size.
It only can keep the position of scroll bar. This is half of what i need.
newsid = new int[webservice.news.size()];
title = new String[webservice.news.size()];
date = new String[webservice.news.size()];
imagepath = new String[webservice.news.size()];
for (int i = 0; i < webservice.news.size(); i++) {
newsid[i] = webservice.news.get(i).getID();
title[i] = webservice.news.get(i).getNtitle();
date[i] = webservice.news.get(i).getNArticalD();
imagepath[i] = webservice.news.get(i).getImagePath();
}
adapter = new CustomAdapter_ParticularCategoryAllNews(this, title,
date, imagepath);
lv.addFooterView(footermore);
if (constant.isOnline()) {
lv.addFooterView(constant.AdMob());
}
TextView titletext = (TextView) findViewById(R.id.text_pagetitle);
titletext.setText(pagetitletext.toString());
lv.setAdapter(adapter);
This is call when launch activity.
btnmore.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
for (int i = 0; i < webservice.news.size(); i++) {
newsid[i] = webservice.news.get(i).getID();
title[i] = webservice.news.get(i).getNtitle();
date[i] = webservice.news.get(i).getNArticalD();
imagepath[i] = webservice.news.get(i).getImagePath();
}
adapter.setTitle(title);
adapter.setDate(date);
adapter.setImagepath(imagepath);
position = lv.getFirstVisiblePosition();
lv.smoothScrollToPosition(position);
adapter.notifyDataSetChanged();
This is what i call after i click "more button". However the list did not extend from 10 to 20 items.
public class CustomAdapter_ParticularCategoryAllNews extends BaseAdapter {
private Activity activity;
private String[] title, date, imagepath;
private static LayoutInflater inflater = null;
private ImageLoader_Loader imageLoader;
private WindowManager wm = null;
private Display display;
private Config_ConstantVariable constant;
public CustomAdapter_ParticularCategoryAllNews(Activity a, String[] title,
String[] date, String[] imagepath) {
activity = a;
this.title = title;
this.date = date;
this.imagepath = imagepath;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
imageLoader = new ImageLoader_Loader(activity.getApplicationContext());
constant = new Config_ConstantVariable(activity);
}
public int getCount() {
return title.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public void setTitle(String[] title) {
this.title = title;
}
public void setDate(String[] date) {
this.date = date;
}
public void setImagepath(String[] imagepath) {
this.imagepath = imagepath;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.main_particularcategoryallnewslist,
parent, false);
LinearLayout linear = (LinearLayout) vi.findViewById(R.id.layout_image);
ImageView imageview = (ImageView) vi
.findViewById(R.id.image_categoryallnewstitle);
TextView titletext = (TextView) vi
.findViewById(R.id.text_categoryallnewstitle);
TextView datetext = (TextView) vi.findViewById(R.id.text_newsdate);
if (!imagepath[position].toString().equals("no picture")) {
imageview.setVisibility(View.VISIBLE);
linear.setVisibility(View.VISIBLE);
imageLoader.DisplayImage(imagepath[position], imageview);
} else {
imageview.setVisibility(View.GONE);
imageview.setImageDrawable(null);
linear.setVisibility(View.GONE);
display = wm.getDefaultDisplay();
int screenWidth = display.getWidth();
titletext.setWidth(screenWidth);
}
if (constant.getscreenresolution() >= 800 && constant.ScreenOrientation() == 1) {
titletext.setTextSize(TypedValue.COMPLEX_UNIT_PX, 30);
datetext.setTextSize(TypedValue.COMPLEX_UNIT_PX, 20);
}
titletext.setText(title[position].toString());
datetext.setText(date[position].toString());
return vi;
}
}
This is the CustomAdapter class.
In your adapter add:
public void setTitle(String[] title) {
this.title = title;
}
public void setDate(String[] date) {
this.date = date;
}
public void setImagepath(String[] imagepath) {
this.imagepath = imagepath;
}
When the more button is pressed call the three methods above with arrays containing 20 objects. Then call notifyDataSetChanged on your adapter.
Update:
This is working for me:
Activity:
public class HelpProjectActivity extends Activity {
private ArrayList<Item> items;
private boolean extend = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
createArray();
ListView lv = (ListView)findViewById(R.id.list);
lv.setAdapter(new HelpListAdapter());
}
private void createArray() {
items = new ArrayList<Item>();
for(int i = 0; i < 20; i++) {
Item item = new Item();
item.title = "Title " + i;
item.subtitle = "Subtitle " + i;
item.image = "default";
items.add(item);
}
}
public void morePressed(View v) {
extend = !extend;
Button b = (Button) findViewById(R.id.button);
b.setText(extend ? R.string.less_button : R.string.more_button);
ListView lv = (ListView)findViewById(R.id.list);
((BaseAdapter)lv.getAdapter()).notifyDataSetChanged();
}
private class HelpListAdapter extends BaseAdapter {
#Override
public int getCount() {
if (extend) {
return items.size();
}
return items.size()/2;
}
#Override
public Object getItem(int pos) {
return items.get(pos);
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
v = View.inflate(getApplicationContext(), R.layout.litst_item, null);
}
Item item = items.get(pos);
TextView titleText = (TextView) v.findViewById(R.id.list_item_title);
titleText.setText(item.title);
TextView subtitleText = (TextView) v.findViewById(R.id.list_item_subtitle);
subtitleText.setText(item.subtitle);
ImageView image = (ImageView) v.findViewById(R.id.list_image);
if (item.image.equalsIgnoreCase("default")) {
image.setImageResource(R.drawable.default_list_image);
} else {
// what ever
}
return v;
}
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="10dp"
android:onClick="morePressed"
android:text="#string/more_button" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="#+id/list_image"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="5dp"
android:layout_gravity="center_vertical"
android:contentDescription="#string/list_image" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:id="#+id/list_item_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold" />
<TextView
android:id="#+id/list_item_subtitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="italic" />
</LinearLayout>
</LinearLayout>
Item.java:
public class Item {
String image;
String title;
String subtitle;
}
adapter.notifyDataSetChanged(); try this

Categories

Resources