How to Set Value for Each Item Button Increase and Decrease Click and Set That Value in Text View

to increase and decrease value inside textview on button click on particular position

As far i understood your code logic is not correct.first you get which item you have selected according to that maintain your quantity[] array if you have selected book from list update your count on quantity [1,0,0] and if again you select book so fist get value of book quantity count increment on it by 1 and update quantity [2,0,0].

set text in textview of a list item on click of button

Follow initial query with answer by user370305.

Please help. Also i need help in how to show the items whose textview contains positive number in next activity or fragment.

Create a data structure, I am taking a HashMap , where key is String.valueOf(position) and Value is count int.

You know the keys since it will be from position "0" to listitem.length. Using the key you can get the count values and check for positive ones.

Why Hashmap: because everytime you change count the new value will be overriden. (Only one unique key is maintained in hashmap).

(position = 0, count = 0) --> - clicked on 0th row--> (position 0 , count = -1) will be overriden on key = 0 cell.

Complete code (with number increment fix and having set of positive value in DataStructure):

public class HomePage extends Fragment { 

String[] listitems;
int[] images = { R.drawable.cadburysilk, R.drawable.cadburys_dairymilk,
R.drawable.perk, R.drawable.kitkat,
R.drawable.nestlemunchchocolate, R.drawable.cadbury_bournville_bar,
R.drawable.snickers };
ListView list;
DBAdapter dbadapter;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub

View rootview = inflater.inflate(R.layout.activity_home_page,
container, false);
View view = View.inflate(getActivity(), R.layout.headerview, null);

Resources res = getResources();
listitems = res.getStringArray(R.array.items);
list = (ListView) rootview.findViewById(R.id.itemslist);
list.addHeaderView(view);
AdapterClass adapterClass = new AdapterClass(this.getActivity(),
listitems, images);
list.setAdapter(adapterClass);
return rootview;

//You can use adapterClass.getPositiveNumber(); to retrieve all positive rows and the values!
//Unique key will be String : 1,2,3....listitems.length.

}

}

class AdapterClass extends ArrayAdapter<String> {
Context context;
int[] images;
String[] names;
Button add, sub;
ViewHolder holder; // Since will be accessed inside onclick

HashMap<String,Integers> positiveNumbers = new HashMap<String,Integers>;
Integer count=0;

static class ViewHolder {
public TextView textView;
public ImageView imageView;
public TextView number;
public String uniqueKey;

}

public AdapterClass(Context c, String[] items, int imgs[]) {
// TODO Auto-generated constructor stub
super(c, R.layout.rowlayout, R.id.quantity, items);
this.context = c;
this.images = imgs;
this.names = items;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
// reuse views

if (row == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.rowlayout, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.imageView = (ImageView) row.findViewById(R.id.img);
viewHolder.textView = (TextView) row.findViewById(R.id.textView1);
viewHolder.number = (TextView)row.findViewById(R.id.quantity);
viewHolder.uniqueKey = String.valueOf(position);
add = (Button) row.findViewById(R.id.button1);
add.setTag(position);
sub = (Button) row.findViewById(R.id.button2);
sub.setTag(position);
row.setTag(viewHolder);

}
holder = (ViewHolder) row.getTag(); //keeping one global memory
holder.imageView.setImageResource(images[position]);
holder.textView.setText(names[position]);
add.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
count=count+1;
holder.number.setText(count.toString());
positiveNumbers.put(holder.uniqueKey,count); //Key -> String.valueOf(position) and Value -> int count
}
});

sub.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
count=count-1;
holder.number.setText(count.toString());
positiveNumbers.put(holder.uniqueKey,count); //Key -> String.valueOf(position) and Value -> int count
}
});

return row;
}


public Map<String,Integer> getPositiveNumbers()
{
return positiveNumbers;
}


}

p.s. I have typed in editor, there might be some compile time error. Also you can store objects of each row against the key so that when you get the positive count, you can get any other reference like the image, which I am guessing you would need to show later!

How to Increase or decrease value of edittext in listview's each row?

You cant access use local variables in this case, By the time the onClickListener is called the variables would have gone out of scope.

So instead you can set the ViewHolder as a tag for the button too, then you can access that in your onClick.

holder.btnEdit.setTag(holder);
holder.btnEdit.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
ViewHolder tagHolder = (ViewHolder) v.getTag();

// TODO Auto-generated method stub
Log.i("Edit Button Clicked", "**********");
/* Toast.makeText(context, "Edit button Clicked",
Toast.LENGTH_LONG).show();*/

int mValue = Integer.parseInt(tagHolder.textAddress.getText().toString());
mValue--;
if(mValue < 0)
{
System.out.println("not valid");
}
else
{
tagHolder.textAddress.setText( ""+mValue );
}
}
});

I hope it helps!

RecyclerView increase(+) and decrease(-) buttons not working properly for each Item

Your problem is declaring only one variable for all views, You should take value from TextView then modify and then set it back to TextView
Try this code

 holder.btnIncrease.setOnClickListener (new View.OnClickListener () {
@Override
public void onClick(View view) {
int val = 0;
try{

val = Integer.parseInt(holder.number.getText().toString());
}catch(Exception e) {
val = 0;
}
holder.number.setText (String.valueOf (val++));

}
});
holder.btnDecrease.setOnClickListener (new View.OnClickListener () {
@Override
public void onClick(View view) {


int val = 0;
try{

val = Integer.parseInt(holder.number.getText().toString());
}catch(Exception e) {
val = 0;
}
if(val>0) val--;
holder.number.setText (String.valueOf (val));

}
});

How to increment and decrement value of textview in listview?

Do you want to decrease or increase of each textView's value? If yes

            for(int position=0;position<mThumbIds.length;position++){

counter = Integer.parseInt(tv1.getText());
counter-=250;
stringVal = Integer.toString(counter);
tv1.setText(stringVal);
}

How to increase or decrease textview number through button in android

Replace for Code with this:

public class SubMenu extends AppCompatActivity {

JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "id";
static String COUNTRY = "name";

static String FLAG = "image";
Integer i = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);


setContentView(R.layout.activity_sub_menu);

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

String SelectedId = getIntent().getStringExtra("id");


getSupportActionBar().setDisplayHomeAsUpEnabled(true);


// Get the view from listview_main.xml

// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}

// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> implements AdapterView.OnItemClickListener {

// @Override
// protected void onPreExecute() {
// super.onPreExecute();
// Create a progressdialog
// mProgressDialog = new ProgressDialog(SubMenu.this);
// Set progressdialog title
// mProgressDialog.setTitle("Categories of Main categories.....");
// Set progressdialog message
// mProgressDialog.setMessage("Loading...");
// mProgressDialog.setIndeterminate(false);
// Show progressdialog
// mProgressDialog.show();
// }

@Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonarray = JsonFunctions
.getJSONfromURL("http://cloud.......com/broccoli/menu_typeitem.php?id=" + getIntent().getStringExtra("id"));
try {
// Locate the array name in JSON
// jsonarray = jsonobject.getJSONArray("main_menu_items");


for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();

jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
// map.put("id", jsonobject.getString("id"));
map.put("name", jsonobject.getString("name"));

map.put("image", jsonobject.getString("image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.list1);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(SubMenu.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
listview.setOnItemClickListener(this);
// Close the progressdialog
// mProgressDialog.dismiss();
}


@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long rowId) {


final AlertDialog customDialog = new AlertDialog.Builder(SubMenu.this).create();
final LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.popup
, null);
customDialog.setView(dialogView);
// set the custom customDialogimation components - text, image and button
final TextView tvDistance = (TextView) dialogView.findViewById(R.id.h2);

final Button ok = (Button) dialogView.findViewById(R.id.ok);
ok.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

customDialog.dismiss();


}
});


final Button cncl = (Button) dialogView.findViewById(R.id.canc);
cncl.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

customDialog.dismiss();


}
});


Button _decrease = (Button) dialogView.findViewById(R.id.incr);
Button _increase = (Button) dialogView.findViewById(R.id.decr);
final TextView _value = (TextView) dialogView.findViewById(R.id.value);
i = Integer.parseInt(_value.getText().toString());


_decrease.setOnClickListener(new View.OnClickListener() {


public void onClick(View v) {
String _stringVal;
Log.d("src", "Decreasing value...");
if (i > 0) {
i = i - 1;
_stringVal = String.valueOf(i);
_value.setText(_stringVal);
} else {
Log.d("src", "Value can't be less than 0");
}

}
});

_increase.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
String _stringVal;

Log.d("src", "Increasing value...");
i = i + 1;
_stringVal = String.valueOf(i);
_value.setText(_stringVal);
}
});
customDialog.show();
}


}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}


Related Topics



Leave a reply



Submit