Android, How to pass the name of int variable to a popupwindow? - java

How can I pass the name of an int variable to a popupwindow when an image is clicked? I have set an int per image and I have a lot of images that I had set.
This is how I'm using the int in a textView on a PopupWindow.
public boolean onLongClick(View v) {
// v.setTag(v);
case R.id.hsv1iv1:
ImageView ivpopup = (ImageView) popupView.findViewById(R.id.pv1);
intcount1++; // I would like to pass this int name to the popup window.
break;
case R.id.hsv2iv1:
ImageView ivpopup = (ImageView) popupView.findViewById(R.id.pv1);
intcount2++; // I would like to pass this int name to the popup window.
break;
LayoutInflater layoutInflater
= (LayoutInflater)getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(
popupView,
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
popupWindow.update(0, 0, 800, 500);
ColorDrawable dw = new ColorDrawable(-005500);
popupWindow.setBackgroundDrawable(dw);
tvpwlikectr = (TextView) popupView.findViewById(R.id.liketv);
Button pwlikebtn = (Button) popupView.findViewById(R.id.pwlikebtn);
Button btnDismiss = (Button)popupView.findViewById(R.id.cancel);
pwlikebtn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
intcount1++;
tvpwlikectr.setText(Integer.toString(intcount1)); // this code doesn't work with the intcount1
}});
btnDismiss.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
popupWindow.dismiss();
popupWindow.setTouchable(true);
popupWindow.setFocusable(true);
popupWindow.setOutsideTouchable(true);
}
}

Could you explain how you are setting the INT per image? Copying and pasting the code on how you set an INT per image would be helpful, because it's unclear what you mean by you are setting an INT per image.
Also, are you interested in the value of the int variable or the name of the variable? Showing how you are settings lots of images with int per image would help clarify what you are trying to do.
-- adding answer after seeing the updated post with code --
I would create an object that has the name you are interested in (i.e. intcount1) and an int to keep the actual value. After that, you can associate each button/ImaveView with that object with the view.setTag method, and get the value via view.getTag method. Here's an example:
private class MyTag {
String mTagName;
int mCount;
MyTag(String tagName) {
mTagName = tagName;
mCount = 0;
}
}
// in your onCreate or initializaion code somewhere
ImageView view1 = (ImageView) popupView.findViewById(R.id.hsv1iv1);
MyTag imageTag = new MyTag("intcount1");
view1.setTag(imageTag);
ImageView view2 = (ImageView) popupView.findViewById(R.id.hsv1iv1);
// this will go wherever you handle the onLongClick
public boolean onLongClick(View v) {
Object tag = v.getTag();
if (tag instanceof MyTag) {
MyTag myTag = (MyTag) tag;
myTag.mCount++;
}
}
// I'm assuming you are setting the text from the actual clicked object
// so this will go wherever you are setting the text/handling the click
public void onClick(View v) {
Object tag = v.getTag();
if (tag instanceof MyTag) {
MyTag myTag = (MyTag) tag;
myTag.mCount++;
tvpwlikectr.setText(myTag.mTagName);
}
}
The bottom line is, creating an object with name/count value, associate each View with its own object using the view.setTag() function, and when you need to read the values, use the view.getTag() to get the object and read the mTagName (the "variable" name) and the mCount (the "variable" value).

Related

Click listener inside OnBindViewHolder

I have the following code for the recyclerview adapter for an android app that I'm working on right now:
#Override
public void onBindViewHolder(final FeedViewHolder contactViewHolder, final int i) {
final FeedInfo ci = feedInfoList.get(i);
//Set the text of the feed with your data
contactViewHolder.feedText.setText(ci.getFeed());
contactViewHolder.surNameText.setText(ci.getSurName());
contactViewHolder.nameText.setText(ci.getFirstName());
contactViewHolder.feedDate.setText(ci.getDate());
contactViewHolder.numberOfGoingText.setText(ci.getNumber_of_going());
contactViewHolder.numberOfInterestedText.setText(ci.getNumber_of_interested());
//seteaza fotografia de profil in postare
new ProfilePictureDownloadImage(contactViewHolder.profilePicture).execute(ci.getProfileImageURL());
ImageButton interestedButton = contactViewHolder.interestedButton;
interestedButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = i;
FeedInfo fi = feedInfoList.get(position);
int displayedNumberOfInterested = Integer.parseInt(ci.getNumber_of_interested()) + 1;
contactViewHolder.numberOfInterestedText.setText(Integer.toString(displayedNumberOfInterested));
System.out.println("emilutzy interested from within" + fi.getPostID());
contactViewHolder.surNameText.setText("kk");
}
});
}
The problem is the click listener. In theory the button I press should increment the number right next to it. However, since I have to declare onBindViewHolder's arguments as final, only the first click works, the rest of the clicks do not change the value of the number. I am new to Android, so could you please help me find a better solution?
There's a nice method called getAdapterPosition() that you can use in your RecyclerView's ViewHolder.
Instead of setting the click listener in onBindViewHolder, set it in the constructor of your ViewHolder like so:
public class FeedViewHolder extends RecyclerView.ViewHolder {
private TextView feedText;
private TextView surNameText;
private Button interestedButton;
// ... the rest of your viewholder elements
public FeedViewHolder(View itemView) {
super(itemView);
feedtext = itemView.findViewById(R.id.feedtext);
// ... find your other views
interestedButton.setOnClickListener(new View.OnClickListener() {
final FeedInfo fi = feedInfoList.get(getAdapterPosition());
int numInterested = Integer.parseInt(ci.getNumber_of_interested()) + 1;
// setting the views here might work,
// but you will find that they reset themselves
// after you scroll up and down (views get recycled).
// find a way to update feedInfoList,
// I like to use EventBus to send an event to the
// host activity/fragment like so:
EventBus.getDefault().post(
new UpdateFeedInfoListEvent(getAdapterPosition(), numInterested));
// in your host activity/fragment,
// update the list and call
// notifyDatasetChanged/notifyDataUpdated()
//on this RecyclerView adapter accordingly
});
}
}
Don't set your position in onBindViewHolder to final (Android Studio will warn you why).
I'm not sure how the object FeedInfo looks like but you could also at a method called for example increaseNumberOfInterested() which would increase the value of Number_of_interested by one and would persist in the object when the recyclerview recycle the cell. it would like kind of like below
#Override
public void onBindViewHolder(final FeedViewHolder contactViewHolder, final int i) {
final FeedInfo ci = feedInfoList.get(i);
//Set the text of the feed with your data
contactViewHolder.numberOfInterestedText.setText(ci.getNumber_of_interested());
contactViewHolder.interestedButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Increase the number of interested in the object, so it can be persisted when cell is reclycled
ci.setNumberOfInterested(ci.getNumber_of_interested()) + 1);
//Get new value and display
contactViewHolder.numberOfInterestedText.setText(Integer.toString(ci.getNumber_of_interested()));
}

How do I randomize images in android studio? The code I wrote isn't working

I want to randomize the the back images that will be brought from a database(code still not added), but the code I wrote isn't working. I have originally just added the flip function. I searched up how to randomize images and tried to follow the code given. Sadly its not working for me.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get references to the imageView objects
imgUpperLeft = (ImageView) findViewById(R.id.imgUpperLeft);
imgUpperRight = (ImageView) findViewById(R.id.imageView2);
imgLowerLeft = (ImageView) findViewById(R.id.imageView3);
imgLowerRight = (ImageView) findViewById(R.id.imageView4);
// Setting the initial image (First face of cards)
imgUpperLeft.setImageResource(R.drawable.img_waterfall);
imgUpperRight.setImageResource(R.drawable.img_waterfall);
imgLowerLeft.setImageResource(R.drawable.img_waterfall);
imgLowerRight.setImageResource(R.drawable.img_waterfall);
imgUpperLeft.setVisibility(View.VISIBLE);
imgUpperRight.setVisibility(View.VISIBLE);
imgLowerLeft.setVisibility(View.VISIBLE);
imgLowerRight.setVisibility(View.VISIBLE);
}
ImageView imgView = new ImageView(this);
Random rand = new Random();
int rndInt = rand.nextInt(4) + 1; // n = the number of images, that start at idx 1
String imgName = "img" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
// Shows the second face of the cards
public void showUpperLeftImage(View v){
imgView.setImageResource(id);
}
public void showUpperRightImage(View v){
imgView.setImageResource(id);
}
public void showLowerLeftImage(View v){
imgView.setImageResource(id);
}
public void showLowerRightImage(View v){
imgView.setImageResource(id);
}
Two things in your code stand out to me:
ImageView imgView = new ImageView(this);
This ImageView is not part of the view hierarchy, meaning it is not on screen. Was it ever meant to be on screen? If not, then I don't think you need this.
public void showUpperLeftImage(View v){
imgView.setImageResource(id);
}
You have four methods like this one that change the image of the view that is not on screen. Judging by their method names, I think you want to change the image of the four ImageViews you found earlier with findViewById().
I think you want to do this:
public void showUpperLeftImage(int id) {
imgUpperLeft.setImageResource(id);
}
public void showUpperRightImage(int id) {
imgUpperRight.setImageResource(id);
}
public void showLowerLeftImage(int id) {
imgLowerLeft.setImageResource(id);
}
public void showLowerRightImage(int id) {
imgLowerRight.setImageResource(id);
}

Get the Integer behind ImageView Array

I have this thing into my application.
That I want to do is this, when someone presses the die with the number 5 I want to add 5 points into his ArrayList. I was thinking for an Listener but how would I know which ImageView has been pressed?
Currently I am using this method to get the right placeholders in the board
public ImageView[] initiateDice() {
ImageView pDice1 = (ImageView) findViewById(R.id.die_one);
ImageView pDice2 = (ImageView) findViewById(R.id.die_two);
ImageView pDice3 = (ImageView) findViewById(R.id.die_three);
ImageView pDice4 = (ImageView) findViewById(R.id.die_four);
ImageView pDice5 = (ImageView) findViewById(R.id.die_five);
ImageView pDice6 = (ImageView) findViewById(R.id.die_six);
ImageView pDice7 = (ImageView) findViewById(R.id.die_seven);
ImageView pDice8 = (ImageView) findViewById(R.id.die_eight);
ImageView[] placeHolders = new ImageView[] {pDice1, pDice2, pDice3, pDice4, pDice5, pDice6, pDice7, pDice8};
return placeHolders;
}
and I am "printing" the dice on the screen using that method
public void printDice(int[] array1, ImageView[] array2) {
for (int i = 0; i < array1.length; i++) {
array2[i].setImageResource(diceImages[array1[i] - 1]);
array2[i].setVisibility(View.VISIBLE);
}
}
where the first array is 8 random generated numbers for the dice and the second array is the PlaceHolders.
The diceImages is for the images of the dice, the six states of them.
private final int[] diceImages = new int[] {R.drawable.dice_one, R.drawable.dice_two, R.drawable.dice_three,
R.drawable.dice_four, R.drawable.dice_five, R.drawable.dice_pico };
Any thoughts or suggestions are welcome.
Other answers are providing some of the solution, but you're actually asking about how to get the number displayed in the image view, in which case, you can save it to the tag:
public void printDice(int[] array1, ImageView[] array2) {
for (int i = 0; i < array1.length; i++) {
array2[i].setImageResource(diceImages[array1[i] - 1]);
array2[i].setVisibility(View.VISIBLE);
array2[i].setTag(array1[i]);
}
}
And modifying Matt's answer:
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
Integer dieValue = v.getTag();
// do something
}
};
pDice1.setOnClickListnener(listener);
pDice2.setOnClickListnener(listener);
pDice3.setOnClickListnener(listener);
pDice4.setOnClickListnener(listener);
pDice5.setOnClickListnener(listener);
pDice6.setOnClickListnener(listener);
pDice6.setOnClickListnener(listener);
pDice8.setOnClickListnener(listener);
One way to do it is to set an OnClickListener like this:
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
if (v == pDice1) {
// do something
} else if (v == pDice2) {
...
}
}
};
pDice1.setOnClickListnener(listener);
pDice2.setOnClickListnener(listener);
pDice3.setOnClickListnener(listener);
pDice4.setOnClickListnener(listener);
pDice5.setOnClickListnener(listener);
pDice6.setOnClickListnener(listener);
pDice6.setOnClickListnener(listener);
pDice8.setOnClickListnener(listener);
You would set an OnClickListener() to all ImageViews. The OnClickListener() gets passed the View that has clicked. View has a getId() that returns an int with the id of the View. Then it is only a matter of adding either a switch or if(){...} else if(...)() to perform a specific action based on the id of the View that was clicked.

Passing values to a function in Java

I am building an android app for work using android studio. I have a list of witnesses stored as sharedpreference, when the uses clicks to amend these witnesses are split up and listed the user can then click the witness they want to amend, well that's the plan, I just cant seem pass the witness listed number (basically the number used in the loop) to another function that will load the witnesses information into a form to be amended. Below is my code:
String s= WitnessDetails;
String[] array = s.split("$_$(?=[0-9])");
LinearLayout parentLayout = (LinearLayout)findViewById(R.id.LinearLayout);
// Layout inflater
LayoutInflater layoutInflater = getLayoutInflater();
View view;
for(String str : array)
{
countWitness++;
String WitnessName= str;
view = layoutInflater.inflate(R.layout.witnesses_activity, parentLayout, false);
// In order to get the view we have to use the new view with text_layout in it
TextView textView = (TextView)view.findViewById(R.id.Witnesses_details);
textView.setText("Witness 1: " + countWitness + "\n" + WitnessName+"\n Edit");
// Add the text view to the parent layout
parentLayout.addView(textView);
textView.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Amendwitness(countWitness);
}
});
}
public void Amendwitness(witnessNum){
}
You are using countWitness inside an inner anonymous class, so either
countWitness should be final
or
countWitness should be class field
otherwise compiler will show error. Since countWitness is incremented inside for-loop, it cannot be declared final, so the only solution left is to make it as class-field
OR
you can use the setTag(Object) function
for(String str : array)
{
countWitness++;
String WitnessName= str;
view = layoutInflater.inflate(R.layout.witnesses_activity, parentLayout, false);
TextView textView = (TextView)view.findViewById(R.id.Witnesses_details);
textView.setText("Witness 1: " + countWitness + "\n" + WitnessName+"\n Edit");
textView.setTag(countWitness); // set the countWitness as tag object
parentLayout.addView(textView);
textView.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Amendwitness((Integer)arg0.getTag());
}
});
}
Here are two possibilities:
Add a custom MyClickListener class:
public class MyClickListener implements View.OnClickListener {
private int mIndex;
public MyClickListener(int index) {
mIndex = index;
}
#Override
public void onClick(View v) {
Amendwitness(index);
}
}
Add your OnClickListeners like this:
textView.setOnClickListener(new MyClickListener(countWitness));
Use the tag of the View:
textView.setTag(countWitness);
textView.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Amendwitness(v.getTag());
}
});

get/use radio button value android

I FIGURED OUT WHAT I WAS DOING. I HAD THE VARIABLE NAME IN QUOTES WITH THE REST OF THE URL STRING.
How do you save the value of a Radio button into a variable and use that variable later.
I can see the variable Day_Item in my LogCat and the value is in there but when try using Day_Item later it does not show the valuable.
Below is a section of my code that shows the buttons.
String Day_Item = null;
public class SearchDB extends Activity {
private static final String TAG = "MyApp";
String start_log = "STARTED";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_layout);
final RadioButton radio_monday = (RadioButton) findViewById(R.id.monday);
radio_monday.setOnClickListener(radio_listener);
cityspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,long arg3)
{
int id = parent.getId();
if (spinner2_count2 < spinner2_count1 ) {
spinner2_count2++; }
else
{
String city_spinner_log = "CITY SPINNER";
Log.d(TAG, city_spinner_log);
String item = cityspinner.getSelectedItem().toString();
String nameContentType = "name";
String cityURL = "GetRestaurant.php?day=Day_Item&city=" + item;
Log.d(TAG, cityURL);
String shop_data = DataCall.getJSON(cityURL,nameContentType);
Log.d(TAG, shop_data);
Bundle bundle = new Bundle();
bundle.putString("shopData", shop_data);
Intent myIntent = new Intent(SearchDB.this, ShowRestaurant.class);
myIntent.putExtras(bundle);
startActivityForResult(myIntent, 0);
}
}
}
//ONCLICKLISTENER that saves RADIO value into a variable.
public OnClickListener radio_listener = new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
RadioButton rb = (RadioButton) v;
Day_Item = (String) rb.getText();
Log.d(TAG,Day_Item);
Toast.makeText(SearchDB.this, Day_Item, Toast.LENGTH_SHORT).show();
}
};
}
You would need a bit more code to get a good solid answer. Such as how is Day_Item allocated? And is it's scope global? Are you calling it from another activity or the one it's allocated within? These are just guesses at this point:
1) Are you sure your onClickListener isn't firing multiple times? Thus setting Day_Item to an undesired text or nothing at all?
2) Rather a question/answer,
"but when try using Day_Item later it does not show the valuable"
I'm assuming this means that it is null? Well if it's being set properly, and then it is being null'd... it either is being explicitly null'd by you somewhere (such as (1)) or else the allocation and scope are the issue area I believe...

Categories