I'm trying to read an element from the list shown below (using onClick), with the data being read from a JSON file, the data itself only holds strings. However, I'm having trouble actually registering the array elements to the onClick procedure.
I have absolutely no experience with JSON and am trying to familiarise myself with reading a JSON file and storing it in an Array (which I've done), but I then want to click the individual fields and make it do something.
below is what I have so far:
public void onBindViewHolder(Adapter.ViewHolder holder, int position) {
final ItemFruit itemFruit = fruitList.get(position);
holder.tvFruit.setText(itemFruit.getFruit());
holder.tvPrice.setText(itemFruit.getPrice());
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//when item is clicked, TOAST displays the field name
}
});
}
Image of array:
array of fruit
Any help whatsoever would be greatly appreciated.
Thanks in advance
put this inside onclick
Toast.makeText(adapterContext, itemFruit.getFruit(),
Toast.LENGTH_LONG).show();
Here adapterContext you have to maintain at adapter level.
Create global variable
Context adapterContext
on onCreateViewHolder initialize it
adapterContext = parent.getContext();
and then use it.
Related
[update] I fix the mistake I made. now the spinner can update dynamically. But every time I launch this new activity, the spinner will be empty, how can I keep the old data when the activity be created again?
I have an EditView, a Button, and a spinner. When the user types in an item in EditView that is not in the spinner, they can click the button to add to the spinner for the next time to save time.
I search for some solutions in StackOverflow and google, but after I click the button, it still not work, the data still not add to the spinner. Here is the part of the code:
purchasedProduct=(EditText)findViewById(R.id.purchasedP);
spinner=(Spinner)findViewById(R.id.spinner);
spinnerBtn=(Button)findViewById(R.id.purchasedDBtn);
items =new ArrayList<String>();
items.add("");
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinnerBtn.setOnClickListener(spinnerBtnListener);
spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
purchasedProduct.setText(adapterView.getSelectedItem().toString());
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private Button.OnClickListener spinnerBtnListener = new Button.OnClickListener(){
#Override
public void onClick(View view) {
String listItem = purchasedProduct.getText().toString();
//check if already there
for(int i = 0;i < adapter.getCount();i++)
{
if(listItem.equals(adapter.getItem(i)))
return;
}
//check if type in is empty
if(!listItem.equals(""))
{
adapter.clear();
items.add(listItem);
adapter.addAll(items);
adapter.notifyDataSetChanged();
}
}
};
Can anyone tell me how to fix it? thank you!
You need to store new data in SQLite database. On start activity you just get data from database. All data in database save on device. See how to use SQLite in Android Studio.
Also you can try store data in XML JSON or text file, but this is bad idea.
You can use Room Persistence Library, Look Here for details.
This library helps you create a cache of your app's data on a device that's running your app. This cache, which serves as your app's single source of truth, allows users to view a consistent copy of key information within your app, regardless of whether users have an internet connection.
I am designing a password system based on images which are displayed in the grid view. Since I am not so much familiar with android I want your help.My images are displayed dynamically on the grid i.e they keep on changing their position.
i am not to figure out how to define image as password.I want four images to be clicked in order and save them at the time of registration to the user.I am having difficulty in the saving part like which method to use and where to save.
what i want to do is this.
I want phone to display 15 images dynamically in grid view. then the user clicks 4 images in sequence to set the pass code for registration and it is saved offline. so the user next time clicks 4 images in same order to get unlocked. I am having difficulty in storing the corresponding image displayed on the particular grid because in need images to save the pass code and how to store the data of the user like username, name , and the images which he has clicked.
You can use ImageButton's in your Gridlayout or use a button and set the image as background.Further write a adapter class(I am assuming that you have written one).
Set OnClick listener inside adapter and listen to the same click..
In your adapter class
holder.buttonone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((GridView)parent).performItemClick(v,position,0);
}
});
holder.buttontwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((GridView)parent).performItemClick(v,position,0);
}
});//further for your 15 buttons
And in your activity:
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(view.getId)
{
case R.id.buttonone:
//set the code in your edittext
break;
case R.id.buttontwo:
//do your stuff
break;
}
});
I am assuming you have a textview/edittext that will print the passcode or atleast xxxx ..So you can display it there and further handle that data.
Use edittext.getText().toString() and store it.
Hope that helps
I'm writing code where in XML I'm using ImageViews and occasionally TextViews to act as buttons. I don't need to do anything with them other than setOnClickListeners in my Java code, so I'm wondering if there's any benefit to leaving them as View objects in Java as opposed to casting them to ImageView or TextView objects.
private ImageView mPlayButton;
mPlayButton = (ImageView) findViewById(R.id.playButton);
mPlayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Audio Play", Toast.LENGTH_SHORT).show();
}
});
as opposed to
private View mCurrentSongButton;
mCurrentSongButton = findViewById(R.id.currentSongIcon);
mCurrentSongButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SongInfo.class);
startActivity(intent);
}
});
I appreciate the assistance.
There is no need to cast a View to an ImageView just to set OnClickListener. Casting an object into a different class doesn't change the object's class i.e an ImageView object will remain an ImageView when cast as a View or even as an Object. And thus same methods would be called regardless the reference wrapper of the object itself.
Purpose of casting any object to a child class should only be to unlock the otherwise unavailable methods. So if you need to call any methods which are dedicated for an ImageView, you will need to cast it to an ImageView before hand (but only so you'd be able to call or use the method).
In short if there is no need to call a child specific method then don't cast the object, it is simply an overhead for the compiler.
If you only need to set click listener, then view type is enough but if you need specialized operations like setText(), setEnabled() etc, then you need to cast them
To put you in context, when the user clicks the floating action button the activity will check which fragment is active.
Then, depending on the fragment tag it will call a method in that specific instance.
I found a way to do it on this awesome forum but the only problem is that I don't understand what I'm doing here
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment_container);
if (fragment.getTag() == "EXERCISES_LIST_FRAGMENT") {
//THIS IS THE PART I DONT UNDERSTAND
ArrayList t = ((ExercisesListFragment) fragment).GetArray();
//THIS IS THE PART I DONT UNDERSTAND
System.out.println(t.size());
}
}
});
It seems like casting a variable but I searched and did not see anything like this.
I want to know what is that part : ((SomeKindofClass) variable).SomeKindOfClassMethod();
I would like to read about that but I don't know how you name that
sorry for my English
Thanks
I got multiple OnClickListener for 8 ImageViews with the same logic behind. OnClick Variable-Details will be shown. I tried to summarize them in a method and tried to add them in the OnCreate method with a Loop. But it did not work. Now I have 8 listeners and also 8 addListener at onCreateMethod.
Is there a more elegant way?
private void addListenerCal1Arrow() {
ivCalArrow1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!cal1Clicked) {
cal1Clicked = true;
ivCalArrow1.setImageResource(R.drawable.arrow_symbol_up);
tvDescription1.setVisibility(View.VISIBLE);
} else {
cal1Clicked = false;
ivCalArrow1.setImageResource(R.drawable.arrow_symbol_down);
tvDescription1.setVisibility(View.GONE);
}
}
});
}
more explanation:
I got an experiment Fragment, where i can add 8 Variables max. Each variable has several textviews and also an ImageView, which holds further information about the variable. when the ImageView is Clicked it shall show the information. I got an container class holding all the widgets of a variable, like the textviews and the imageview and also the description which shall be displayed when its clicked
There are 2 level to summrize this code
1- use 1 onClick() for all ImageViews: this involves
1.a implementing OnClickListener and not using anonymous inner class
make your activity or fragment implements OnClickListener and override onClick()
public class MyActivity extends Activity implements OnClickListener {
//class implementation
#override
public void onClick(View view){
}
}
use this as OnClickLister for method setOnClickListener():
ivCalArrow1.setOnClickListener(this);//this here refers to MyActivity
ivCalArrow2.setOnClickListener(this);//this here refers to MyActivity
//and so on ...
b. recognize the click source (which ImageView) generated the action)
you will need to compare view id with the 8 ImageViews id and execute proper code based on that:
#override
public void onClick(View view){
if(view.getId() == ivCalArrow1.getId()){
//do what needed on ivCalArrow1
}else if(view.getId() == ivCalArrow2.getId()){
//do what needed on ivCalArrow2
}
//and so on ... for 3 4 5 6 7 8
}
2- make onClick() general to handle the click properly: this involves using arrays instead of single variables named with 1 2 3, like cal1Clicked cal2Clicked ... or tvDescription1, tvDescription2 ...
this can be done in several ways, it could be complex to understand or maintain, so try to make it clear
you might need a Map where ImageView.getId as key and some value based on what you need
for example,
boolean variables calXClicked may be you can use a HashMap, that the key is an identifier for calX and the value is boolean for the clicked status
from my understanding the identifier for cal1Clicked is the imageView itself ivCalArrow1 so:
declare this class-scope
HashMap<int, boolean> calClickedStatus = new HashMap();
an at onCreate() add this:
//assuming all boolean values are false on first create of activity
calClickedStatus.put(ivCalArrow1.getId,false);
calClickedStatus.put(ivCalArrow2.getId,false);
calClickedStatus.put(ivCalArrow3.getId,false); // and so on
now at onClick() you will use view.getId as key to lookup other data needed
no need to find what is the source of the click, because you will look it up using the key (view.getId)
#override
public void onClick(View view){
if (!calClickedStatus.get(view.getId())) {
calClickedStatus.put(view.getId(), true);
//the view here is actually the clicked ImageView, so just cast it and use it, replace this
//ivCalArrow1.setImageResource(R.drawable.arrow_symbol_up);
//with this
((ImageView)view).setImageResource(R.drawable.arrow_symbol_up);
//now for this, you may want to use an array of TextView to hold tvDescription1, tvDescription2 ...
//and make a map to link each tvDescriptionX to the index of licked image
tvDescription1.setVisibility(View.VISIBLE);
} else {
//do same changes here too
calClickedStatus.put(view.getId(), false);
ivCalArrow1.setImageResource(R.drawable.arrow_symbol_down);
tvDescription1.setVisibility(View.GONE);
}
}
as i mentioned earlier this could be complex and might be hard to explain
and it could be done in may ways, so this is just to guide you on the concept and the rest is up to you
You can define in your layout for each View the following:
android:onClick="myClickFct"
android:clickable="true"
and also in the class which loads the layout the method:
public void myClickFct(View view){
...
}