I tried to get a array from an adapter from my code
here is the array that i wanted to get from my adapter, named MakananAdapter :
private int[] JumlahPesan = {0,0,0,0};
The array is changing constantly since user will be deciding the amount that they want, here is the onBindViewHolder code:
public void onBindViewHolder(#NonNull viewHolder holder, final int position) {
ImageView ivMakanan = holder.ivMakanan;
TextView tvNamaHarga = holder.tvNamaMakanan;
TextView tvKetersediaan = holder.tvKetersediaan;
TextView tvHarga = holder.tvHargaMakanan;
final TextView tvPesanan = holder.tvJumlahPesanan;
Button btnTambah = holder.btnTambah;
Button btnKurang = holder.btnKurang;
ivMakanan.setImageResource(makanans.get(position).getGambarMakanan());
tvNamaHarga.setText(makanans.get(position).getNamaMakanan());
tvKetersediaan.setText("Stok : " + makanans.get(position).getStatusMakanan());
tvHarga.setText("Harga : " + makanans.get(position).getHargaMakanan());
btnTambah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JumlahPesan[position]++;
tvPesanan.setText(String.valueOf(JumlahPesan[position]));
}
});
btnKurang.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JumlahPesan[position]--;
tvPesanan.setText(String.valueOf(JumlahPesan[position]));
}
});
}
as you can see i make a button that increase and decrease the data of the array
and i tried to get the array data to my activity, but i still get error.
my activity named PilihMakananActivity.class
here is the array to save the data from the adapter
private int[] Pesanan = {0,0,0,0};
and i tried to get the data in onResume
protected void onResume() {
super.onResume();
com.example.iotforcanteen.adapter.MakananAdapter coba = null;
for (int i = 0; i<4 ; i++) {
Pesanan [i]= coba.AmbilJumlahPesanan(i);
}
}
and i tried to show it in a snackbar like this
btnKonfirmasi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Snackbar.make(v, Pesanan[0] + Pesanan[1] + Pesanan[2] + Pesanan[3],Snackbar.LENGTH_SHORT).show();
}
});
Im so sorry if the code is so messy, because im new to android development.so is there any way to fix this error?
It has error because you set to your adapter null value in onResume .
But in general I assume you use RecyclerView in code so the steps for using RecyclerView is important, first you must set LayoutManager for RecyclerView. Then make an adapter and set it to RecyclerView and I recommend you to do this steps in onCreate not onResume.
Here is a little example
RecyclerView recyclerView = findViewById(R.id.rec);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, list);
recyclerView.setAdapter(adapter);
Also make your array in adapter public or write getter for it. After calling setAdapter for RecyclerView, you can get your data in adapter. For example you can define a Button and in OnClickListener get the desired array(here is JumlahPesan) in adapter
you aren't initiating this adapter (null) and few lines below trying to access data from it, this is NullPointerException
com.example.iotforcanteen.adapter.MakananAdapter coba = null;
for (int i = 0; i<4 ; i++) {
Pesanan [i]= coba.AmbilJumlahPesanan(i);
}
make reference to already exitsting adapter atached to your ListView or RecyclerView, not freshly created and not initialised at all
note that onResume is called once at the beggining, thus your Pesanan won't have current data, only copy from start of Activity
maybe just get your values straightly when button pressed, without a copy of array in Activity:
btnKonfirmasi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Snackbar.make(coordinatorLayout,
adapterAttachedToView.AmbilJumlahPesanan(0) + " " +
adapterAttachedToView.AmbilJumlahPesanan(1) + " " +
adapterAttachedToView.AmbilJumlahPesanan(2) + " " +
adapterAttachedToView.AmbilJumlahPesanan(3),
Snackbar.LENGTH_SHORT).show();
}
});
note that Snackbar.make( should take View, in which Snackbar will appear, not clicked Button (you are passing v to Snackbar.make)
Related
I use onBindViewHolder in my CardAdapter. It includes an onClick method of checkedTextView.I am trying to get these texts and put to Arraylist(sharedP). But ArrayList only returns the last element. Where is my fault?
public void onBindViewHolder(#NonNull final CardTasarimTutucu holder, int position) {
SharedPreferences sp = mContext.getSharedPreferences("checked",Context.MODE_PRIVATE);
e=sp.edit();
sharedP= new ArrayList<>();
word = words.get(position).getMean();
Log.e("getMean",word);
id= words.get(position).getId();
str= new StringBuffer("");
holder.rowText.setText(word);
holder.rowText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.rowText.isChecked()) {
sharedP.remove(sharedP.indexOf(word));
flag=false;
holder.rowText.setCheckMarkDrawable(null);
holder.rowText.setChecked(false);
} else {
sharedP.add(word);
flag=true;
Log.e("deneme",word);
holder.rowText.setCheckMarkDrawable(R.drawable.ic_check_black_24dp);
holder.rowText.setChecked(true);
}
str.delete(0,str.length());
for(int i=0;i<sharedP.size();i++){
Log.e("sharedpreference1",sharedP.get(i).toString());
str.append(sharedP.get(i));
str.append(".");
}
if(flag==false){
e.remove("str");
e.commit();
}
Log.e("size",str.toString());
e.putString("str", str.toString());
e.remove("set");
e.commit();
}
});
}
example of checkedTextView
shared preference
First of all onBindViewHolder is calling for each item in RecyclerView in order to display the data in each position in the view item. So it is like a loop. In your code you initialize the sharedP array inside onBindViewHolder sharedP= new ArrayList<>();. So for each item you pass / scroll , the array is getting initialized again and the previous item is being lost.In other words when you reach the end of your list you will have only 1 item inside your list , the last one.
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()));
}
I have a ListView display file from SD card. I want to add a button for deleting all items from ListView and from SD card. I tried the following, but it deletes one. And after clicking the button a second time, it deletes another one.
Button delete = (Button) findViewById(R.id.delete);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i=0;i<adapter.getCount();i++){
adapter.getItem(i);
File ff = new File(Environment.getExternalStorageDirectory().toString() + "/TestApp/" + adapter.getItem(i));
ff.delete();
}
adapter.remove(adapter.getItem(i));
adapter.notifyDataSetChanged();
}
}
You need to clear the list associated with your adapter here. Then just call notifyDataSetChanged() on your adapter. So the sample code should look like this. Just clear the list after you have deleted all associated files in your SD card.
Button buy = (Button) findViewById(R.id.delete);
buy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = 0; i < yourList.size(); i++){
File ff = new File(Environment.getExternalStorageDirectory().toString() + "/TestApp/" + yourList.get(i));
ff.delete();
}
// Clear your list here
yourList.clear();
// And remove the following line
// adapter.remove(adapter.getItem(i));
adapter.notifyDataSetChanged();
}
}
Place following method in you adapter:
public void clearData(){
list.clear();
notifyDataSetChanged();
}
Now Replace your code lines:
adapter.remove(adapter.getItem(i));
adapter.notifyDataSetChanged();
to This line:
adapter.clearData();
I'm adding EditText in linear layout and it gives a view like that in image.
I'm getting this view by using this code.
public class SearchRecipe extends AppCompatActivity {
LinearLayout parentLayout;
ImageButton searchRecipe;
private int EDITTEXT_ID = 1;
private List<EditText> editTextList;
EditText editTextItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_recipe);
setActionBar();
init();
searchRecipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editTextItem = (EditText) parentLayout.findViewById(EDITTEXT_ID);
for (int i = 0; i < editTextList.size(); i++) {
Log.e("All Values=", editTextList.get(i).getText().toString());
Toast.makeText(SearchRecipe.this, editTextItem.getText().toString() + " ", Toast.LENGTH_SHORT).show();
}
}
});
}
public void init() {
parentLayout = (LinearLayout) findViewById(R.id.parent_layout); //make sure you have set vertical orientation attribute on your xml
searchRecipe = (ImageButton) findViewById(R.id.search_button);
editTextList = new ArrayList<EditText>();
TextView addMoreText = new TextView(this);
addMoreText.setText("Add More Ingredients");
addMoreText.setGravity(Gravity.CENTER);
addMoreText.setPadding(20, 20, 20, 20);
addMoreText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.add, 0);
addMoreText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editTextItem = new EditText(SearchRecipe.this);
editTextItem.setId(EDITTEXT_ID);
editTextList.add(editTextItem);
EDITTEXT_ID++;
editTextItem.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.cross, 0);
editTextItem.setPadding(20, 20, 20, 20);
editTextItem.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
parentLayout.removeView(editTextItem);
return true;
}
});
parentLayout.addView(editTextItem, 0);
}
});
parentLayout.addView(addMoreText);
}
Now the only problem I'm facing is that. I'm not getting the text from edittext properly. Let me Explain what I want to do.
Click on Add More TextView will add one more edit text.
After adding all edittexts I will click on Search button.
By clicking search button will get the data from edittexs and save in arraylist. I tried a lot but can't do this properly. will you please help me to do this thing ? I'm stuck in from many days.
if you are createing edit text run time only for this purpose then there is no need of below tow lines
editTextItem.setId(EDITTEXT_ID);
EDITTEXT_ID++;
To retrive data from each edit box follow below things
for (EditText editText : editTextList) {
/* now you can get the value from Edit-text and save in the ArrayList
or you can append it in same string*/
yourArraList.add(editText.getText().toString()));
}
Get the editext from your list editTextList
String data = editTextList.get(index).getText().toString();
Add check for editTextList should not be null or empty.
You can iterate over list using for-each loop
for (EditText editText : editTextList) {
// now you can get the value from Edit-text and save in the ArrayList
yourArraList.add(editText.getText().toString()));
}
you can do like below if view inside fragment.
public static String getText(final Activity activity) {
final StringBuilder stringBuilder=new StringBuilder();
LinearLayout scrollViewlinerLayout = (LinearLayout) activity.findViewById(R.id.linearLayoutForm);
ArrayList<String> msg = new ArrayList<String>();
for (int i = 0; i < scrollViewlinerLayout.getChildCount(); i++)
{
LinearLayout innerLayout = (LinearLayout) scrollViewlinerLayout.getChildAt(i);
EditText editText = (EditText) innerLayout.findViewById(R.id.meeting_dialog_et);
msg.add(editText.getText().toString());
}
for (int j=0;j<msg.size();j++)
{
stringBuilder.append(msg.get(j)).append(";");
}
Toast t = Toast.makeText(activity.getApplicationContext(), stringBuilder.toString(), Toast.LENGTH_SHORT);
t.show();
return stringBuilder.toString();
}
there is another way is make arraylist Edittexes and add each edittext when it added to layout. then you can get like below:
for (int i = 0; i < Edittexes.size(); i++) {
if (Edittexes.get(i) == view)
{
String text=Edittexes.get(i).getText();
}
}
I have this code :
private ImageView d1;
private ArrayList<Integer> listaImagenes = new ArrayList<Integer>();
private ArrayList<String> listaFrases = new ArrayList<String>();
private Button button;
private Integer contador = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.rellenarImagenes();
setContentView(R.layout.imagentonas);
d1 = (ImageView) findViewById(R.id.imagenes01);
while (contador < listaImagenes.size()) {
d1.setImageResource(listaImagenes.get(contador));
button = (Button) findViewById(R.id.botoncillo);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
contador++;
}
});
}
}
private void rellenarImagenes() {
listaImagenes.add(R.drawable.a01);
listaImagenes.add(R.drawable.a02);
listaImagenes.add(R.drawable.a03)
}
I am trying do a loop that when I press the button , increment contador and d1 change image.
but it is not working, application background remains black and not working.
remove while loop and setimage in onclick method.
You are expecting that modifying the value of the variable contador would result in the array item to change.
Keep in mind that in the code line d1.setImageResource(listaImagenes.get(contador));, the get function receives an int. So at the time where it's called it receives a value, not a reference to an Integer. When you change the value of contador, the value that was used to obtain the index in the array is not changed.
And even if the value did change, d1 would still be using the same resource.
What you need to do in the onClickListener is add the code to set the image. Something along the lines of
public void onClick(View v) {
++contador;
if (contador >= listaImagenes.size())
{
contador=0;
}
//you'll probably need to modify the next line to be able to access the button variable.
//one way to do it is to use a final variable in the onCreate method that creates this OnClickListener
button.setImageResource(listaImagenes.get(contador));
}
The while loop is not needed. What your code is doing is setting the image to the 3 items of the array, one after the other, and adding a new click listener 3 times.
I will try to answer and point some of the flaws you have in the code.
wat if there were 100 drawable like R01 ,R02...? Instead you can use getting drawable using string.
why are you using while loop ? since you have the counter you can directly use that.
Let me try to write the code
int contador=1;
#Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.imagentonas);
context=this;
d1=(ImageView)findViewById(R.id.imagenes01);
button=(Button)findViewById(R.id.botoncillo);
button=(Button)findViewById(R.id.botoncillo);
button.setOnClickListener( new View . OnClickListener () {
public void onClick ( View v ) {
int id = context.getResources().getIdentifier("a"+contador,
"drawable", context.getPackageName());
d1.setImageResource(id);
contador++;
}
});
}
Notice : int id = context.getResources().getIdentifier("a"+contador,"drawable", context.getPackageName()); Here using the string you can access the drawable this solves the issue for any number of consecutive drawables.
Hope you get the concept...
Thanks