Personalized Adapter, trying to get every element's id and display it - java

I am currently working on a personal adapter.
I have some buttons in every one of them.
One to delete, one to edit and one to add to shared pref. list.
However, I do not know how to get the Id or a specific property from the element such as it's ID.
In other words, I try to get the ID (a property from my object) to display when I click one of the buttons, later on, I will implement the feature.
However, I don't really understand where to get the elements and what does every #Override do in the adapter, also, where to declare the onClick function?
Here is my adapter, for now (The Toastare for test purpose):
package a.bogin.revmidterm.Adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import a.bogin.revmidterm.Models.StringInfos;
import a.bogin.revmidterm.R;
public class StringsAdapter extends RecyclerView.Adapter<StringsAdapter.ViewHolder> {
private List<StringInfos> allStrings;
public StringsAdapter(List<StringInfos> lst){
this.allStrings = lst;
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView string1;
TextView string2;
TextView string3;
Button delB;
Button editB;
Button addPrefB;
public ViewHolder(final View itemView) {
super(itemView);
string1 = itemView.findViewById(R.id.forS1);
string2 = itemView.findViewById(R.id.forS2);
string3 = itemView.findViewById(R.id.forS3);
delB = itemView.findViewById(R.id.delBtn);
delB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
editB = itemView.findViewById(R.id.editbtn);
editB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(itemView.getContext(), "TEST", Toast.LENGTH_SHORT).show();
}
});
addPrefB = itemView.findViewById(R.id.pref);
addPrefB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(itemView.getContext(), " C MON NOM", Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public void onBindViewHolder(final StringsAdapter.ViewHolder vh, final int position) {
StringInfos str = allStrings.get(position);
vh.string1.setText(str.getString1());
vh.string2.setText(str.getString2());
vh.string3.setText(str.getString3());
}
#Override
public int getItemCount() {
return allStrings.size();
}
#Override
public StringsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context ctx = parent.getContext();
LayoutInflater inf = LayoutInflater.from(ctx);
View createdViewForAdapter = inf.inflate(R.layout.string_adapter_infos, parent, false);
ViewHolder vh = new ViewHolder(createdViewForAdapter);
vh.editB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "TEEEEST", Toast.LENGTH_SHORT).show();
}
});
return vh;
}
}
Here is my object class:
package a.bogin.revmidterm.Models;
public class StringInfos {
private int id;
private String string1;
private String string2;
private String string3;
public StringInfos(String string1, String string2, String string3) {
this.string1 = string1;
this.string2 = string2;
this.string3 = string3;
}
public String getString1() {
return string1;
}
public void setString1(String string1) {
this.string1 = string1;
}
public String getString2() {
return string2;
}
public void setString2(String string2) {
this.string2 = string2;
}
public String getString3() {
return string3;
}
public void setString3(String string3) {
this.string3 = string3;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Also, here is my MainActivity:
package a.bogin.revmidterm;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import java.util.ArrayList;
import a.bogin.revmidterm.Adapter.StringsAdapter;
import a.bogin.revmidterm.DB.DBManager;
import a.bogin.revmidterm.Models.StringInfos;
public class MainActivity extends AppCompatActivity {
ArrayList<StringInfos> listOfAll;
StringsAdapter strAdapter;
RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLayoutManager = new LinearLayoutManager(this);
.setLayoutManager(mLayoutManager);
RecyclerView myOwnRc = findViewById(R.id.rc);
myOwnRc.addItemDecoration(new DividerItemDecoration(getApplicationContext(), DividerItemDecoration.VERTICAL));
mLayoutManager = new LinearLayoutManager(this);
myOwnRc.setLayoutManager(mLayoutManager);
listOfAll = DBManager.getAllItems();
strAdapter = new StringsAdapter(listOfAll);
myOwnRc.setAdapter(strAdapter);
myOwnRc.setLayoutManager(new LinearLayoutManager(this));
myOwnRc.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos, long id){
}
});
}
public void addStuff(View v){
Intent addNew = new Intent(this, AddItem.class);
startActivity(addNew);
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inf = getMenuInflater();
inf.inflate(R.menu.itemsstuff, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.ea:
deleteAll();
return true;
case R.id.pref:
seePrefs();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void seePrefs(){
}
public void deleteAll(){
listOfAll.clear();
finish();
startActivity(getIntent());
}
}
Feel free to suggest me links in order to know where to start or ask for any specification.
Thank you for your time.
Problem with setOnItemClickListner:
myOwnRc.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos, long id){
}
});
after myOwnRc, it is red, however, the second one is accepted.

After using these lines to display your data in a activity:
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyAdapter(myDataset);
mRecyclerView.setAdapter(mAdapter);
You can set up setonItemClickListener:
mRecylerView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//here you can use the id or position to make changes to your data
//Something like myDataset.add or myDataset.remove
String one = myDataset.get(position).getString1();
}
});
Edit: Updated Main Activity part:
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
myOwnRc.setLayoutManager(linearLayoutManager);
strAdapter = new StringsAdapter(listOfAll);
myOwnRc.setAdapter(strAdapter);
myOwnRc.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});

Related

List not updating after Filtering with searchView

I implemented searchView in android which filters data. It works correctly But after filtering data, when I add new data it does not show in recyclerView when I restart the app then it shows, I am also able to view that item after again searching something and then backspace it.
Here is My Adapter Class
package com.example.keepnotes;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
ArrayList<Notes> arrNotes;
DatabaseHelper databaseHelper;
RecyclerViewAdapter(Context context, ArrayList<Notes> arrNotes, DatabaseHelper databaseHelper) {
this.context = context;
this.arrNotes = arrNotes;
this.databaseHelper = databaseHelper;
}
public void setFilteredList(ArrayList<Notes> filteredList) {
this.arrNotes = filteredList;
notifyDataSetChanged();
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.single_view, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, #SuppressLint("RecyclerView") int position) {
holder.title.setText(arrNotes.get(position).title);
holder.body.setText(arrNotes.get(position).text);
holder.index.setText(String.valueOf(position + 1));
holder.llView.setOnClickListener(view -> {
Intent iNext = new Intent(context, ViewActivity.class);
iNext.putExtra("title", arrNotes.get(position).title);
iNext.putExtra("text", arrNotes.get(position).text);
iNext.putExtra("id", arrNotes.get(position).id);
context.startActivity(iNext);
});
holder.llView.setOnLongClickListener(view -> {
showDeleteDialog(position);
return true;
});
}
#Override
public int getItemCount() {
return arrNotes.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView title, body, index;
CardView llView;
public ViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.text_title_view);
body = itemView.findViewById(R.id.text_text_view);
index = itemView.findViewById(R.id.index);
llView = itemView.findViewById(R.id.card_View);
databaseHelper = DatabaseHelper.getDatabase(context);
}
}
private void showDeleteDialog(int position) {
AlertDialog.Builder alert = new AlertDialog.Builder(context)
.setTitle("Delete view")
.setMessage("Are you sure to delete")
.setIcon(R.drawable.ic_baseline_delete_24)
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
databaseHelper.notesDao().deleteNotes(new Notes(arrNotes.get(position).getId(), arrNotes.get(position).getTitle(), arrNotes.get(position).getText()));
}
})
.setNegativeButton("No", (dialogInterface, i) -> {
});
alert.show();
}
}
Here is My filterable function
private void filterList(String text) {
ArrayList<Notes> filteredList = new ArrayList<>();
for (Notes notes : arrNotes) {
if (notes.title.toLowerCase().contains(text.toLowerCase()) || notes.text.toLowerCase().contains(text.toLowerCase())) {
filteredList.add(notes);
}
if (!(filteredList.isEmpty())) {
adapter.setFilteredList(filteredList);
}
}
}
Here I implemented SearchView
searchView = findViewById(R.id.searchView);
searchView.clearFocus();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
filterList(newText);
return false;
}
});
I updated data using live data using this
modelView = new ViewModelProvider(this).get(notesModelView.class);
modelView.getAllNotes().observe(this, new Observer<List<Notes>>() {
#Override
public void onChanged(List<Notes> notes) {
arrNotes.clear();
arrNotes.addAll(notes);
adapter.notifyDataSetChanged();
}
});
Modify your filterList() function like this -
private void filterList(String text) {
if (!text.trim().isEmpty()) {
ArrayList<Notes> filteredList = new ArrayList<>();
for (Notes notes : arrNotes) {
if (notes.title.toLowerCase().contains(text.toLowerCase()) || notes.text.toLowerCase().contains(text.toLowerCase())) {
filteredList.add(notes);
}
adapter.setFilteredList(filteredList);
}
}else{
adapter.setFilteredList(arrNotes);
}
}

How to set Item position in order after using ItemTouchHelper.Callback

I am creating a document arrangement activity with RecyclerView. I want to arrange the document with drag and drop. It was done by using ItemTouchHelper.Callbackbut after that I can't set the page number after the OnItemMove callback. what should I do?
EDIT: added code snippet
package adapters;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.pdf.PdfRenderer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import com.mobilix.docscanner.R;
import java.util.ArrayList;
import java.util.Collections;
import helper.ItemTouchHelperAdapter;
import helper.ItemTouchHelperViewHolder;
import helper.OnStartDragListener;
import helper.SimpleItemTouchHelperCallback;
public class PageAjdustAdapter extends RecyclerView.Adapter<PageAjdustAdapter.PageAdjustHolder> implements ItemTouchHelperAdapter, OnStartDragListener {
private final String TAG = getClass().getName();
Context mContext;
ArrayList<PdfPage> pdfPages = new ArrayList<>();
private ItemTouchHelper itemTouchHelper;
public PageAjdustAdapter(Context context, ArrayList<PdfPage> pages) {
this.mContext = context;
pdfPages = pages;
ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(this);
itemTouchHelper = new ItemTouchHelper(callback);
itemTouchHelper.attachToRecyclerView(((Activity) context).findViewById(R.id.rcvPageArrange));
}
#NonNull
#Override
public PageAdjustHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_page_adajustment, parent, false);
return new PageAdjustHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PageAdjustHolder holder, int position) {
Log.d(TAG, "onBindViewHolder: ");
holder.ivPage.setImageBitmap(pdfPages.get(position).bitmap);
holder.cbPage.setChecked(pdfPages.get(position).isSelected);
holder.tvPageNo.setText(String.valueOf(position + 1));
holder.cbPage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
pdfPages.get(holder.getAdapterPosition()).isSelected = isChecked;
}
});
holder.ivRotate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getAdapterPosition();
pdfPages.get(pos).bitmap = Bitmap.createBitmap(//
pdfPages.get(pos).bitmap, 0, 0, pdfPages.get(pos).bitmap.getWidth(),//
pdfPages.get(pos).bitmap.getHeight(), pdfPages.get(pos).matrix, true);//
notifyItemChanged(pos);
}
});
}
#Override
public int getItemCount() {
return pdfPages.size();
}
#Override
public boolean onItemMove(int fromPosition, int toPosition) {
Log.d(TAG, "onItemMove: ->fp " + (fromPosition + 1) + " tp-> " + (toPosition + 1));
Collections.swap(pdfPages, fromPosition, toPosition);
notifyItemMoved(fromPosition, toPosition);
return false;
}
#Override
public void onItemDismiss(int position) {
pdfPages.remove(position);
notifyItemRemoved(position);
}
#Override
public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
itemTouchHelper.startDrag(viewHolder);
}
public static class PageAdjustHolder extends RecyclerView.ViewHolder implements
ItemTouchHelperViewHolder {
ImageView ivPage, ivRotate;
CheckBox cbPage;
TextView tvPageNo;
public PageAdjustHolder(#NonNull View itemView) {
super(itemView);
ivPage = itemView.findViewById(R.id.ivPage);
ivRotate = itemView.findViewById(R.id.ivRotate);
cbPage = itemView.findViewById(R.id.cbPage);
tvPageNo = itemView.findViewById(R.id.tvPageNo);
}
#Override
public void onItemSelected() {
}
#Override
public void onItemClear() {
}
}
public static class PdfPage {
PdfRenderer.Page page;
Bitmap bitmap;
boolean isSelected;
Matrix matrix;
int rotate = 0;
public PdfPage(PdfRenderer.Page page, Bitmap bitmap) {
this.page = page;
this.bitmap = bitmap;
matrix = new Matrix();
rotate += 90;
matrix.postRotate(90);//martix work on +=90
}
}
}
You have to call notifyDataSetChanged() when an item position is changed. The easiest way it to used onItemClear(), it will be called when an item is de-selected. Add it like following.
#Override
public void onItemClear() {
notifyDataSetChanged();
}
One thing you have to add is check weather the position is actually changed after the drag operation or not other wise it will always update the whole dataset whenever an item is selected and than de-selected.
Edit
Create a local variable in view-holder class. Than you just have to set it in onItemSelected() and check it in onItemClear();
#Override
public void onItemSelected() {
lastpos = getAdapterPosition();
}
#Override
public void onItemClear() {
if(lastpos != getAdapterPosition())
notifyDataSetChanged();
}

Button inside RecyclerView

I have a problem with my android app.
I have a RecyclerView and a click handler for it. When you click on a list item, one of the class fields is displayed on the screen. Also inside there is a button, by clicking on which another class field should be displayed. But the program throws a NullPointerException. I understand why this is happening, but I cannot understand how to modify my code, please help.
here is my Adapeter
package com.skorbr.stock_yandextest;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class TickerAdapter extends RecyclerView.Adapter<TickerAdapter.TickerViewHolder> {
private List<Ticker> tickers;
private Context context;
// listener
private final Listener onTickerClickListener;
// constructor
public TickerAdapter(List<Ticker> tickers, Listener onTickerClickListener) {
this.tickers = tickers;
this.onTickerClickListener = onTickerClickListener;
}
#NonNull
#Override
public TickerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.recycler_stock_item, parent, false);
// click on RecyclerView
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onTickerClickListener.onTickerClick((Ticker) v.getTag());
}
});
// click on button
view.findViewById(R.id.button_favourite).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onTickerClickListener.onFavouriteClick((Ticker) v.getTag());
}
});
return new TickerViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull TickerViewHolder holder, int position) {
Ticker ticker = tickers.get(position);
holder.bind(ticker);
holder.itemView.setTag(ticker);
}
#Override
public int getItemCount() {
return tickers.size();
}
class TickerViewHolder extends RecyclerView.ViewHolder {
private TextView ticker;
private TextView tickerFull;
private TextView price;
private TextView priceChange;
private ImageView tickerLogo;
private Button favouriteButton;
public TickerViewHolder(#NonNull final View itemView) {
super(itemView);
ticker = itemView.findViewById(R.id.ticker);
tickerFull = itemView.findViewById(R.id.ticker_full);
price = itemView.findViewById(R.id.price);
priceChange = itemView.findViewById(R.id.price_change);
tickerLogo = itemView.findViewById(R.id.ticker_image);
favouriteButton = itemView.findViewById(R.id.button_favourite);
}
// заполнение элемента RecyclerView данными
void bind(Ticker ticker) {
double priceNow = ticker.getPrice();
double priceDayAgo = ticker.getPriceDayAgo();
String sign = "";
this.ticker.setText(ticker.getTicker());
this.tickerFull.setText(ticker.getTickerFull());
this.price.setText("$" + priceNow);
// check price
if (priceNow < priceDayAgo) {
sign = "-";
this.priceChange.setTextColor(context.getResources().getColor(R.color.colorRedDm));
} else if (priceNow > priceDayAgo) {
sign = "+";
this.priceChange.setTextColor(context.getResources().getColor(R.color.colorGreenDm));
}
// check favourites
if (ticker.isFavourite()) {
this.favouriteButton.setBackground(context.getDrawable(R.drawable.ic_favourite_on));
} else {
this.favouriteButton.setBackground(context.getDrawable(R.drawable.ic_favourite_off));
}
this.priceChange.setText(String.format("%s$%.2f (%.2f%%)", sign, Math.abs(priceNow-priceDayAgo), Math.abs(priceNow/priceDayAgo*100-100)));
this.tickerLogo.setImageResource(ticker.getTickerLogo());
}
}
interface Listener {
void onTickerClick(Ticker ticker);
void onFavouriteClick(Ticker ticker);
}
}
Here is my Main Activity
package com.skorbr.stock_yandextest;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class ActivityMain extends Activity {
private RecyclerView tickerList;
private TickerAdapter tickerAdapter;
private List<Ticker> tickerListList;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tickerListList = tickerList();
tickerList = findViewById(R.id.tickers_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
tickerList.setLayoutManager(layoutManager);
tickerAdapter = new TickerAdapter(tickerListList, new TickerAdapter.Listener() {
#Override
public void onTickerClick(Ticker ticker) {
Toast.makeText(ActivityMain.this, ticker.getTickerFull(), Toast.LENGTH_SHORT);
}
#Override
public void onFavouriteClick(Ticker ticker) {
Toast.makeText(ActivityMain.this, ticker.getTicker(), Toast.LENGTH_SHORT);
}
});
tickerList.setAdapter(tickerAdapter);
}
private List<Ticker> tickerList() {
List<Ticker> tickers = new ArrayList<>();
tickers.add(new Ticker("APPL", "Apple Inc.", 138.54, 150.22, R.drawable.apple_logo, false));
tickers.add(new Ticker("TSLA", "Tesla Motors", 904.37, 753.92, R.drawable.tesla_logo, true));
tickers.add(new Ticker("GOOGL", "Alphabel Class A", 1845.90, 1845.90, R.drawable.google_logo, false));
return tickers;
}
}
Here is my class for data
package com.skorbr.stock_yandextest;
public class Ticker {
private String ticker;
private String tickerFull;
private double price;
private double priceDayAgo;
private int tickerLogo;
private boolean isFavourite;
public Ticker(String ticker, String tickerFull, double price, double priceDayAgo, int tickerLogo, boolean isFavourite) {
this.ticker = ticker;
this.tickerFull = tickerFull;
this.price = price;
this.priceDayAgo = priceDayAgo;
this.tickerLogo = tickerLogo;
this.isFavourite = isFavourite;
}
public String getTicker() {
return ticker;
}
public String getTickerFull() {
return tickerFull;
}
public double getPrice() {
return price;
}
public double getPriceDayAgo() {
return priceDayAgo;
}
public int getTickerLogo() {
return tickerLogo;
}
public boolean isFavourite() {
return isFavourite;
}
public void setFavourite(boolean favourite) {
isFavourite = favourite;
}
}
#Override
public void onBindViewHolder(#NonNull TickerViewHolder holder, int position) {
Ticker ticker = tickers.get(position);
holder.bind(ticker);
holder.itemView.setTag(ticker);
// add this line
holder.favouriteButton.setTag(ticker);
}
Or you can modify the onCreateViewHolder()
view.findViewById(R.id.button_favourite).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// instead of
onTickerClickListener.onFavouriteClick((Ticker) v.getTag());
// use
onTickerClickListener.onFavouriteClick((Ticker) view.getTag());
}
});

SharedPreferences Data spreads on every Fragment

I got a problem with the date of my SharedPreferences. I am using 5 Fragment wher you can dynamically add item to a RecyclerView. The Problem is that when ever I save my data on a particular fragment and reload the app the value that has been saved loads into every single Fragment of mine.It actually save the data to the Fragment it is on.I am using Gson to save my ArrayList of items
This is my Fragment (Fragment0 from 5 in total, the others are just copied and refactored)
package com.example.barryblack;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import static android.content.Context.MODE_PRIVATE;
public class FragmentPage0 extends Fragment {
private ExampleAdapter mAdapter;
private EditText editTask;
ArrayList<MyItem> items;
private Button insertbtn;
private Button stateButton;
private TextView taskText;
private String task;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable
Bundle savedInstanceState) {
CreateExampleList();
View view = inflater.inflate(R.layout.page_fragment0, container, false);
loadData();
RecyclerView recyclerView = view.findViewById(R.id.listRecyclerView);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemViewCacheSize(500);
mAdapter = new ExampleAdapter(items);
recyclerView.setAdapter(mAdapter);
taskText = view.findViewById(R.id.tv_country);
insertbtn = view.findViewById(R.id.button_insert);
editTask = view.findViewById(R.id.editTask);
stateButton = view.findViewById(R.id.tv_button);
insertbtn.setEnabled(false);
editTask.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String taskInput = editTask.getText().toString().trim();
insertbtn.setEnabled(!taskInput.isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
task = editTask.getText().toString().trim();
}
});
insertbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InsertItem();
SaveData();
editTask.setText(null);
}
});
return view;
}
private void SaveData() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("shared
preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(items);
editor.putString("task list", json);
editor.apply();
}
private void loadData() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("shared
preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list", null);
Type type = new TypeToken<ArrayList<MyItem>>() {
}.getType();
items = gson.fromJson(json, type);
if (items == null) {
items = new ArrayList();
}
}
public void InsertItem() {
items.add(new MyItem(task, stateButton));
mAdapter.notifyItemInserted(items.size());
}
private void CreateExampleList() {
items = new ArrayList<MyItem>();
}
ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder
viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
items.remove(viewHolder.getAdapterPosition());
mAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
SaveData();
}
};
}
This is my Adapter. I think the problem is inside the OnCreateViewHolder but im not quiet sure
package com.example.barryblack;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<MyItem> mExampleList;
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
private EditText topicName;
public Button mButton;
private int clicks = 1;
public static final String SHARED_PREFS = "sharedPrefs";
public static final String TOPIC = "topic";
public static final String CLICKS = "clicks";
public ExampleViewHolder(View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.tv_country);
mButton = itemView.findViewById(R.id.tv_button);
topicName = itemView.findViewById(R.id.editText);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicks++;
if (clicks % 2 == 0) {
mButton.setBackgroundResource(R.drawable.button_green);
}else
mButton.setBackgroundResource(R.drawable.button_red);
}
});
}
}
public ExampleAdapter(ArrayList<MyItem> exampleList) {
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
MyItem currentItem = mExampleList.get(position);
holder.mTextView.setText(currentItem.getTaskText());
}
#Override
public int getItemCount() {
return mExampleList.size();
}
}
Use this for your fragments. So every fragment has his own SharedPreferences
private static final String SHARED_PREFS_FRAGMENT_A = "fragmentA";
private static final String SHARED_PREFS_FRAGMENT_B = "fragmentB";
...
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(SHARED_PREFS_FRAGMENT_A , MODE_PRIVATE);

How to change GroupView background color on Expand in ExpandableListView?

I Have problem to change background color of GroupView on position..
According to My Code
when i press 1nd number GroupView then the color change of 1st number GroupView.
AND
when i press 2nd number GroupView then 1st number GroupView is color is Changed.
I Want to change GroupView Color on Postion Expand and Collapse.
ExpandableListViewAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.NumberPicker;
import android.widget.TextView;
import com.acase.clouds.cloudstailor.Models.ExpandableModel;
import com.acase.clouds.cloudstailor.R;
import java.util.List;
public class ExpandableListViewAdapter extends BaseExpandableListAdapter {
private Context context;
private LayoutInflater inflater;
private List<ExpandableModel> listDataGroup;
public ExpandableListViewAdapter(Context context, List<ExpandableModel> listDataGroup) {
this.context = context;
this.listDataGroup = listDataGroup;
this.inflater = LayoutInflater.from(context);
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return listDataGroup.get(groupPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return 1;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
ExpandableModel model = listDataGroup.get(groupPosition);
if (convertView == null) {
convertView = inflater.inflate(model.getLayoutId(), null);
}
switch (model.getType()) {
case AGE:
setNumberPicker(convertView, model);
break;
case STATE:
setNumberPicker(convertView, model);
break;
}
return convertView;
}
private void setNumberPicker(View convertView, final ExpandableModel model) {
NumberPicker numberPicker = convertView.findViewById(R.id.numberPicker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(99);
if (!model.getValue().isEmpty()) {
numberPicker.setValue(Integer.parseInt(model.getValue()));
}
// to change formate of number in numberpicker
numberPicker.setFormatter(new NumberPicker.Formatter() {
#Override
public String format(int i) {
return String.format("%02d", i);
}
});
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int i, int i1) {
model.setValue(i1 + "");
}
});
}
#Override
public int getChildrenCount(int groupPosition) {
return 1;
}
#Override
public Object getGroup(int groupPosition) {
return this.listDataGroup.get(groupPosition);
}
#Override
public int getGroupCount() {
return this.listDataGroup.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
// String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_row_group, null);
}
ExpandableModel model = listDataGroup.get(groupPosition);
TextView tv_title = convertView.findViewById(R.id.tv_title);
TextView tv_value = convertView.findViewById(R.id.tv_value);
tv_title.setText(model.getName());
tv_value.setText(model.getValue());
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
EditProfileActivity
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.acase.clouds.cloudstailor.Adapter.ExpandableListViewAdapter;
import com.acase.clouds.cloudstailor.Models.ExpandableModel;
import com.bumptech.glide.Glide;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class EditProfileActivity extends AppCompatActivity {
Toolbar toolbar;
ImageView profileimage;
TextView changephototext, textView;
RelativeLayout item;
private static final int PICK_IMAGE_REQUEST = 1;
public Uri path;
private ExpandableListView expandableListView;
private ExpandableListViewAdapter expandableListViewAdapter;
List<ExpandableModel> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
toolbar = findViewById(R.id.tool).findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Edit Profile");
profileimage = findViewById(R.id.Profile_Img);
profileimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fileChooser();
}
});
changephototext = findViewById(R.id.Change_Photo_Button);
changephototext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fileChooser();
}
});
// initializing the views
initViews();
// initializing the listeners
initListeners();
// initializing the objects
initObjects();
}
private void initViews() {
expandableListView = findViewById(R.id.expandableListView);
}
private void initListeners() {
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
ExpandableModel model = list.get(groupPosition);
Toast.makeText(EditProfileActivity.this, model.getName() + " clicked at " + childPosition, Toast.LENGTH_SHORT).show();
return false;
}
});
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
ExpandableModel model = list.get(groupPosition);
Toast.makeText(EditProfileActivity.this, model.getName() + " expanded", Toast.LENGTH_SHORT).show();
item = findViewById(R.id.Group);
item.setBackgroundResource(R.drawable.selectedlistback);
textView = findViewById(R.id.tv_title);
textView.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
}
});
// ExpandableListView Group collapsed listener
expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
ExpandableModel model = list.get(groupPosition);
Toast.makeText(EditProfileActivity.this, model.getName() + " collapsed", Toast.LENGTH_SHORT).show();
item = findViewById(R.id.Group);
item.setBackgroundResource(R.drawable.listback);
textView = findViewById(R.id.tv_title);
textView.setTextColor(getResources().getColor(R.color.colorAccent));
}
});
}
private void initObjects() {
ExpandableModel age = new ExpandableModel("AGE", "", ExpandableModel.ExpandableType.AGE, R.layout.list_row_child);
list.add(age);
ExpandableModel state = new ExpandableModel("STATE", "", ExpandableModel.ExpandableType.STATE, R.layout.list_row_child);
list.add(state);
expandableListViewAdapter = new ExpandableListViewAdapter(this, list);
expandableListView.setAdapter(expandableListViewAdapter);
}
private void fileChooser()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data.getData() != null)
{
path = data.getData();
Glide.with(this).load(path).into(profileimage);
path = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),path);
profileimage.setImageBitmap(bitmap);
}catch (IOException e){
e.printStackTrace();
}
}
}
}
Try add the following code inside getGroupView of your adapter:
if(isExpanded) {
convertView.setBackgroundResource(R.drawable.selectedlistback);
tv_title.setTextColor(context.getResources().getColor(R.color.colorPrimaryDark));
}else{
convertView.setBackgroundResource(R.drawable.listback);
tv_title.setTextColor(context.getResources().getColor(R.color.colorAccent));
}
and remove the listeners. Hope that helps!

Categories