Pass a variable value from Base Adapter to activity - android

I have a set a variable in my Base Adapter class, now I want to get(pass) this variable in my related Activity. I am not getting how to do this.
Here is my code.
public class TourDescAdapter extends BaseAdapter {
private List<Descriptions> descriptList;
private LayoutInflater mInflater;
ViewHolder holder;
#SuppressWarnings("unused")
private OnClickListener clickListener;
Activity context;
//TourDescription tourDesc;
ArrayList<HashMap<String, Object>> obj = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> discountedTourDetails = null;
String price = null, prodId = null;
String promoTourname, tourName;
public TourDescAdapter(List<Descriptions> descriptList,
TourDescription activity) {
this.context = activity;
this.descriptList = descriptList;
mInflater = LayoutInflater.from(activity);
clickListener = (OnClickListener) activity;
}
#Override
public int getCount() {
return this.descriptList.size();
}
#Override
public Object getItem(int position) {
return this.descriptList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.tourlist, null);
/****
* Creates a ViewHolder and store references to the two children
* views we want to bind data to
****/
holder = new ViewHolder();
holder.rlayout = (RelativeLayout) convertView
.findViewById(R.id.tourlayout);
holder.title = (TextView) convertView
.findViewById(R.id.tourtitletext);
holder.desc = (TextView) convertView.findViewById(R.id.tourdes);
holder.amountButton = (Button) convertView
.findViewById(R.id.amtBtn);
holder.pinButton = (Button) convertView.findViewById(R.id.pinBtn);
holder.arrowButton = (Button)convertView.findViewById(R.id.arrowBtn);
holder.serialText = (EditText)convertView.findViewById(R.id.pinText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText((String) descriptList.get(position)
.getImageTitle());
holder.desc.setText((String) descriptList.get(position)
.getImageDescription());
((ImageView) holder.rlayout.getChildAt(0)).setImageBitmap(BitmapFactory
.decodeFile((RaconTours.PATH + RaconTours.city + File.separator
+ TourDescription.currentTour.getObjtourName()
+ File.separator + descriptList.get(position)
.getImagePath().split("/")[2]).replace(" ", "_")));
if (position == 0) {
SharedPreferences settings = context.getSharedPreferences("downloadDetails", 0);
String isTourDownloaded = settings.getString(TourDescription.currentTour.getObjtourName(), "");
if (isTourDownloaded.equals("true")) {
//if (!(TourDescription.downloadFile.exists())||TourDescription.downloadFile.exists() == false ) {
//if (TourDescription.currentTour.getIsTourDownloaded() == true) {
//holder.pinButton.setVisibility(View.INVISIBLE);
//holder.arrowButton.setVisibility(View.INVISIBLE);
//holder.serialText.setVisibility(View.INVISIBLE);
}
holder.amountButton.setVisibility(View.VISIBLE);
holder.amountButton.setText("Start");
} else {
File promoPlistPath = new File(RaconTours.PATH + "promocode.txt");
checkPromoCode(promoPlistPath);
if (discountedTourDetails != null) {
tourName = (String) discountedTourDetails.get("promoTour");
price = (String) discountedTourDetails.get("discountPrice");
prodId = (String) discountedTourDetails.get("disProId");
holder.amountButton.setVisibility(View.VISIBLE);
// Setting the background color
holder.title
.setBackgroundColor(Color.parseColor("#993333"));
// Setting the Title color
holder.title.setTextColor(Color.WHITE);
// Centering the title
holder.title.setGravity(Gravity.LEFT);
// setting the city
((TextView) holder.rlayout.getChildAt(1))
.setText(RaconTours.city);
((TextView) holder.rlayout.getChildAt(1))
.setVisibility(View.VISIBLE);
// setting the Tour Amount
holder.amountButton.setText("$" +price);
//promoPlistPath.delete();
} else {
// Enabling the two buttons
holder.amountButton.setVisibility(View.VISIBLE);
// Setting the background color
holder.title
.setBackgroundColor(Color.parseColor("#993333"));
// Setting the Title color
holder.title.setTextColor(Color.WHITE);
// Centering the title
holder.title.setGravity(Gravity.LEFT);
// setting the city
((TextView) holder.rlayout.getChildAt(1))
.setText(RaconTours.city);
((TextView) holder.rlayout.getChildAt(1))
.setVisibility(View.VISIBLE);
// setting the Tour Amount
holder.amountButton.setText(TourDescription.currentTour
.getObjPrice());
}
}
} else {
holder.amountButton.setVisibility(View.INVISIBLE);
holder.pinButton.setVisibility(View.INVISIBLE);
holder.arrowButton.setVisibility(View.INVISIBLE);
holder.serialText.setVisibility(View.INVISIBLE);
holder.title.setBackgroundColor(Color.WHITE);
holder.title.setTextColor(Color.BLACK);
holder.title.setGravity(Gravity.CENTER_HORIZONTAL);
((TextView) holder.rlayout.getChildAt(1))
.setVisibility(View.INVISIBLE);
}
return convertView;
}
#SuppressWarnings("unchecked")
private void checkPromoCode(File promoPlistPath) {
if (promoPlistPath.exists()) {
try {
ObjectInputStream inStream = new ObjectInputStream(
new FileInputStream(promoPlistPath));
obj = (ArrayList<HashMap<String, Object>>) inStream
.readObject();
for (HashMap<String, Object> tmpObj : obj) {
promoTourname = (String) tmpObj.get("promoTour");
if (promoTourname.equals(TourDescription.currentTour.getObjtourName())) {
discountedTourDetails = tmpObj;
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ViewHolder {
Button pinButton;
Button amountButton;
RelativeLayout rlayout;
TextView title;
TextView desc;
Button arrowButton;
EditText serialText;
}
}
Here
prodId = (String) discountedTourDetails.get("disProId");
I want to pass prodId to related activity.
Note: Base Adapter is called from the activity
adapter = new TourDescAdapter(currentTour.getListOfDescriptions(), this);
setListAdapter(adapter);
Any one can tell me how to do this?

Couldn't you just use String iGotTheString = adapter.prodId?

Related

Duplicate checkbox when checked and row value disappears

I have an application in which there is a listview that displays values and when a row is pressed, the third value of the row will display a value.
Example is: third value is 30 and when it's pressed, it should be
divided by 6, so the answer should be 5.
But when I scroll and press a row in listview example: I pressed row1, there will be a duplicate checked row in row10 and the value of the third row returns to it's old value (30) for example.
Is there any way to keep the checkbox from duplicating and the value of the row preserved when clicked?
Here's my code for the adapter:
public class MyAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> mData;
public MyAdapter(ArrayList<HashMap<String, String>> mData2) {
this.mData = mData2;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int i) {
return this.mData.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
View mView = convertView;
String betid = mData.get(i).get("betid");
ViewHolder holder ;
if (mView == null) {
Context context = viewGroup.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
mView = inflater.inflate(R.layout.row_layout, null,false);
holder = new ViewHolder();
holder.tx_number = (TextView) mView.findViewById(R.id.tx_number);
holder.tx_amount = (TextView) mView.findViewById(R.id.tx_amount);
holder.tx_counter = (TextView) mView.findViewById(R.id.tx_counter);
mView.setTag(holder);
} else {
holder = (ViewHolder) mView.getTag();
}
if (betid != null) {
String betnumber = mData.get(i).get("betnumber");
String amountTarget = mData.get(i).get("amountTarget");
String amountRamble = mData.get(i).get("amountRamble");
holder.tx_number.setText(betnumber);
holder.tx_amount.setText(amountTarget);
holder.tx_counter.setText(amountRamble);
}
return mView;
}
private class ViewHolder {
TextView tx_number;
TextView tx_amount;
TextView tx_counter;
}
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckBox checkBox = (CheckBox)view.findViewById(R.id.checkmark);
TextView tv3 = (TextView)view.findViewById(R.id.tx_counter);
EditText editText = (EditText)findViewById(R.id.editText3);
String yy = editText.getText().toString().trim();
String shitts = listView.getItemAtPosition(position).toString();
ArrayList<String> list = new ArrayList<String>();
try {
String[] a = shitts.split(", ");
String[] b = a[1].split("=");
String[] sep = a[0].split("=");
String betnumber = sep[1];
String betamount= b[1];
checkBox.setChecked(!checkBox.isChecked());
if(checkBox.isChecked()){
//sort number
final String sorted = betnumber.chars().sorted().mapToObj(c -> Character.valueOf((char)c).toString()).collect(Collectors.joining());
//check if double digit
Boolean checker = doubleChecker(sorted);
if (checker == true){
Toast.makeText(getApplicationContext(),"DOUBLE DIGIT", LENGTH_SHORT).show();
int answer = Integer.parseInt(betamount) / 3;
tv3.setText(String.valueOf(answer));
}else{
Toast.makeText(getApplicationContext(),"NOT DOUBLE DIGIT", LENGTH_SHORT).show();
int answer;
if(yy.equals("")){
answer = Integer.parseInt(betamount) / 6;
tv3.setText(String.valueOf(answer));
}else{
answer = (Integer.parseInt(betamount) - Integer.parseInt(yy)) / 6;
tv3.setText(String.valueOf(answer));
}
}
//TODO save to array to send
}else{
//TODO mistake RETURN tv3 to old value // remove from array
tv3.setText("0");
}
}catch (Exception e){
}
}
});
I think the issue is here
if (betid != null) {
String betnumber = mData.get(i).get("betnumber");
String amountTarget = mData.get(i).get("amountTarget");
String amountRamble = mData.get(i).get("amountRamble");
holder.tx_number.setText(betnumber);
holder.tx_amount.setText(amountTarget);
holder.tx_counter.setText(amountRamble);
}
You are missing an elsestatement to set other values when betid is null.
If betid is null, other rows can hold values from previous rows.
...
holder.tx_amount.setText(amountTarget);
holder.tx_counter.setText(amountRamble);
} else {
// assuming that if betid is null, then, TextViews should be cleared
// or replace with your own values
holder.tx_number.setText("");
holder.tx_amount.setText("");
holder.tx_counter.setText("");
}

Textview Values of counter changes after scrolling Listview?

The Problem is :
I am having list of products in listview and a textview following incremenat/decrement buttons. If I perform increment and decrement on first item of the listview it changes to the other listview positions also while performing scrolling on it.
what all I have tried so far:
TextView's value changed while scrolling listview
TextView in listview rows showing repeated values on scroll in Android?
Duplicated entries in ListView
Android list items are changing when scrolling
I was not able to solve my problem with none of these.
I am stuck with this problem from last three days. Any one please help me with it I will be really grateful to you. Thanks
This is my code of Adapter Class:
class SubProductsListAdapter extends BaseAdapter{
private Context context;
// private ArrayList<String> list;
DBHelper dbHelper;
ArrayList<AddedProducts> arrayList;
boolean exists;
String addedQuant;
String quant;
String discounted;
String finalPrice;
URI uri;
private List<SubProductData> subProductDataList = null;
public SubProductsListAdapter(Context context, ArrayList<SubProductData> list){
this.context = context;
this.subProductDataList = list;
}
#Override
public int getCount() {
return subProductDataList.size();
}
#Override
public Object getItem(int position) {
return subProductDataList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
dbHelper = new DBHelper(context);
convertView = LayoutInflater.from(context).inflate(R.layout.sub_fragment_list_items,null,false);
holder.ItemImage = (ImageView) convertView.findViewById(R.id.item_image);
holder.txtItemName = (TextView) convertView.findViewById(R.id.item_name);
holder.disCountedPrice = (TextView) convertView.findViewById(R.id.discounted_price);
holder.finalPrice = (TextView) convertView.findViewById(R.id.final_price);
holder.quantity = (TextView) convertView.findViewById(R.id.quantity);
holder.addedQuantity = (TextView) convertView.findViewById(R.id.item_quantity);
holder.addItem = (Button) convertView.findViewById(R.id.add);
holder.removeItem = (Button) convertView.findViewById(R.id.remove);
holder.v = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
/** set item name from the arrayList */
holder.txtItemName.setText(subProductDataList.get(position).getProductName());
final String url = subProductDataList.get(position).getProductImage();
String parentUrl = "http://test//";
String finalUrl = parentUrl+url;
try {
uri = new URI(finalUrl.replaceAll(" ", "%20"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
Picasso.with(context)
.load(String.valueOf(uri)) // loaded image
.placeholder(R.drawable.categorydefault) // thumbnail image
.error(R.drawable.categorydefault) // if unable to load image or fetch image from server
.into(holder.ItemImage);
String productPrice = subProductDataList.get(position).getProductPrice();
double myProductFianlPrice = Double.parseDouble(productPrice);
myProductFianlPrice =Double.parseDouble(new DecimalFormat("##.####").format(myProductFianlPrice));
holder.finalPrice.setText(String.valueOf(myProductFianlPrice));
/** Strike discounted price */
holder.disCountedPrice.setPaintFlags(holder.disCountedPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
addedQuant = holder.addedQuantity.getText().toString();
discounted = holder.disCountedPrice.getText().toString();
finalPrice = holder.finalPrice.getText().toString();
/** Setting quantitiy of products from databse to textview */
final String itemName =subProductDataList.get(position).getProductName();
arrayList = dbHelper.getAllProducts();
exists = false;
for (AddedProducts hmap : arrayList)
{
if (hmap.getTitle().equals(itemName))
{
exists = true;
break;
}}
if (exists){
Cursor id = dbHelper.getQuantityOfProduct(itemName);
quant = null;
id.moveToFirst();
if (id.moveToFirst()) {
quant = id.getString(id.getColumnIndex("qty"));
Log.e(quant,"this is my quantity");
}
holder.addedQuantity.setText(quant);
}
/** Add items to the cart */
holder.addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String present_value_string = holder.addedQuantity.getText().toString();
int present_value_int = Integer.parseInt(present_value_string);
present_value_int++;
holder.addedQuantity.setText(String.valueOf(present_value_int));
addedQuant = holder.addedQuantity.getText().toString();
float tot = Float.parseFloat(finalPrice) * present_value_int;
int dis = Integer.parseInt(discounted) * present_value_int;
String itemName =subProductDataList.get(position).getProductName();
String proIds = subProductDataList.get(position).getProductId();
String proModel = subProductDataList.get(position).getProductModel();
Log.e(proModel,"productModel");
final String url = subProductDataList.get(position).getProductImage();
String parentUrl = "http://falconet.co.in/jubstore/image/";
String finalUrl = parentUrl+url;
try {
uri = new URI(finalUrl.replaceAll(" ", "%20"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
boolean test = dbHelper.CheckIsDataAlreadyInDBorNot(itemName);
if (!test)
{
dbHelper.insertProduct(context,itemName,proIds,finalPrice, discounted,present_value_int,proModel,String.valueOf(uri),tot,dis);
}
else
{
//item already exists
Cursor id = dbHelper.getQuantityData(itemName);
String myId = null;
id.moveToFirst();
if (id.moveToFirst()) {
myId = id.getString(id.getColumnIndex("id"));
Log.e(myId,"this is my id");
}
float tots = Float.parseFloat(finalPrice) * present_value_int;
dbHelper.updateProduct(Integer.parseInt(myId),present_value_int,tots);
Log.e(String.valueOf(tots),"updatedtotalcheck");
}
}
});
/** remove items from the cart */
holder.removeItem.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View v) {
String present_value_string = holder.addedQuantity.getText().toString();
int present_value_int = Integer.parseInt(present_value_string);
if (present_value_int > 0) {
present_value_int--;
holder.addedQuantity.setText(String.valueOf(present_value_int));
holder.v.vibrate(300);
String itemName =subProductDataList.get(position).getProductName();
boolean test = dbHelper.CheckIsDataAlreadyInDBorNot(itemName);
if (test)
{
//item already exists
Cursor id = dbHelper.getQuantityData(itemName);
String myId = null;
id.moveToFirst();
if (id.moveToFirst()) {
myId = id.getString(id.getColumnIndex("id"));
Log.e(myId,"this is my id");
}
float tots = Float.parseFloat(finalPrice) * Integer.parseInt(addedQuant);
dbHelper.updateProduct(Integer.parseInt(myId),present_value_int,tots);
}
}
/** if textview quantity is equal to zero remove product from cart */
if (holder.addedQuantity.getText().toString() == "0"){
Cursor id = dbHelper.getQuantityData(itemName);
String myId = null;
id.moveToFirst();
if (id.moveToFirst()) {
myId = id.getString(id.getColumnIndex("id"));
SubProductsListAdapter.this.notifyDataSetChanged();
}
if (myId != null) {
dbHelper.deleteProduct(Integer.valueOf(myId));
}
}
}});
return convertView;
}
class ViewHolder{
Button removeItem;
Button addItem;
TextView disCountedPrice,finalPrice,quantity,addedQuantity;
ImageView ItemImage;
TextView txtItemName;
Vibrator v;
}
}
Add one variable in holder class that store value of quantity and set last quantity in it.
class ViewHolder{
int quanity
}
store that quantity
holder.quantity = your quantity
now you can get last quantity value from holder and place it to your textview.
/** set item name from the arrayList */
holder.txtItemName.setText(subProductDataList.get(position).getProductName());
holder.txtQuanity.setText(holder.quantity)
Hope this will help.

Duplicate data in ListView?

I have a ListView that fill from Sqlite . But when I fill the ListView I see Duplicate Data.
My Struct.class :
public class Struct{
public String IdS;
public String NameS;
public String Group;
}
My Activity.class :
ArrayAdapter adapter = new AdapterPSK(MPSK, activity, width, context);
ListView lstPa = (ListView) findViewById(R.id.lstPasokhgoo);
lstPa.setAdapter(adapter);
Struct stp = new Struct();
cursor_Sharee = sql.rawQuery("SELECT ID_P,Name_P,Group_P FROM ChatPasokhgo_tbl where Group_P = '" + "LOL" + "'", null);
try {
if (cursor_Sharee != null) {
if (cursor_Sharee.moveToFirst()) {
do {
stp.IdS = cursor_Sharee.getString(cursor_Sharee.getColumnIndex("ID_P"));
stp.NameS = cursor_Sharee.getString(cursor_Sharee.getColumnIndex("Name_P"));
stp.Group = cursor_Sharee.getString(cursor_Sharee.getColumnIndex("Group_P"));
MPSK.add(stp);
} while (cursor_Sharee.moveToNext());
}
}
} catch (Exception e) {
// TODO: handle exception
}finally{
cursor_Sharee.close();
}
adapter.notifyDataSetChanged();
MPSK is:
public ArrayList<Struct> MPSK = new ArrayList<Struct>();
My AdapterPSK.class :
public class AdapterPSK extends ArrayAdapter<Struct> {
static boolean enable = true;
static Activity activity;
static int widths;
public AdapterPSK(ArrayList<Struct> array,Activity act,int WIDTH,Context context) {
super(context, R.layout.chat_page, array);
activity = act;
widths = WIDTH;
}
public ViewHolder(View view)
{
txtName = (TextView) view.findViewById(R.id.txtname);
layoutRoot = (ViewGroup) view.findViewById(R.id.layoutRoot);
txtname = (TextView) view.findViewById(R.id.txtname);
}
public void fill(ArrayAdapter<Struct> arrayAdapter,final Struct item , int position)
{
MarginLayoutParams txtN = (MarginLayoutParams) txtname.getLayoutParams();
txtN.rightMargin = MarginRight;
txtname.setTextSize(TextSize);
if (item.NameS != null) {
txtName.setText(item.NameS);
}else if(item.NameE != null){
txtName.setText(item.NameE);
}
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Struct item = getItem(position);
if(convertView == null)
{
convertView = G.inflater.inflate(R.layout.adapter_pasokhgoo,parent,false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
holder.fill(this, item, position);
return convertView;
}
Notice : ListView show me last row of sqlite . But when I get Log see all of fetching data .My Query is true . My bug is from MPSK .
Your Struct stp = new Struct(); should be in :
do {
Struct stp = new Struct();
.....
......
} while (cursor_Sharee.moveToNext());
;)
Clear MPSK after retrieving cursor.. as
cursor_Sharee = sql.rawQuery("SELECT ID_P,Name_P,Group_P FROM ChatPasokhgo_tbl where Group_P = '" + "LOL" + "'", null);
MPSK.clear();
try
{
.....
Change this
if (cursor_Sharee != null) {
if (cursor_Sharee.moveToFirst()) {
do {
stp.IdS = cursor_Sharee.getString(cursor_Sharee.getColumnIndex("ID_P"));
stp.NameS = cursor_Sharee.getString(cursor_Sharee.getColumnIndex("Name_P"));
stp.Group = cursor_Sharee.getString(cursor_Sharee.getColumnIndex("Group_P"));
MPSK.add(stp);
} while (cursor_Sharee.moveToNext());
}
To
if (cursor_Sharee != null)
{
while(cursor_Sharee.moveToNext())
{
stp.IdS = cursor_Sharee.getString(cursor_Sharee.getColumnIndex("ID_P"));
stp.NameS = cursor_Sharee.getString(cursor_Sharee.getColumnIndex("Name_P"));
stp.Group = cursor_Sharee.getString(cursor_Sharee.getColumnIndex("Group_P"));
MPSK.add(stp);
}
}

Wrong Loading Data when using Viewholder in BaseAdapter Android

I am using BaseAdapter for loading the data in gridview. When the data is loaded to the gridview, and the user tries to scroll, I used to get incorrect data. In order to fix that I used ViewHolder. That actually fixed the issue, however, when the users click any of the data in the gridview, instead of getting the correct id from the item, all the items are returning a similar id number.
public class ProductAdapter extends BaseAdapter {
// Context context;
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
ViewHolder holder;
int layoutResourceId;
Event event;
EventDBAdapter eventDb;
int id;
PersianCalendar sc;
String Today;
SharedPreferences Prefrences_test;
String date, userid;
String newText = "";
String test;
int status;
MoodsDBAdapter moodsDBAdapter;
Mood mood;
ArrayList<MoodsNote> arrayMoodsNote;
MoodsNoteDBAdapter moodsNoteDBAdapter;
MoodsNote moodsNote;
public ProductAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
// this.context = context;
eventDb = new EventDBAdapter(activity);
event = new Event();
moodsDBAdapter = new MoodsDBAdapter(activity);
mood = new Mood();
moodsNoteDBAdapter = new MoodsNoteDBAdapter(activity);
data = d;
// this.layoutResourceId = layoutResourceId;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Prefrences_test = activity.getSharedPreferences("temp", 0);
date = Prefrences_test.getString("date", "");
userid = Prefrences_test.getString("userid", "");
sc = new PersianCalendar();
Today = date;
eventDb = new EventDBAdapter(activity.getApplicationContext());
event = eventDb.getName(Today);
try {
arrayMoodsNote = moodsNoteDBAdapter.getItems(event.getID());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
holder = null;
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
if (vi == null) {
vi = inflater.inflate(R.layout.note_mood_list_item, null);
holder = new ViewHolder();
holder.title = (TextView) vi.findViewById(R.id.mood_text);
holder.txt_id = (TextView) vi.findViewById(R.id.txt_id_mood);
holder.thumb_image = (ImageView) vi.findViewById(R.id.mood_img);
holder.linear = (LinearLayout) vi.findViewById(R.id.mood_layout);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
holder.linear.setBackgroundResource(R.drawable.bg_mood);
//holder.txt_id.setText("");
String titles = song.get("name");
holder.title.setText(titles);
Resources res = activity.getResources();
int resourceId = res.getIdentifier(song.get("icon"), "drawable",
activity.getPackageName());
holder.thumb_image.setBackgroundResource(resourceId);
holder.txt_id.setText(song.get("id"));
try {
for (MoodsNote m : arrayMoodsNote) {
int moodd = m.getMOOD();
if (Integer.parseInt(holder.txt_id.getText().toString()) == moodd)
{
holder.linear.setBackgroundResource(R.drawable.bg_mood_on);
}
}
} catch (Exception e) {
// TODO: handle exception
}
holder.thumb_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(activity, holder.txt_id.getText().toString(), 0).show();
status = 1;
event = new Event();
int tedad = eventDb.getDate(date);
if (tedad <= 0) {
event = new Event(userid, date);
eventDb.insert(event);
}
event = eventDb.getName(date);
moodsNote = new MoodsNote();
id = 0;
id = Integer.parseInt(holder.txt_id.getText().toString());
// id = rowItem.getID();
int tedadd = moodsNoteDBAdapter.getLastItemID(id);
if (tedadd <= 0)
{
moodsNote.setMOOD(id);
moodsNote.setEVENT(event.getID());
moodsNoteDBAdapter.insert(moodsNote);
holder.linear.setBackgroundResource(R.drawable.bg_mood_on);
}
else {
moodsNoteDBAdapter.deleteId(id);
holder.linear.setBackgroundResource(R.drawable.bg_mood);
}
}
});
return vi;
}
static class ViewHolder {
ImageView thumb_image;
TextView txt_id, title;
LinearLayout linear;
}

How can I change the background to a shape I already made, according to a string (I wish to change the status Bckgrnd)

MAINSCREEN
imports;
public class HomeFragment extends Fragment {
// Declare Variables
ListView list;
TextView text;
ListViewAdapter adapter;
EditText editsearch;
String[] title;
String[] date;
String[] status;
ArrayList<ListCourse> arraylist = new ArrayList<ListCourse>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
date = new String[] { "11/01/2011", "10/05/2006", "12/07/2002", "05/04/2011", "01/08/2012",
"09/12/2017", "22/06/2024", "31/01/2000", "10/10/2156", "10/02/2006" };
title = new String[] { "Programação", "Matemática", "Logística",
"Mobile", "Sistemas Operativos", "iOS", "Android", "Windows",
"Hardware", "Formação" };
status = new String[] { " ongoing ", " ongoing ",
" ongoing ", " standby ", " ongoing ", " ongoing ",
" ongoing ", " ongoing ", " finished ", " ongoing " };
// Locate the ListView in listview_main.xml
list = (ListView) rootView.findViewById(R.id.listview);
for (int i = 0; i < title.length; i++)
{
ListCourse wp = new ListCourse(date[i], title[i],
status[i]);
// Binds all strings into an array
arraylist.add(wp);
}
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(getActivity(), arraylist);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
return rootView;
}
}
Do I need to paste my adapter too? The id of the TextView in the .xml layout is status.
My idea is to change the background to yellow if standy, red to finish and green to ongoing. I have a shape_"color".xml for each one.
ADAPTER
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<ListCourse> coursepopulatelist = null;
private ArrayList<ListCourse> arraylist;
public ListViewAdapter(Context context, List<ListCourse> coursepopulatelist) {
mContext = context;
this.coursepopulatelist = coursepopulatelist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<ListCourse>();
this.arraylist.addAll(coursepopulatelist);
}
public class ViewHolder {
TextView title;
TextView date;
TextView status;
}
#Override
public int getCount() {
return coursepopulatelist.size();
}
#Override
public ListCourse getItem(int position) {
return coursepopulatelist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.title = (TextView) view.findViewById(R.id.title);
holder.date = (TextView) view.findViewById(R.id.date);
holder.status = (TextView) view.findViewById(R.id.status);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.title.setText(coursepopulatelist.get(position).getTitle());
holder.date.setText(coursepopulatelist.get(position).getDate());
holder.status.setText(coursepopulatelist.get(position).getStatus());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, SingleItemView.class);
// Pass all data rank
intent.putExtra("title",(coursepopulatelist.get(position).getTitle()));
// Pass all data country
intent.putExtra("date",(coursepopulatelist.get(position).getDate()));
// Pass all data population
intent.putExtra("status",(coursepopulatelist.get(position).getStatus()));
// Pass all data flag
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
coursepopulatelist.clear();
if (charText.length() == 0) {
coursepopulatelist.addAll(arraylist);
}
else
{
for (ListCourse wp : arraylist)
{
if (wp.getDate().toLowerCase(Locale.getDefault()).contains(charText))
{
coursepopulatelist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
And this is my shape.xml, example red.
shape
xmlns:android="http://schemas.android.com/apk/res/android" android:padding="10dp" android:shape="rectangle"
<solid android:color="#c50504" />
<stroke
android:width="10dip"
android:color="#c50504" />
<corners android:radius="10dp" />
Set the same shape to your list item just change the color inside getView wrt status.
try changing your getView to:
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.title = (TextView) view.findViewById(R.id.title);
holder.date = (TextView) view.findViewById(R.id.date);
holder.status = (TextView) view.findViewById(R.id.status);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.title.setText(coursepopulatelist.get(position).getTitle());
holder.date.setText(coursepopulatelist.get(position).getDate());
holder.status.setText(coursepopulatelist.get(position).getStatus());
//<<----------See the code below-------------------
int color = Color.RED;
String s=coursepopulatelist.get(position).getStatus();
if (s.trim().equals("ongoing")) {
color = Color.GREEN;
} else if (s.trim().equals("standby")) {
color = Color.YELLOW;
} else if (s.trim().equals("finished")) {
color = Color.RED;
}
GradientDrawable gd = (GradientDrawable) holder.status.getBackground();
gd.setColor(color);
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, SingleItemView.class);
// Pass all data rank
intent.putExtra("title",(coursepopulatelist.get(position).getTitle()));
// Pass all data country
intent.putExtra("date",(coursepopulatelist.get(position).getDate()));
// Pass all data population
intent.putExtra("status",(coursepopulatelist.get(position).getStatus()));
// Pass all data flag
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
There's a few ways to do this, depending on how much memory you have available, etc. It seems like all you really want to do is to change the background color. Given that, I would do the following:
Create a HashMap that contains the colors you want indexed by the strings.
It seems you want to change the background of the individual item based on the string that it contains. In that case, you'll want to check the value of each string inside the view, and set the color based off of what it ends up with in the HashMap.
For instance.
static HashMap<String, Integer> colorMap=null;
//This should be run from the constructor
public populateMap () {
if (colorMap==null) {
colorMap=new HashMap<String,Integer>();
colorMap.add("finish",0xffff0000);
}
}
public View getView(int position, View convertView, ViewGroup parent)
String text; //Put in your text value here
TextView tv; // This is your view, I'm assuming a TextView
tv.setText(text);
if (colorMap.containsKey(text)) {
tv.setBackgroundColor(colorMap.get(text));
}
}

Categories

Resources