How to find which dynamic button is clicked in android - android

i have created dynamic button in activity on button click. When i created more than on button in activity,onclick works for the most recent button as i assigned id to every button. how can i identify which dynamic button is pressed other than most recent button.
Here is the snippet of my code
public void dynamicButton()
{
// int x=0;
preferences = PreferenceManager.getDefaultSharedPreferences(TimeStudy.this);
value = preferences.getInt("value", 0);
//myButton = new Button(this);
// if (value > x)
if ( i <= value) {
myButton= new Button(this);
myButton.setId(value);
BtnId.add(value);
myButton.setTag(value);
LinearLayout ll = (LinearLayout) findViewById(R.id.dynamiclayout);
ll.setOrientation(LinearLayout.VERTICAL);
ll.setPadding(10, 300, 10, 10);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
myButton.setLayoutParams(lp);
btnid= myButton.getId();
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (btnid) {
case 1:case 2:case 3:case
Intent intent = new Intent(TimeStudy.this, CollectSample.class);
startActivity(intent);
break;
}
}
});
ll.addView(myButton, lp);
i++;
}
switch (btnid) {
case 1:case 2:case 3:
SharedPreferences average = getSharedPreferences("avg", 0);
String avgbtn = average.getString("btnavg", "");
settings = getSharedPreferences("dynamicbtname", 0);
btnname = settings.getString("btnname", "");
ar.add(btnname);
String styledText = "<font color='#008000'>" + btnname + "</font>" + "&nbsp" + "&nbsp" + "&nbsp"
+ "<small>"
+ avgbtn + "</font>"
+ "<small>";
myButton.setText(Html.fromHtml(styledText));
myButton.setGravity(Gravity.CENTER | Gravity.LEFT);
break;
}
i want result like this even if after creation of all three button and 1 button is clicked no shows on first button.
enter image description here
i get this if i pressed 1 button after creation of 2 or third button data returns to most recent button.
enter image description here
any help appriciated thanks in advance.

THere's two ways.
1)Check by comparing it to the view variable passed in
2)Use an OnClickListener implementation that knows which one it is (by using different classes, or using one class with a parameter in it).

Related

How to save the updated value of an array back to the firestore database?

for (QueryDocumentSnapshot snapshot : Objects.requireNonNull(task.getResult())) {
String value1 = snapshot.getString("QuestionName");
q_tv1.setText("Question: "+value1);
ArrayList<String> description = (ArrayList<String>) snapshot.get("Description");
Log.d(Tag,"output for des: "+description);
List<String> noOfOptions = (List<String>) snapshot.get("Options");
Log.d(Tag,"output for option: "+noOfOptions);
ArrayList<String> finalCount=(ArrayList<String>) snapshot.get("CountValue");
int size=noOfOptions.size();
Log.d(Tag,"size: "+finalCount);
for(i=0;i<=size-1;i++)
{
String op=noOfOptions.get(i);
String n=finalCount.get(i);
CardView cardview=new CardView(PublicVote.this);
LayoutParams layoutparams = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT
);
LayoutParams layoutparams2 = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT
);
cardview.setLayoutParams(layoutparams);
cardview.setRadius(25);
layoutparams.setMargins(10,10,10,10);
layoutparams2.setMargins(10,100,100,100);
cardview.setPadding(25, 25, 25, 25);
cardview.setCardBackgroundColor(Color.TRANSPARENT);
cardview.setBackgroundTintList(ColorStateList.valueOf(Color.YELLOW));
cardview.setMaxCardElevation(30);
cardview.setMaxCardElevation(6);
TextView textview = new TextView(PublicVote.this);
textview.setLayoutParams(layoutparams);
textview.append("o " +noOfOptions.get(i));
textview.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 25);
textview.setTextColor(Color.BLACK);
textview.setPadding(25,25,25,25);
textview.setGravity(Gravity.LEFT);
textview.setLayoutParams(layoutparams);
TextView textview1 = new TextView(PublicVote.this);
textview1.setLayoutParams(layoutparams);
textview1.append("Description: "+description.get(i));
textview1.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 25);
textview1.setTextColor(Color.BLACK);
textview1.setPadding(25,25,25,25);
textview1.setGravity(Gravity.LEFT);
textview1.setLayoutParams(layoutparams2);
cardview.addView(textview);
cardview.addView(textview1);
l1.addView(cardview);
cardview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(PublicVote.this, n, Toast.LENGTH_SHORT).show();
n1 = Integer.parseInt(String.valueOf(n));
n1 = n1 + 1;
Log.d(Tag,"i->>: "+n1);
}
});
}
}
This is my code above here my n1 is the countValue which is updated everytime the user clicks the cardview it keeps on incrementing. Now I want to save this incremented value i.e. the countValue (n1 here)back to the database which is given below.
Now here the options 121 and 122 have count value 10 and 5 respectively which gets incremented by 1 when any one option is clicked, lets say 121 is clicked so new value is 11 and 5(remains the same). This 11 and 5 needs to be updated back to the database, need help with this!
Hum, I suggest to set the settings in the XML layout instead of the setting in the class, it's more easy to visualize. If I understood should be like this, unless is another variable.
If the variable n1 is counting the numbers
Log.d(Tag,"n1->>: "+ n1);
Try todo this:
Log.d(Tag,"n1->>: "+ (n1 + 1));
or setting the number outside the operation
n1 = n1 + 1;
This way every time they click on is going to set the number +1, try to do what i said about the settings in the xml.
you can use the two atomic operations in Cloud Firestore:
Transactions or Batch Writes on your snapshot and the document.
Update data with transactions when button click event is called.
Use Batch Writes at some point of interval.
Check this link for reference.
You can add your write back to firestore action inside onClick method as below.
cardview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(PublicVote.this, n, Toast.LENGTH_SHORT).show();
n1 = Integer.parseInt(String.valueOf(n));
n1 = n1 + 1;
Log.d(Tag,"i->>: "+n1);
//update database
//add your update code here.
}
});
You can find more on [Firebase] Cloud Firestore — Add, Set, Update, Delete, Get data

How to update whole output row on change of given Input?

I am having trouble with my output screen!
When I click on Click button with these inputs output screen looks like attached image, which is so far great!
But if I change my input, the program gives new answer by adding more rows with previous answers! I want only new answers on screen to be shown!
Also without updating input if I click on button same way screen adds up new rows!
I am including a picture of this also..
I used this code given below,
clickbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aI = Double.parseDouble(Ia.getText().toString());
bI = Double.parseDouble(Ib.getText().toString());
cI = Double.parseDouble(Ic.getText().toString());
bisection();
}
});
private void bisection() {
if ((f(aI) < 0 && f(bI) > 0) || (f(aI) > 0 && f(bI) < 0)) {
for (int i = 0; i < cI; i++) {
View tableRow = LayoutInflater.from(this).inflate(R.layout.table_item, null, false);
TextView iteration = (TextView) tableRow.findViewById(R.id.index);
TextView a = (TextView) tableRow.findViewById(R.id.a);
TextView b = (TextView) tableRow.findViewById(R.id.b);
TextView x = (TextView) tableRow.findViewById(R.id.x);
TextView fx = (TextView) tableRow.findViewById(R.id.fx);
double root = (aI+bI)/2;
iteration.setText(" " + (i + 1));
a.setText(Double.toString(aI));
b.setText(Double.toString(bI));
x.setText(Double.toString(root));
fx.setText(Double.toString(f(root)));
tableLayout.addView(tableRow);
if(f(aI)*f(root) < 0){
bI = root;
}else if (f(aI)*f(root) >0) {
aI = root;
}
}
} else {
Toast.makeText(getApplicationContext(), R.string.popUpMsg,Toast.LENGTH_SHORT).show();
}
}
public static double f(double x){
return ((Math.pow(x,3))-x-4);
}
I have already found almost same problem has been solved in a post previously asked by someone else but I couldn't fix mine! Help me. Thanks!
In your button click listener method, add following line of code before calling bisection().
tableLayout.removeAllViews();
Whenever, you will click the button, previous output will be removed before calculating new input values.
Your code would look like this:
clickbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aI = Double.parseDouble(Ia.getText().toString());
bI = Double.parseDouble(Ib.getText().toString());
cI = Double.parseDouble(Ic.getText().toString());
tableLayout.removeAllViews(); // Remove previous output
bisection();
}
});
first way; You have to use
removeAllViews();
Before adding. To do this, you have to have a layout variable around. ex;
linearLayout.removeAllViews();
Another way is adding the Textviews in the beginning with VIEW.INVISIBLE or VIEW.GONE
Whichever suits you.

Creating new Textviews in another activity based onClick android

I would like to create a new textview to hold the information sent each time the button is clicked. I have the data I want passing to another screen in a textview but each time i try to put new data it overrides this data because it uses the same textView (textview4). I would like to know if there is a way of creating a new text view to hold my data each time the button is clicked. I hope I was clear enough, thanks.
This code is from a class called CreateWorkout.Java
public void createNewWorkout (View view){
TextView Exercise1TextView = (TextView) findViewById(R.id.Exercise1TextView);
EditText weightEntered = (EditText)findViewById(R.id.WeightLiftedEditText);
EditText reps = (EditText)findViewById(R.id.RepsEditText1);
EditText sets = (EditText)findViewById(R.id.setsEditText1);
Intent getWorkoutIntent = new Intent(this, SelectWorkout.class);
getWorkoutIntent.putExtra("Workout", Exercise1TextView.getText().toString()
+ " " + weightEntered.getText().toString() + "kg"
+ " " + reps.getText().toString() + " reps"
+ " " + sets.getText().toString() + " sets");
startActivity(getWorkoutIntent);
}
This is where the intent is called. This is from SelectWorkout.Java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_workout);
TextView textView4 = (TextView) findViewById(R.id.textView4);
textView4.setText(getIntent().getExtras().getString("Workout"));
}
i want to take the data entered here to the next screen. So the exercise name(Leg Press), weight(50), set(3), reps(10)
creating a new text view to hold my data each time
Not an exact answer, but this should guide you in the right direction. You could do something like the following:
Get your bundle
Iterate bundle
Create Textviews during iteration and add them to "your_main_layout" which is the id of the main layout inside select_workout
The bundle is the extra data you're sending over from the Intent. The Iterate is going through each item you sent over to this new intent, the create part refers to creating a TextView for each item you sent over. I've supplied links to what I found below.
Listing all extras of an Intent
//Get a bundle:
for (String key : bundle.keySet()) {
// This is each value (text) you sent over from the last intent
Object value = bundle.get(key);
//output data to log, so you can see what prints out
Log.d(TAG, String.format("%s %s (%s)", key, value.toString(), value.getClass().getName()));
//adding a textview to a layout called your_main_layout (which can be a linear layout or something)
//with value.toString() as the text
your_main_layout.addView(createATextView(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
value.toString(), 20, 10, 20));
}
How can I add a TextView to a LinearLayout dynamically in Android?
//method to create view:
public TextView createATextView(int layout_widh, int layout_height, int align,
String text, int fontSize, int margin, int padding) {
TextView textView_item_name = new TextView(this);
// LayoutParams layoutParams = new LayoutParams(
// LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// layoutParams.gravity = Gravity.LEFT;
RelativeLayout.LayoutParams _params = new RelativeLayout.LayoutParams(
layout_widh, layout_height);
_params.setMargins(margin, margin, margin, margin);
_params.addRule(align);
textView_item_name.setLayoutParams(_params);
textView_item_name.setText(text);
textView_item_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
textView_item_name.setTextColor(Color.parseColor("#000000"));
// textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
textView_item_name.setPadding(padding, padding, padding, padding);
return textView_item_name;
}

Button OnClicklistener from dynamically genereated Buttons

I have a problem to build correct OnClicklistener for buttons I generate at runtime. I found some threads here on stackoverflow but after many tries I don't get it working.
I have a methode with builds a GUI with a TextView in left "column" and in right "column" x buttons. Each Button has an other link which should be open by onClick. I don't know the link before it's created at runtime.
Here my Code with my actuall try. But in this Case I get everytime only the link of the last generated button. If I click on first one, second one .... it's everytime the same link.
Hope there is a solution for it!
private void createNewView (String JsonInputBeacon, String JsonInputConfig){
TableLayout tableLayout = new TableLayout(this);
tableLayout.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
tableLayout.setStretchAllColumns(true);
try {
final JSONArray jsonArrayBeacon = new JSONArray(JsonInputBeacon);
final JSONArray jsonArrayConfig = new JSONArray(JsonInputConfig);
int Patientencounter = 1;
for(int JsonObjectCounterBeacon = 0; JsonObjectCounterBeacon < jsonArrayBeacon.length(); JsonObjectCounterBeacon ++ ){
final JSONObject objectBeacon = jsonArrayBeacon.getJSONObject(JsonObjectCounterBeacon);
TableRow row = new TableRow(this);
TextView outputLeft = new TextView(this);
outputLeft.setText("Patient " + Patientencounter + ":\n" + "Name: " + objectBeacon.getString("surname") + ", " + objectBeacon.getString("firstName") + "\n" + "Geb-Datum: " + objectBeacon.getString("birthdate"));
row.addView(outputLeft);
for (int JsonObjectCounterConfig = 0; JsonObjectCounterConfig < jsonArrayConfig.length(); JsonObjectCounterConfig++){
final JSONObject objectConfig = jsonArrayConfig.getJSONObject(JsonObjectCounterConfig);
TableRow rowRight = new TableRow(this);
Button buttonRight = new Button(getApplicationContext());
buttonRight.setText(objectConfig.getString("name"));
final String myURL = objectConfig.getString("link");
buttonRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW,Uri.parse(myURL));
startActivity(browserIntent);
}
});
rowRight.addView(buttonRight);
row.addView(rowRight);
}
tableLayout.addView(row);
Patientencounter +=1;
}
} catch (JSONException e) {
e.printStackTrace();
}
setContentView(tableLayout);
}
But in this Case I get everytime only the link of the last generated
button. If I click on first one, second one .... it's everytime the
same link
Because myURLcontains value which is assigned by last iteration of for-loop.
Use setTag/getTag method of buttonRight to get url according to Button click. like:
Set value using setTag :
final String myURL = objectConfig.getString("link");
buttonRight.setTag(myURL);
and get myURL value using v parameter of onClick method:
Intent browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(v.getTag().toString()));
Set the tag of your button to be the URI, then access the tag from the view passed in to your onclick method.

Change image to a button created programmatically

I have created a interface with buttons, but i don't know how many buttons I need to create, so I have created them in java, with this code:
public void criaButton (String nome){
TableLayout tl=(TableLayout)findViewById(R.id.tabBTALERT);
TableRow tr1 = new TableRow(this);
tr1.setPadding(17, 15, 15, 5);
final Button bt = new Button(this);
bt.setText(nome);
bt.setTextColor(Color.BLACK);
bt.setBackgroundResource(R.drawable.botao);
bt.setCompoundDrawablesWithIntrinsicBounds(R.drawable.envelope, 0, 0, 0);
bt.setPadding(10, 20, 20, 20);
bt.setId(id);
tr1.addView(bt);
tl.addView(tr1);
bt.setOnClickListener( new View.OnClickListener() {
public void onClick(View arg0) {
idButton = bt.getId();
nomeButton = (String) bt.getText();
inicia ();
Toast.makeText(Alerta.this, "Nome e ID : " + nomeButton + " " + idButton, Toast.LENGTH_SHORT).show();
}
});
}
with this method I can save the id and the name of every button I create. The problem is, these buttons have an image, and when I start another activity I have to change the image, if the message was read, not read, approved or rejected.
The question is, how can I give the id of the button to change the image and start again the activity with the changed image?? Is this possible?
Save the button ids in an array and then find the buttons by their ids and change their image to the desired one.

Categories

Resources