I Am working on project where users recognizes text(OCR) and then see all their text(OCR) history in another activity
App Link : https://play.google.com/store/apps/details?id=com.thetechroot.vision
I added shared preference and recycle view,
but i am only getting the first Text that was recognized
Working :-
Users Recognize Text(OCR) in Textactivity, then to view users history of scanned text(OCR) the history is shown in different activity
How Can I Saved Textview From One Activity to diff activity, and show it into recycleview using shared preference
TEXTACTIVTY.JAVA
textRecognizer.processImage(image)
.addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
#Override
public void onSuccess(final FirebaseVisionText firebaseVisionText) {
translatelan(firebaseVisionText);
cd_text_re.setVisibility(View.VISIBLE);
spinnerlan.setVisibility(View.VISIBLE);
txtrecog.setText(firebaseVisionText.getText());
String th = SharedCommon.getSharedPreferencesString(getApplicationContext(), texthistory,firebaseVisionText.getText());
//int i = SharedCommon.getPreferencesInt(getApplicationContext(), key1,50);
final SharedCommon scth = new SharedCommon();
if (txtrecog.equals("")){
Toast.makeText(TextActivity.this, "Text: "+th, Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(TextActivity.this, "Text: "+th, Toast.LENGTH_SHORT).show();
scth.putSharedPreferencesString(getApplicationContext(), SharedCommon.texthistory, th);
}
/* SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", String.valueOf(txtrecog.getText()));
editor.putInt("idName", 1);
editor.apply();*/
drawtextvision(firebaseVisionText);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> values;
ArrayList personNames;
Context context;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView txtHeader;
public TextView txtFooter;
public View layout;
public ViewHolder(View v) {
super(v);
layout = v;
txtHeader = (TextView) v.findViewById(R.id.firstLine);
txtFooter = (TextView) v.findViewById(R.id.secondLine);
}
}
public void add(int position, String item) {
values.add(position, item);
notifyItemInserted(position);
}
public void remove(int position) {
values.remove(position);
notifyItemRemoved(position);
}
public MyAdapter(Context context, ArrayList personNames) {
this.context = context;
this.personNames = personNames;
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(List<String> myDataset) {
values = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
/*final String th = SharedCommon.getSharedPreferencesString(getApplicationContext(), texthistory,"");
*/
LayoutInflater inflater = LayoutInflater.from(
parent.getContext());
View v =
inflater.inflate(R.layout.layout_history_text, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final String name = values.get(position);
holder.txtHeader.setText(name);
holder.txtHeader.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
holder.txtFooter.setText("Footer: " + name);
}
});
//holder.txtFooter.setText("Footer: " + name);
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return values.size();
}
}
HISTORYACTIVITY.JAVA
public class AboutActivity extends AppCompatActivity {
/* WebView webView;*/
ProgressDialog mprogreeinternet;
String apppackagename = "com.thetechroot.vision";
int versionCode = BuildConfig.VERSION_CODE;
String versionName = BuildConfig.VERSION_NAME;
String appid = BuildConfig.APPLICATION_ID;
Button btnlimit;
WebView webview;
/* private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;*/
private RecyclerView recyclerView;
private MyAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
LinearLayout layouthide,layoutcredit;
int[] photos={R.drawable.logoam, R.drawable.iconshandwrit52,R.drawable.productsearch52,R.drawable.iconsqrcode52};
ImageButton arrdown,arrup,arrcre,arrcreup;
TextView txthistory;
TextView mItemDescription;
ImageButton mDescriptionImg,mupImg;
CardView cdhistory;
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
/* btnlimit = (Button) findViewById(R.id.btnlimit);*/
final String th = SharedCommon.getSharedPreferencesString(getApplicationContext(), texthistory,"");
// Toast.makeText(this, ""+th, Toast.LENGTH_SHORT).show();
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
// recyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
// Use the default animator
// recyclerView.setItemAnimator(new DefaultItemAnimator());
// you could add item decorators
// RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST);
// recyclerView.addItemDecoration(itemDecoration);
ArrayList<String> values = new ArrayList<String>();
/*for (int i = 0; i < 100; i++) {
values.add("Test" + i);
}*/
Toast.makeText(this, ""+String.valueOf(th), Toast.LENGTH_SHORT).show();
values.add(""+String.valueOf(th));
// specify an adapter (see also next example)
mAdapter = new MyAdapter(values);
recyclerView.setAdapter(mAdapter);
ItemTouchHelper.SimpleCallback simpleItemTouchCallback =
new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder
target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
// input.remove(viewHolder.getAdapterPosition());
mAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent startIntent = new Intent(AboutActivity.this, TextActivity.class);
startActivity(startIntent);
finish();
}
}
It's a position issue, you have to use setTag() and getTag(), check this
final String name = values.get(position);
**holder.txtFooter.setTag(name);**
holder.txtHeader.setText(name);
holder.txtHeader.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
**holder.txtFooter.setText("Footer: " + v.getTag());**
}
});
Here TEXTACTIVTY.JAVA you are using single string, so instead of appending it to previous strings in shared preference you are replacing the history. Ideally you should save Strings array and retrieve the same. Currently values have size one because it has only one string.
First use Sting Array. To save String Array in shared preferences do the following
StringBuilder sb = new StringBuilder();
for (int i = 0; i < playlists.length; i++) {
sb.append(playlists[i]).append(",");
}
prefsEditor.putString(PLAYLISTS, sb.toString());
Then when you get the String from SharedPreferences simply parse it like this:
String[] playlists = playlist.split(",");
Refer Put and get String array from shared preferences
And https://blog.fossasia.org/storing-a-data-list-in-phimpme-android/ for more.
Related
Hi like it says in the title im trying to make my recyclerview work but it always show empty on first load. Only when i change activity and come back it appear. The data is fetched on create but dont seem to get passed to the adapter.
So my question is : How to load data in recyclerview on first load ?
RecyclerViewFragment.java
private static final String TAG = "RecyclerViewFragment";
private static final String KEY_LAYOUT_MANAGER = "layoutManager";
private static final int SPAN_COUNT = 2;
private static final int DATASET_COUNT = 60;
public static ArrayList<String> arraylist_News = new ArrayList<String>();
public static ArrayList<String> arraylist_Thumbs = new ArrayList<String>();
public static ArrayList<String> arraylist_Links = new ArrayList<String>();
private static String URL = "https://mangascan.cc/";
public String titre;
public String name;
public String img;
public String lien;
private enum LayoutManagerType {
GRID_LAYOUT_MANAGER,
LINEAR_LAYOUT_MANAGER
}
protected LayoutManagerType mCurrentLayoutManagerType;
protected RadioButton mLinearLayoutRadioButton;
protected RadioButton mGridLayoutRadioButton;
protected RecyclerView mRecyclerView;
protected CustomAdapter mAdapter;
protected RecyclerView.LayoutManager mLayoutManager;
protected String[] mDataset;
protected String[] mDatasetName;
protected String[] mDatasetImg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize dataset, this data would usually come from a local content provider or
// remote server.
initDataset();
new getWebsite().execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.recycler_view_frag, container, false);
rootView.setTag(TAG);
// BEGIN_INCLUDE(initializeRecyclerView)
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
//mRecyclerView.setHasFixedSize(false);
// LinearLayoutManager is used here, this will layout the elements in a similar fashion
// to the way ListView would layout elements. The RecyclerView.LayoutManager defines how
// elements are laid out.
mLayoutManager = new LinearLayoutManager(getActivity());
mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
if (savedInstanceState != null) {
// Restore saved layout manager type.
mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState
.getSerializable(KEY_LAYOUT_MANAGER);
}
setRecyclerViewLayoutManager(mCurrentLayoutManagerType);
// END_INCLUDE(initializeRecyclerView)
// getParentFragmentManager().beginTransaction().detach(this).attach(this).commit();
mAdapter = new CustomAdapter(getActivity(),mDataset,mDatasetName,mDatasetImg);
// Set CustomAdapter as the adapter for RecyclerView.
mRecyclerView.setAdapter(mAdapter);
mAdapter.ResetValues(mDataset);
// mAdapter.notifyItemRangeChanged(0, arraylist_News.size());
return rootView;
}
/**
* Set RecyclerView's LayoutManager to the one given.
*
* #param layoutManagerType Type of layout manager to switch to.
*/
public void setRecyclerViewLayoutManager(LayoutManagerType layoutManagerType) {
int scrollPosition = 0;
// If a layout manager has already been set, get current scroll position.
if (mRecyclerView.getLayoutManager() != null) {
scrollPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager())
.findFirstCompletelyVisibleItemPosition();
}
mLayoutManager = new LinearLayoutManager(getActivity(),RecyclerView.HORIZONTAL, false);
mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.scrollToPosition(scrollPosition);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save currently selected layout manager.
savedInstanceState.putSerializable(KEY_LAYOUT_MANAGER, mCurrentLayoutManagerType);
super.onSaveInstanceState(savedInstanceState);
}
/**
* Generates Strings for RecyclerView's adapter. This data would usually come
* from a local content provider or remote server.
*/
private void initDataset() {
mDataset = new String[arraylist_News.size()];
for (int i = 0; i < arraylist_News.size(); i++) {
mDataset[i] = String.valueOf(arraylist_News.get(i));
}
mDatasetName = new String[arraylist_Links.size()];
for (int i = 0; i < arraylist_Links.size(); i++) {
mDatasetName[i] = String.valueOf(arraylist_Links.get(i));
}
mDatasetImg = new String[arraylist_Thumbs.size()];
for (int i = 0; i < arraylist_Thumbs.size(); i++) {
mDatasetImg[i] = String.valueOf(arraylist_Thumbs.get(i));
}
}
private class getWebsite extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
arraylist_News.clear();
arraylist_Thumbs.clear();
arraylist_Links.clear();
}
private static final String userAgent = "Mozilla/5.0 (jsoup)";
#Override
protected Void doInBackground(Void... voids) {
try {
Document doc = Jsoup.connect(URL).userAgent(userAgent).timeout(12000).get();
//scan-mangas get news script
Element news = doc.select(".hot-thumbnails").first();
// Log.d("jSoup", news.toString());
for (Element e : news.select(".span3")){
titre = e.select("p").text().toString();
//Log.d("okk", titre);
img = e.select("img").attr("src");
lien = e.select("a").attr("href");
name = e.getElementsByClass("label label-warning").text().toString();
arraylist_News.add((titre));
arraylist_Thumbs.add(img);
arraylist_Links.add(name);
}
for (String str_Agil : arraylist_Thumbs) // using foreach
{
Log.e("NEWS:: " , str_Agil);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// This code will always run on the UI thread, therefore is safe to modify UI elements.
((CustomAdapter)mRecyclerView.getAdapter()).ResetValues(mDataset);
mAdapter.notifyDataSetChanged();
mAdapter.notifyItemRangeInserted(0, arraylist_News.size());
//System.out.println("update ui");
mRecyclerView.removeAllViews();
}
});
}
}
CustomAdapter.java
private String[] mDataSet;
private String[] mDataSetName;
private String[] mDataSetImg;
Context context;
// BEGIN_INCLUDE(recyclerViewSampleViewHolder)
/**
* Provide a reference to the type of views that you are using (custom ViewHolder)
*/
public static class ViewHolder extends RecyclerView.ViewHolder {
private final TextView textView;
private final TextView textView2;
private final ImageView imgView;
public ViewHolder(View v) {
super(v);
// Define click listener for the ViewHolder's View.
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "Element " + getAdapterPosition() + " clicked.");
}
});
textView = (TextView) v.findViewById(R.id.textView);
textView2 = (TextView) v.findViewById(R.id.textView2);
imgView = (ImageView) v.findViewById(R.id.thumbnail);
}
public TextView getTextView() {
return textView;
}
public TextView getTextView2() {
return textView2;
}
}
// END_INCLUDE(recyclerViewSampleViewHolder)
/**
* Initialize the dataset of the Adapter.
*
* #param dataSet String[] containing the data to populate views to be used by RecyclerView.
*/
public CustomAdapter(Context context, String[] dataSet, String[] dataSet1, String[] dataSet2) {
mDataSet = dataSet;
mDataSetName = dataSet1;
mDataSetImg = dataSet2;
this.context = context;
}
// BEGIN_INCLUDE(recyclerViewOnCreateViewHolder)
// Create new views (invoked by the layout manager)
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
// Create a new view.
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.text_row_item, viewGroup, false);
return new ViewHolder(v);
}
// END_INCLUDE(recyclerViewOnCreateViewHolder)
// BEGIN_INCLUDE(recyclerViewOnBindViewHolder)
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
Log.d(TAG, mDataSet[position] + " set.");
// Get element from your dataset at this position and replace the contents of the view
// with that element
viewHolder.getTextView().setText(mDataSet[position]);
viewHolder.getTextView2().setText(mDataSetName[position]);
Picasso.with(viewHolder.imgView.getContext()).load(mDataSetImg[position]).into(viewHolder.imgView);
}
// END_INCLUDE(recyclerViewOnBindViewHolder)
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataSet.length;
}
public void ResetValues(String[] dataSet)
{
notifyDataSetChanged();
}
Thanks fellows devs
Bump
heres the full project so you can test it : https://drive.google.com/file/d/15rx7vELGiwlIfxZH3Np6Joycrsf4PxO_/view?usp=sharing
i been struggling for three months on this please help
This solution based on code in Google drive
Goto PageViewFragment.java and change this
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// This code will always run on the UI thread, therefore is safe to modify UI elements.
if(pageAdapter==null){
pageAdapter =new PageAdapter(getActivity(), mDataset);
mRecyclerView.setAdapter(pageAdapter);
} else {
pageAdapter.notifyDataSetChanged();
Log.d("dataset", "changed");
}
}
});
To this
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// This code will always run on the UI thread, therefore is safe to modify UI elements.
initDataset();
pageAdapter = new PageAdapter(getActivity(), mDataset);
mRecyclerView.setAdapter(pageAdapter);
}
});
I have a a view where a bunch of my Sqlite data is displayed. I recently added a column to my database called location_position. I have added a button to my relative layout so that when its clicked I want the data inside to be sorted in ascending format. I have tried following a few examples online but with the way my app is setup im struggling tom get it to work.
I have a routeView.java class and a routeAdapter
I would really apreciate if someone can show me how to have the content sorted when the button is clicked, or any resources with similar solutions
public class RouteView extends AppCompatActivity {
RecyclerView recyclerView;
routeAdapter routeAdapter;
ArrayList<String> location_id, location_name, location_county, location_description, location_route, location_position;
MyDatabaseHelper myDB;
Button createPDFButton, btnNorth, southBtn;
Context mContext = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route_view);
Button southBtn = findViewById(R.id.button_south);
southBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Collections.sort(ArrayList);
}
});
// btnRemove = findViewById(R.id.btnRemove);
recyclerView = findViewById(R.id.recyclerView);
myDB = new MyDatabaseHelper(this);
createPDFButton = findViewById(R.id.createPDFButton);
location_id = new ArrayList<>();
location_name = new ArrayList<>();
location_county = new ArrayList<>();
location_description = new ArrayList<>();
location_route = new ArrayList<>();
location_position = new ArrayList<>();
Cursor cursor = myDB.readAllData();
createPDFButton.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View v) {
if (UserActivity.checkAppPermission(RouteView.this, "android.permission.WRITE_EXTERNAL_STORAGE", 1)){
generatePDF(recyclerView);
}
}
});
while (cursor.moveToNext()){
if(cursor.getString(4).equals("1")) {
location_id.add(cursor.getString(0));
location_name.add(cursor.getString(1));
location_county.add(cursor.getString(2));
location_description.add(cursor.getString(3));
location_route.add(cursor.getString(4));
location_position.add(cursor.getString(8));
}
}
routeAdapter = new routeAdapter(this, this, location_id, location_name, location_county, location_description, location_route, location_position);
recyclerView.setAdapter(routeAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
and this is the route adapter class
public class routeAdapter extends RecyclerView.Adapter<routeAdapter.MyViewHolder> {
//private final ClickListener listener;
private Context context;
MyDatabaseHelper myDB;
Activity activity;
private ArrayList location_id, location_name, location_county, location_description, location_position, location_route, location_image_url;
Button btnRemove;
String id, name, county, description;
routeAdapter(Activity activity, Context context, ArrayList location_id, ArrayList location_name, ArrayList location_county,
ArrayList location_description, ArrayList location_route, ArrayList location_position){
this.activity = activity;
this.context = context;
this.location_id = location_id;
this.location_name = location_name;
this.location_county = location_county;
this.location_description = location_description;
this.location_position = location_position;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.route_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
holder.location_id_txt.setText(String.valueOf(location_id.get(position)));
holder.location_name_txt.setText(String.valueOf(location_name.get(position)));
holder.location_county_txt.setText(String.valueOf(location_county.get(position)));
holder.location_description_txt.setText(String.valueOf(location_description.get(position)));
holder.mainLayout2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, RouteView.class);
intent.putExtra("id", String.valueOf(location_id.get(position)));
intent.putExtra("name", String.valueOf(location_name.get(position)));
intent.putExtra("county", String.valueOf(location_county.get(position)));
intent.putExtra("description",String.valueOf(location_description.get(position)));
activity.startActivityForResult(intent, 2);
}
});
}
#Override
public int getItemCount() { return location_id.size(); }
class MyViewHolder extends RecyclerView.ViewHolder {
TextView location_id_txt, location_name_txt, location_county_txt, location_description_txt, added_to_route_txt, location_image_url;
LinearLayout mainLayout2;
Button btnRemove;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
location_id_txt = itemView.findViewById(R.id.location_id_txt);
location_name_txt = itemView.findViewById(R.id.location_name_txt);
location_county_txt = itemView.findViewById(R.id.location_county_txt);
location_description_txt = itemView.findViewById(R.id.location_description_txt);
mainLayout2 = itemView.findViewById(R.id.mainLayout2);
}
}
}
This is the basic concept:
On clicking a button or whatever to sort the things in a specific order, you sort the ArrayList that contains the values reflected in the RecyclerView. Then you update/ recreate the RecyclerView to register the changes.
I tried to make an app in which I made a recycler View of Array List Of items and I want that when I will click on particular item of Array List the it should open a activity in which I could add some text with edit text and again if I want to open another item of Array List so it should open the same activity but not the previous saved data .
I want to add different data in each list of items. but its not happening for every list of items the same saved data is loading in the activity....
is there any solution..
this is second activity..
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.student_list);
loadData();
toolbar = findViewById(R.id.toolbar);
bundle = getIntent().getExtras();
String subName = bundle.getString("Subject Name");
if (bundle != null) {
toolbar.setTitle(subName);
}
fabButton();
buildRecyclerView();
}
private void buildRecyclerView() {
recyclerView = findViewById(R.id.recyclerView2);
recyclerView.hasFixedSize();
layoutManager = new LinearLayoutManager(StudentListActivity.this);
rAdapter = new AdapterForStudentList(listOfNames);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(rAdapter);
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);
}
public void insertData(String text, String t1, String t2) {
ListOfNames lt = new ListOfNames(text, t1, t2);
listOfNames.add(lt);
rAdapter.notifyDataSetChanged();
}
public void saveData() {
sharedPreferences = getSharedPreferences("SHARED PREF", MODE_PRIVATE);
editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(listOfNames);
editor.putString("text", json);
editor.apply();
}
public void loadData() {
sharedPreferences = getSharedPreferences("SHARED PREF", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("text", null);
Type type = new TypeToken<ArrayList<ListOfNames>>() {
}.getType();
listOfNames = gson.fromJson(json, type);
if (listOfNames == null) {
listOfNames = new ArrayList<>();
}
}
ListOfNames deletedItem = null;
ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
#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) {
final int position = viewHolder.getAdapterPosition();
String name = listOfNames.get(position).getStudentName();
deletedItem = listOfNames.get(position);
listOfNames.remove(deletedItem);
sharedPreferences = getSharedPreferences("SHARED PREF", MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.remove("text");
saveData();
editor.apply();
rAdapter.notifyItemRemoved(position);
Snackbar.make(recyclerView, name + "Deleted", Snackbar.LENGTH_LONG)
.setAction("Undo", new View.OnClickListener() {
#Override
public void onClick(View v) {
listOfNames.add(position, deletedItem);
rAdapter.notifyItemInserted(position);
saveData();
}
}).show();
}
#Override
public void onChildDrawOver(#NonNull Canvas c, #NonNull RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
new RecyclerViewSwipeDecorator.Builder(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
.addSwipeLeftBackgroundColor(ContextCompat.getColor(StudentListActivity.this, R.color.my_background))
.addSwipeLeftActionIcon(R.drawable.ic_delete_black_24dp)
.create()
.decorate();
super.onChildDrawOver(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
};
public void fabButton() {
FloatingActionButton floatingActionButton = findViewById(R.id.fab2);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder b = new AlertDialog.Builder(StudentListActivity.this);
View view = getLayoutInflater().inflate(R.layout.dialogbox_frontpage, null);
final EditText editText = view.findViewById(R.id.editText);
b.setView(view);
b.setTitle("Student name");
b.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String text = editText.getText().toString();
if (text.isEmpty()) {
Toast.makeText(StudentListActivity.this, "Please add subject name", Toast.LENGTH_SHORT).show();
} else {
insertData(text, t1, t2);
saveData();
}
}
});
b.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
b.setCancelable(false);
b.show();
}
});
}
}
**MainActivity**
`public class ScrollingActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private AdaptreForRecycler adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<ExampleItem> mExampleList;
RecyclerView.ViewHolder viewHolder;
private Gson gson;
private String json;
private Type type;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
EditText editText;
private ExampleItem ex;
public static final String t2 = "new";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrolling);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
loadData();
buildRecyclerView();
editText = findViewById(R.id.editText);
fabButoonClick();
}
public void saveData() {
sharedPreferences = getSharedPreferences("SHARED_PREFS", MODE_PRIVATE);
editor = sharedPreferences.edit();
gson = new Gson();
json = gson.toJson(mExampleList);
editor.putString("text", json);
editor.apply();
}
public void loadData() {
sharedPreferences = getSharedPreferences("SHARED_PREFS", MODE_PRIVATE);
gson = new Gson();
json = sharedPreferences.getString("text", null);
type = new TypeToken<ArrayList<ExampleItem>>() {
}.getType();
mExampleList = gson.fromJson(json, type);
if (mExampleList == null) {
mExampleList = new ArrayList<>();
}
}
public void insertItem(String text, String t2) {
ex = new ExampleItem(text, t2);
mExampleList.add(ex);
adapter.notifyDataSetChanged();
}
ExampleItem deletedIndex = null;
ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
#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) {
final int position = viewHolder.getAdapterPosition();
String name = mExampleList.get(position).getText1();
deletedIndex = (mExampleList.get(position));
mExampleList.remove(position);
sharedPreferences = getSharedPreferences("SHARED_PREFS", MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.remove("text");
saveData();
editor.apply();
adapter.notifyItemRemoved(position);
Snackbar.make(recyclerView, name + " Deleted", Snackbar.LENGTH_LONG)
.setAction("Undo", new View.OnClickListener() {
#Override
public void onClick(View v) {
mExampleList.add(position, deletedIndex);
adapter.notifyItemInserted(position);
saveData();
}
}).show();
}
#Override
public void onChildDraw(#NonNull Canvas c, #NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
new RecyclerViewSwipeDecorator.Builder(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
.addSwipeLeftBackgroundColor(ContextCompat.getColor(ScrollingActivity.this, R.color.my_background))
.addSwipeLeftActionIcon(R.drawable.ic_delete_black_24dp)
.create()
.decorate();
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
};
private void buildRecyclerView() {
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(ScrollingActivity.this);
adapter = new AdaptreForRecycler(mExampleList);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new AdaptreForRecycler.OnItemCLickListener() {
#Override
public void onItemClick(int position) {
Intent i =new Intent(ScrollingActivity.this,StudentListActivity.class);
i.putExtra("Subject Name",mExampleList.get(position).getText1());
startActivity(i);
}
});
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);
}
public void fabButoonClick() {
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder b = new AlertDialog.Builder(ScrollingActivity.this);
View mview = getLayoutInflater().inflate(R.layout.dialogbox_frontpage, null);
final EditText editText = mview.findViewById(R.id.editText);
b.setView(mview);
b.setTitle("Add subject name");
b.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
b.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String text = editText.getText().toString();
if (text.isEmpty()) {
Toast.makeText(ScrollingActivity.this, "Please add subject name", Toast.LENGTH_SHORT).show();
} else {
insertItem(text, t2);
saveData();
}
}
});
b.setCancelable(false);
b.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_scrolling, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}AdaptreOfFirstActivity`
public class AdaptreForRecycler extends RecyclerView.Adapter<AdaptreForRecycler.ProgrammingViewHolder> {
private OnItemCLickListener mListener;
public interface OnItemCLickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemCLickListener listener) {
mListener = listener;
}
private ArrayList<ExampleItem> mExampleList;
public class ProgrammingViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView1, mTextView2;
public ProgrammingViewHolder(#NonNull View itemView, final OnItemCLickListener listener) {
super(itemView);
mTextView1 = itemView.findViewById(R.id.tv1);
mTextView2 = itemView.findViewById(R.id.tv2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION)
listener.onItemClick(position);
}
}
});
}
}
public AdaptreForRecycler(ArrayList<ExampleItem> exampleList) {
mExampleList = exampleList;
}
#NonNull
#Override
public AdaptreForRecycler.ProgrammingViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_item_layout, parent, false);
return new ProgrammingViewHolder(view, mListener);
}
#Override
public void onBindViewHolder(#NonNull AdaptreForRecycler.ProgrammingViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
holder.mTextView1.setText(currentItem.getText1());
holder.mTextView2.setText(currentItem.getText2());
}
#Override
public int getItemCount() {
return mExampleList.size();
}
} AdaptreForSecondActivity
public class AdapterForStudentList extends RecyclerView.Adapter<AdapterForStudentList.StudentViewHolder> {
private ArrayList<ListOfNames> mListOfNames;
public static class StudentViewHolder extends RecyclerView.ViewHolder {
public TextView studentName, attendence, percentage;
public StudentViewHolder(#NonNull View itemView) {
super(itemView);
studentName = itemView.findViewById(R.id.studentName);
attendence = itemView.findViewById(R.id.attendence);
percentage = itemView.findViewById(R.id.percentage);
}
}
public AdapterForStudentList(ArrayList<ListOfNames> listOfNames) {
mListOfNames = listOfNames;
}
#NonNull
#Override
public StudentViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.check_box_cardview, parent, false);
return new StudentViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull StudentViewHolder holder, int position) {
ListOfNames currentItems = mListOfNames.get(position);
holder.studentName.setText(currentItems.getStudentName());
holder.attendence.setText(currentItems.getAttendent());
holder.percentage.setText(currentItems.getPercetage());
}
#Override
public int getItemCount() {
return mListOfNames.size();
}
}
Now I saw that you did what I said in my first original answer, I compliment you for it.
Also, this thread/post can end here seeing that you already implemented the onClick for RecyclerView. I'd appreciate it if you mark my answer as the solution.
But of course, you raised another problem which is:
I want to add different data in each list of items. but its not
happening for every list of items the same saved data is loading in
the activity...
That's because you're loading and also saving with the same key:
editor.putString("text", json);
editor.apply();
See there? You were loading and saving to the key "text" in each subject. (You mentioned that you have a list of subjects hence I used the word subject)
I suggest you create a means to change the key for each different subject. In this case, your subject's name can be the key instead of plain "text".
I also suggest you to use a private static final String variable for "text" and also make it more clear. A key called "text" is a bit ambiguous don't you think?
Now I will post the modified code part of your StudentListActivity, I encourage you to analyse it and paste it to your code. I'm sure it will work now.
Modified part in StudentListActivity
// Added a string variable here as key for saving/loading your data
String subName; // I kept your naming the same which is 'subName'
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.student_list);
// I placed this bit of code above loadData() now that we
// use subName as the key
// Or else loadData() will use the initial value of
// subName which is going to be null first
bundle = getIntent().getExtras();
subName = bundle.getString("Subject Name");
if (bundle != null) {
toolbar.setTitle(subName);setTitle(subName);
}
loadData();
toolbar = findViewById(R.id.toolbar);
fabButton();
buildRecyclerView();
}
// Other code... Which in your code are:
// private void buildRecyclerView() { ... }
// public void insertData(String text, String t1, String t2) { ... }
public void saveData() {
sharedPreferences = getSharedPreferences("SHARED PREF", MODE_PRIVATE);
editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(listOfNames);
// Now here use the name of your subject as key
// Which is of course the variable 'subName'
editor.putString(subName, json);
editor.apply();
}
public void loadData() {
sharedPreferences = getSharedPreferences("SHARED PREF", MODE_PRIVATE);
Gson gson = new Gson();
// Same here
// Use 'subName' as key
String json = sharedPreferences.getString(subName, null);
Type type = new TypeToken<ArrayList<ListOfNames>>() {
}.getType();
listOfNames = gson.fromJson(json, type);
if (listOfNames == null) {
listOfNames = new ArrayList<>();
}
}
// Other code ...
By the way, I tried making the layouts myself in order to test your application and I noticed something: I guess you have an EditText inside your dialogbox_frontpage.xml file. And you still wrote a code to get the view in to your ScrollingActivity which is unnecessary. In fact, you re-defined it inside the fab's onClick method. You can remove that global variable.
Last notes: This is just a suggestion but you could try and learn about the Singleton pattern. Use that pattern to save your data.
Also, SharedPreferences is not really a good idea to save huge amount of data. So I also encourage you to try to look up Room databases.
I hope your program works now and as always, happy coding! (This has been a very long answer, hahaha)
Original answer (modified it a bit)
I suggest to create an interface that will pass the position of the clicked item because we only care about the position of the item to be able to do something to it. Besides, it's better that way so that we can put in the activity the code to be executed when an item has been clicked.
This is how the interface should look like:
public interface OnItemClickListener {
void onItemClick(int position);
}
Add a new variable inside your adapter, that is, the OnItemClickListener:
private OnItemCLickListener listener;
You could either define its implementation by implementing it to the activity or pass its implementation by creating another method called addOnItemClickListener in to your adapter:
addOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
Then inside your onBindViewHolder method, get the layout of the item from the ViewHolder and set its onClick listener and finally inside its onClick method, call your interface's method onItemClick inside it and pass the position there. Like this:
#Override
public void onBindViewHolder(#NonNull CustomRecyclerView.ViewHolder holder, final int position) {
holder.layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onItemClick(position);
}
});
}
Edit: Explanation on why I set the listener inside the onBindViewHolder method
The itemView or the View we get from the constructor of the ViewHolder depends on the View returned by the LayoutInflater inside your onCreateViewHolder. Hence, the layout resource you're passing in the inflate method, whatever the main layout you're using there (e.g. ConstraintLayout, LinearLayout, it can also be a TextView, Button, etc.), will be the View returned. To test this, try and copy/paste this simple line of code in your onCreateViewHolder then run your app and check Logcat:
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.YOUR_LAYOUT_HERE, parent, false);
Log.i("View", view.getClass().getSimpleName()); // Logs the main view in our layout
return new YourCustomViewHolderHere(view);
}
The ViewHolder is only responsible for getting our views because using the findViewById method is an extensive task if we do it inside onBindViewHolder so we don't do it there because it'll slow down the performance of our application.
We do all settings like changing the texts of the TextViews for example or setting onClick listeners inside the onBindViewHolder to avoid creating unnecessary complexity in our code. We don't want codes floating around now, would we?
Also, the Observer pattern is quite dangerous.
There was a talk in an Android Conference, I don't remember which, that talked about RecyclerView. Do you know why it's called like that? Because it recycles views. (It needs a proper explanation how they recycle views so I won't be covering it here. I think you can find it on YouTube if you search for "Android Conference RecyclerView", it's quite long, maybe around an hour, but it's worth to watch it.)
The Observer pattern (i.e. Listener) may cause memory leaks in which will affect our application's performance. Hence, it's better to set it up inside our onBindViewHolder method because whenever we scroll down or up on our RecyclerView, it'll recycle views and we risk on creating multiple instances of the same listener inside the ViewHolder.
According to Wikipedia on Observer pattern:
The observer pattern can cause memory leaks, known as the lapsed
listener problem, because in basic implementation it requires both
explicit registration and explicit deregistration, as in the dispose
pattern, because the subject holds strong references to the observers,
keeping them alive. This can be prevented by the subject holding weak
references to the observers.
Another way to set an onClick is inside onCreateViewHolder but the catch is you don't have a way on knowing which item was clicked.
I hope this answers your question in the comment.
I'm trying to load thumbnail images in a ImageView contained in a RecyclerAdapter Picasso.with(context).load(stringUrl).into(imageView); but this requires a Context. From the RecyclerAdapter is it possible to get the Context of my app's MainActivity? Do I want to do this, or should I be loading the image elsewhere?
These are my classes. The RecyclerAdapater doesn't compile, of course, but it represents what I'm trying to do.
MainActivity:
public class MainActivity extends AppCompatActivity implements MainScreenContract.View {
ArrayList<String> list;
// Objects for RecyclerView
private RecyclerView recyclerView;
private RecyclerView.Adapter recyclerAdapter;
private RecyclerView.LayoutManager recyclerLayoutManager;
#Inject
MainScreenPresenter mainPresenter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Timber.plant(new Timber.DebugTree() {
// Add the line number to the tag
#Override
protected String createStackElementTag(StackTraceElement element) {
return super.createStackElementTag(element) + ':' + element.getLineNumber();
}
});
// RecyclerView implementation
recyclerView = (RecyclerView) findViewById(R.id.my_list);
// set to true because all images will be the same size
recyclerView.setHasFixedSize(true);
recyclerLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerLayoutManager);
DaggerMainScreenComponent.builder()
.netComponent(((App) getApplicationContext()).getNetComponent())
.mainScreenModule(new MainScreenModule(this))
.build().inject(this);
//Call the method in MainPresenter to make Network Request
mainPresenter.loadVideo();
}
#Override
public void showVideos(Video video){
// Loop through the posts, get the title of the post, and add it to our list object
// TODO: Simplify these references with a variable?
for(int i = 0; i < video.getResults().size(); i++){
// TODO: add second for loop, or simplyfy and get rid of Video object
list.add(video.getResults().get(i).getSiteDetailUrl());
//list.add(video.get(i).getSiteDetailUrl());
Timber.d("List item " + i + " = " + list.get(i));
}
// RecyclerView implementation
recyclerAdapter = new MainScreenRecyclerAdapter(list);
recyclerView.setAdapter(recyclerAdapter);
}
#Override
public void showError(String message){
// Show error message text as a Toast message
Toast.makeText(getApplicationContext(), "Error" + message, Toast.LENGTH_SHORT).show();
Timber.e("Error: " + message);
}
#Override
public void showComplete(){
// Show completed Toast message
Toast.makeText(getApplicationContext(), "Complete", Toast.LENGTH_SHORT).show();
}
}
RecyclerAdapter:
public class MainScreenRecyclerAdapter extends RecyclerView.Adapter<MainScreenRecyclerAdapter.ViewHolder> {
private List<String> dataset;
public static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public ViewHolder(ImageView v) {
super(v);
imageView = v;
}
}
// TODO: Should I make the list contain Video/Result objects and pull the data from that?
public MainScreenRecyclerAdapter(List<String> dataset) {
dataset = dataset;
}
// Create new views
#Override
public MainScreenRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
ImageView v = (ImageView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.thumbnail_view, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from dataset at this position
// - replace the contents of hte view with that element
// TODO: Call to picasso to load image into holder.imageView
String imageUrl = dataset.get(position);
Timber.d("Image URL: " + imageUrl);
ImageView view = holder.imageView;
Picasso.with(MainActivity.context).load(imageUrl).into(view);
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return dataset.size();
}
}
Thanks!
you need to pass the context as a constructor argument and then use this context
private Context mContext;
public MainScreenRecyclerAdapter (Context context) {
mContext = context;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String imageUrl = dataset.get(position);
Timber.d("Image URL: " + imageUrl);
ImageView view = holder.imageView;
Picasso.with(MainActivity.context).load(imageUrl).into(view);
}
I have a question about passing clicked cardview data to activity, and here the full story :
I have an Activity called "Details", which contains 2 TextViews in it's layout, Title & Description .
I have setup a fragment ( tab_1 ) which contain the recyclerview codes and the the items data, each item of those contain : title & description .
What i want :
When the user click the item, it will open the Details Activity, and change Details layout title, with clicked item title, and the same for description .
I've manged to create the other activity as an example, and made intent to start it, plus adding "addOnTouchlistener" thanks to Stackoverflow, i've found the way to make it .
So, how to make this alive? I've tried many ways of the available answers on Stackoverflow, but all of them not working, or not related to my request .
Here are my files :
itemsdata.java :
public class itemsdata {
int CatPic;
String title;
String Descr;
int Exapnd;
int expand_no;
tab_1.java ( fragment )
public class tab_1 extends Fragment implements SearchView.OnQueryTextListener {
private RecyclerView mRecyclerView;
public RecyclingViewAdapter adapter;
private Activity context;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.tab_1, container, false);
mRecyclerView = (RecyclerView)layout.findViewById(R.id.recycler_view);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener
(getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent i = new Intent(view.getContext(), DetailsActivity.class);
view.getContext().startActivity(i);
}
}));
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new RecyclingViewAdapter(getActivity(),Listed());
mRecyclerView.setAdapter(adapter);
return layout;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextChange(String query) {
final List<itemsdata> filteredModelList = filter(Listed(), query);
adapter.animateTo(filteredModelList);
mRecyclerView.scrollToPosition(0);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
private List<itemsdata> filter(List<itemsdata> models, String query) {
query = query.toLowerCase();
final List<itemsdata> filteredModelList = new ArrayList<>();
for (itemsdata model : models) {
final String text = model.title.toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
public List<itemsdata> Listed()
{
//Titles Strings
String sys_title1 = getString(R.string.system_item_title_1);
String sys_title2 = getString(R.string.system_item_title_2);
String sys_title3 = getString(R.string.system_item_title_3);
//Description Strings
String sys_descr1 = getString(R.string.system_item_desc_1);
String sys_descr2 = getString(R.string.system_item_desc_2);
String sys_descr3 = getString(R.string.system_item_desc_3);
//Adding New Cards
List<itemsdata> data = new ArrayList<>();
//Categories Icons New Items ** Make It The Same
int[] icons = {
R.drawable.facebook_icon ,
R.drawable.twitter_icon ,
R.drawable.twitter_icon
};
//Expand Button New Items
int[] expandbutton = {
R.drawable.expanded ,
R.drawable.expanded ,
R.drawable.expanded
};
//UnExpand Button New Items
int[] unexpandbutton = {
R.drawable.ca_expand ,
R.drawable.ca_expand ,
R.drawable.ca_expand
};
//Titles New Items
String[] titles = {
sys_title1 ,
sys_title2 ,
sys_title3
};
//Description New Items
String[] Description = {
sys_descr1 ,
sys_descr2 ,
sys_descr3
};
for(int i = 0;i<titles.length && i < icons.length && i < Description.length && i < unexpandbutton.length && i < expandbutton.length ; i++)
{
itemsdata current = new itemsdata();
current.CatPic = icons[i];
current.title = titles[i];
current.Descr = Description[i];
current.expand_no = unexpandbutton[i];
current.Exapnd = expandbutton[i];
data.add(current);
}
return data;
}
}
Details Activity :
public class DetailsActivity extends AppCompatActivity{
TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
title = (TextView)findViewById(R.id.details_title);
}
EDIT : I've made it, i have added a button which open the fragment, and passed the data, in the Adapter, but i want it via tab_1.java, not the Adapter, i mean i want to click on the item to open the fragment, not on a button, here a snap from my Adapter code ( i've added it in OnBindViewHolder )
I've setup a OnClick and implemented the Vew.setOnClick ..etc, but when i click the item, nothing happen.
#Override
public void onBindViewHolder(final MyRecycleViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(),DetailsActivity.class);
v.getContext().startActivity(i);
}
});
//Referencing Data
final itemsdata currentobject = mdata.get(position);
//Referencing Items
holder.ProbTitle.setText(currentobject.title);
holder.ProbDescr.setText(currentobject.Descr);
holder.CategoryPic.setImageResource(currentobject.CatPic);
holder.ExpandButton.setImageResource(currentobject.Exapnd);
holder.ExpandNoButton.setImageResource(currentobject.expand_no);
//What Happen When You Click Expand Button .
holder.ExpandButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), DetailsActivity.class);
i.putExtra("TitleKey",holder.ProbTitle.getText().toString());
v.getContext().startActivity(i);
}
}
);
public static class MyRecycleViewHolder extends RecyclerView.ViewHolder
{
SwipeLayout swipeLayout;
//Defining Items .
TextView ProbTitle;
ImageButton ExpandButton;
TextView ProbDescr;
ImageButton ExpandNoButton;
ImageView CategoryPic;
/*
TextView Card_Star;
TextView Card_UnStar;
*/
TextView Card_Share;
//Referencing Resources
public MyRecycleViewHolder(final View itemView) {
super(itemView);
ProbTitle = (TextView) itemView.findViewById(R.id.prob_title);
CategoryPic = (ImageView) itemView.findViewById(R.id.cat_pic);
ProbDescr = (TextView) itemView.findViewById(R.id.prob_descr);
ExpandButton = (ImageButton) itemView.findViewById(R.id.expand_button);
ExpandNoButton = (ImageButton) itemView.findViewById(R.id.expand_no_button);
/*
Card_Star = (TextView) itemView.findViewById(R.id.card_star);
Card_UnStar = (TextView) itemView.findViewById(R.id.card_unstar);
*/
Card_Share = (TextView) itemView.findViewById(R.id.card_share);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
}
create an Interface inside your adapter containing methods. And while implementing your Adapter, those methods will be implemented in your activity and you can perform whatever action you want.
public class Adapter extends RecyclerView.Adapter<MyRecycleViewHolder> {
public interface Callbacks {
public void onButtonClicked(String titleKey);
}
private Callbacks mCallbacks;
public Adapter() {
}
#Override
public MyRecycleViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_details, null);
return new MyRecycleViewHolder(v);
}
#Override
public void onBindViewHolder(final MyRecycleViewHolder holder, final int i) {
holder.ExpandButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCallbacks != null) {
mCallbacks.onButtonClicked(holder.ProbTitle.getText().toString());
}
}
});
}
#Override
public int getItemCount() {
return;
}
public void setCallbacks(Callbacks callbacks) {
this.mCallbacks = callbacks;
}
}
you may try do this on your onItemClick()
Intent i = new Intent(view.getContext(), DetailsActivity.class);
i.putExtra("title", yourTitle);
i.putExtra("description", yourDescription);
view.getContext().startActivity(i);
and when oncreate in your DetailActivity,do this
String title = getIntent().getStringExtra("title");
String description = getIntent().getStringExtra("description");
so you can pass title and description to DetailActivity
IMO, you implement setOnClickListener inside Adapter of RecyclerView. You can refer to my following sample code, then apply its logic to your code. Hope it helps!
public class MyRVAdapter extends RecyclerView.Adapter<MyRVAdapter.ViewHolder> {
Context mContext;
List<String> mStringList;
public MyRVAdapter(Context mContext, List<String> mStringList) {
this.mContext = mContext;
this.mStringList = mStringList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView1 = (TextView) v.findViewById(R.id.textView1);
TextView textView2 = (TextView) v.findViewById(R.id.textView2);
Bundle bundle = new Bundle();
bundle.putString("key1", textView1.getText().toString());
bundle.putString("key2", textView2.getText().toString());
passToAnotherActivity(bundle);
}
});
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// do something...
}
#Override
public int getItemCount() {
if (mStringList != null) {
return mStringList.size();
}
return 0;
}
private void passToAnotherActivity(Bundle bundle) {
if (mContext == null)
return;
if (mContext instanceof MainActivity) {
MainActivity activity = (MainActivity) mContext;
activity.passToAnotherActivity(bundle); // this method must be implemented inside `MainActivity`
}
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ViewHolder(View itemView) {
super(itemView);
// do something...
}
#Override
public void onClick(View v) {
}
}
}
First of all make your "itemsdata" object to implement Parcelable. You can check it here . In your onItemClick method you pass the object to your Details activity using intent.putExtra("key",listOfDataItems.get(position));
In your DetailsActivity you can get your custom object with getParcelable("key")
All above methods worked, but kinda long, so this one worked for me :
Cardview cardview;
cardView = (CardView)itemView.findViewById(R.id.cv);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent (view.getContext(), DetailsActivity.class);
i.putExtra("TitleKey",ProbTitle.getText().toString());
i.putExtra("DescrKey",ProbDescr.getText().toString());
view.getContext().startActivity(i);
}
});
And in Details.java :
TextView title;
TextView Descr;
title = (TextView)findViewById(R.id.details_title);
Descr = (TextView)findViewById(R.id.details_descr);
String titleresult = result.getExtras().getString("TitleKey");
String Descrresult = result.getExtras().getString("DescrKey");
title.setText(titleresult);
Descr.setText(Descrresult);