How can I load images using Picasso from a RecyclerAdapter? - java

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);
}

Related

Recyclerview empty on first load

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);
}
});

How to load AdMobs inside RecycleView after every 5th row?

I am trying to implement AdMobs to load ads, every 5th row but i am having a difficult time, as you can see from my screenshot ads are being loaded successfully but they're being loaded after every row. Can someone help me accomplish this? I already tried reading through post on stack overflow but none seems to help. Thank you in advance. image screenshot
Fragment
public class SectorPerformanceFragment extends Fragment {
private RecyclerView newsFeedRecycleView;
private SectorPerformanceAdapter mostActiveAdapter;
private RecyclerViewAdopter recyclerViewAdopter;
public static final int ITEMS_PER_AD = 9;
private RecyclerView.LayoutManager layoutManager;
private RequestQueue requestQueue;
private JSONObject stockDetails;
public static ArrayList<SectorPerformanceModel> mostActiveArrayList;
private RequestQueue requestQueues;
private ImageView backImage;
private View rootView;
private ProgressBar loadingProgressBar;
private TextView sectorNameTv;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.recycle_view_list_ui, container, false);
sectorNameTv = rootView.findViewById(R.id.sectorNameTv);
sectorNameTv.setText("Sector Performance");
loadingProgressBar = rootView.findViewById(R.id.loadingProgressBar);
backImage = rootView.findViewById(R.id.backImageView);
backImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().popBackStack();
//
// Fragment generalMarketFragment = new BrowseFragment();
// FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
// FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// fragmentTransaction.replace(R.id.fragment_container, generalMarketFragment);
// fragmentTransaction.addToBackStack(null);
// fragmentTransaction.commit();
}
});
requestQueues = Volley.newRequestQueue(getActivity());
findViewById();
mostActiveArrayList = new ArrayList<>();
initRecycleView();
retreiveBundleInformation();
return rootView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void findViewById() {
newsFeedRecycleView = rootView.findViewById(R.id.recylcle_view_list);
}
//set up RecycleVIew/listener to detect taps layout manager tels recycle view how to display the list.. without it, nothing shows up
public void initRecycleView() {
layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
newsFeedRecycleView.setHasFixedSize(true);
newsFeedRecycleView.setLayoutManager(layoutManager);
//mostActiveAdapter = new SectorPerformanceAdapter(getContext(), mostActiveArrayList);
// recyclerViewAdopter = new RecyclerViewAdopter(getContext(),mostActiveArrayList);
//
// //newsFeedRecycleView.setAdapter(mostActiveAdapter);
// newsFeedRecycleView.setAdapter(recyclerViewAdopter);
}
//download news data stocknewsapi..
private void downloadStockList(String api) {
// Initialize a new JsonArrayRequest instance
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
api,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Do something with response
//mTextView.setText(response.toString());
loadingProgressBar.setVisibility(View.INVISIBLE);
//Log.i("jsonResponse", response.toString());
// Process the JSON
// Loop through the array elements
for (int i = 0; i < response.length(); i++) {
// Get current json object
try {
stockDetails = response.getJSONObject(i);
Log.i("stockDetails", stockDetails.toString());
SectorPerformanceModel sectorPerformanceModel2 = new SectorPerformanceModel(stockDetails.getString("sector"),stockDetails.getString("changesPercentage"),1);
mostActiveArrayList.add((sectorPerformanceModel2));
SectorPerformanceModel sectorPerformanceModel3 = new SectorPerformanceModel(stockDetails.getString("sector"),stockDetails.getString("changesPercentage"),2);
mostActiveArrayList.add(mostActiveArrayList.size(),sectorPerformanceModel3);
recyclerViewAdopter = new RecyclerViewAdopter(getContext(),mostActiveArrayList);
//newsFeedRecycleView.setAdapter(mostActiveAdapter);
newsFeedRecycleView.setAdapter(recyclerViewAdopter);
//recyclerViewAdopter.notifyDataSetChanged();
// mostActiveArrayList.add(sectorPerformanceModel);
// mostActiveAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("error", error.toString());
}
}
);
// Add JsonArrayRequest to the RequestQueue
requestQueues.add(jsonArrayRequest);
}
public void retreiveBundleInformation() {
downloadStockList("APIKEY");
}
}
Adapter
[public class RecyclerViewAdopter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private Context mContext;
private List<SectorPerformanceModel> mList;
public RecyclerViewAdopter(Context mContext, List<SectorPerformanceModel> mList) {
this.mList = mList;
this.mContext = mContext;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name;
private TextView newsTitle, sourceName, epsEstiatmate;
private CircleImageView newsThumbImage;
public MyViewHolder(View view) {
super(view);
epsEstiatmate = itemView.findViewById(R.id.formTypeTv);
newsTitle = itemView.findViewById(R.id.tickerTv);
sourceName = itemView.findViewById(R.id.dateTv);
newsThumbImage= itemView.findViewById(R.id.defaultImageColor);
newsThumbImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("tapped","TAPPED");
}
});
}
}
public static class ViewHolderAdMob extends RecyclerView.ViewHolder {
public AdView mAdView;
public ViewHolderAdMob(View view) {
super(view);
mAdView = (AdView) view.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
mAdView.loadAd(adRequest);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch(viewType){
case 1:{
View v = inflater.inflate(R.layout.trending_stock_row, parent, false);
viewHolder = new MyViewHolder(v);
break;
}
case 2:{
View v = inflater.inflate(R.layout.ads_row, parent, false);
viewHolder = new ViewHolderAdMob(v);
break;
}
}
return viewHolder;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
SectorPerformanceModel model= mList.get(holder.getAdapterPosition());
switch(holder.getItemViewType()){
case 1:{
MyViewHolder viewHolder = (MyViewHolder) holder;
Random r = new Random();
int red = r.nextInt(255 - 0 + 1) + 0;
int green = r.nextInt(255 - 0 + 1) + 0;
int blue = r.nextInt(255 - 0 + 1) + 0;
GradientDrawable draw = new GradientDrawable();
draw.setShape(GradientDrawable.OVAL);
draw.setColor(Color.rgb(red, green, blue));
viewHolder.newsThumbImage.setBackground(draw);
viewHolder.newsTitle.setText(model.getSector());
viewHolder.sourceName.setText(model.getChangesPercentage());
break;
}
case 2:{
break;
}
}
}
#Override
public int getItemViewType(int position) {
return mList.get(position).getViewType();
}
#Override
public int getItemCount() {
return mList.size();
}
}][1]
It looks like you are adding 2 items to your adapter's data source for each element in your API response: one element has viewType 1 and the other viewType 2:
SectorPerformanceModel sectorPerformanceModel2 = new SectorPerformanceModel(stockDetails.getString("sector"),stockDetails.getString("changesPercentage"),1);
mostActiveArrayList.add((sectorPerformanceModel2));
SectorPerformanceModel sectorPerformanceModel3 = new SectorPerformanceModel(stockDetails.getString("sector"),stockDetails.getString("changesPercentage"),2);
mostActiveArrayList.add(mostActiveArrayList.size(),sectorPerformanceModel3);
Your adapter is rendering items with viewType 2 as ad rows, so if you want to display an ad row every 5 rows you'll need to update the downloadStockList method to execute this
SectorPerformanceModel sectorPerformanceModel3 = new SectorPerformanceModel(stockDetails.getString("sector"),stockDetails.getString("changesPercentage"),2);
mostActiveArrayList.add(mostActiveArrayList.size(),sectorPerformanceModel3);
only after having added 4 items with viewType 1.

Not Able to get Text In recycle view

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.

How to achieve this view

I created an app which displays all files from internal storage in gridview using recyclerviewadapter. But I am not sure how to display different icons for different file types. I want to achieve somewhat this kind of view. Like it has different icon for a folder, different for a pdf file, or an image. How can I achieve this ?
InternalStorage.java:
public class InternalStorage extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
MyRecyclerViewAdapter adapter;
private ArrayList<String> myList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_internal_storage);
myList = new ArrayList<>();
String path= Environment.getExternalStorageDirectory().getAbsolutePath();
File f = new File(path);//converted string object to file
File list[] = f.listFiles();//getting the list of files in string array
for( int i=0; i< list.length; i++) {
myList.add(list[i].getName());
}
// set up the RecyclerView
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rvNumbers);
int numberOfColumns = 4;
recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
adapter = new MyRecyclerViewAdapter(this, myList);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
}
MyRecyclerViewAdapter.java:
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private ArrayList<String> mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
public MyRecyclerViewAdapter(Context context, ArrayList<String> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the cell layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
return new ViewHolder(view);
}
// binds the data to the textview in each cell
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String animal = mData.get(position);
holder.myTextView.setText(animal);
}
// total number of cells
#Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ImageButton myImage;
ViewHolder(View itemView) {
super(itemView);
myTextView = (TextView) itemView.findViewById(R.id.info_text);
myImage = (ImageButton) itemView.findViewById(R.id.buttonimage);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
public String getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
first of all you need to creat a model than allows you to diferentiate each animal from the others. You can do it with a model wich has a name and a imageUrl (an image url to each animal than you can set depending of the type of the animal). After that you must define a imageView who will have the new image (the one that will be inflatin with the image you bring from the url). To load the image i recomend to you to use Picasso, whihc is a library that makes easier to load any kind of imagen.
The code is somethin like this
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private ArrayList<Animal> mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
public MyRecyclerViewAdapter(Context context, ArrayList<String> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the cell layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
return new ViewHolder(view);
}
// binds the data to the textview in each cell
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Animal animal = mData.get(position);
holder.myTextView.setText(animal);
Picasso.with(context).load(animal.imageUrl).into(holder.imageViewYouWantToChangue)
}
// total number of cells
#Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ImageButton myImage;
ViewHolder(View itemView) {
super(itemView);
myTextView = (TextView) itemView.findViewById(R.id.info_text);
myImage = (ImageButton) itemView.findViewById(R.id.buttonimage);
imageViewYouWantToChangue = (ImageView) itemView.findViewById(R.id.image_you_to_changue);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
public String getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}}
public class Animal{
String name;
String imageUrl;
public Animal(String name, String type) {
this.name = name;
this.imageUrl = imageUrl;
}
}
The info about picasso
http://square.github.io/picasso/
And don't forget to add the INTERNET_PERMISION to you app in the manifest.

RecyclerView Slide New Item In At Top

I recently set up my RecyclerView and want to slide in all new items that are added. Specifically, I have a comment screen and every time a new comment is added, I want it to slide in from the left with an animation effect.
Note that I add all new items to my mCommentArrayList at index 0 so that they appear at the top of the view.
I have read about using third-party libraries, but from what I understand that is not necessary. Here is my code:
Where I first call to Firebase to find data to populate the RecyclerView:
mUpdateRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
setImage(dataSnapshot);
setQuestion(dataSnapshot);
createInitialCommentIDArray(dataSnapshot);
mNumberOfCommentsAtPoll = (int) dataSnapshot.child(COMMENTS_LABEL).getChildrenCount();
for (int i = 0; i < mNumberOfCommentsAtPoll; i++) {
String commentID = (String) dataSnapshot.child(COMMENTS_LABEL).child(mCommentIDArrayList.get(i)).child("COMMENT").getValue();
Log.v("COMMENT_ID", "The comment ID is " + commentID);
String userID = (String) dataSnapshot.child(COMMENTS_LABEL).child(mCommentIDArrayList.get(i)).child("USER_ID").getValue();
Log.v("USER_ID", "The user ID is " + userID);
mCommentArrayList.add(0, new Comments(mUserAvatar, userID, commentID));
mCommentAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Subsequent Calls to Firebase on Data Change:
#Override
protected void onStart() {
super.onStart();
mUpdateComments = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mNumberOfCommentsAtPoll = (int) dataSnapshot.getChildrenCount();
for (DataSnapshot x : dataSnapshot.child(COMMENTS_LABEL).getChildren()) {
Log.v("DATA_SNAPSHOT", x.toString());
if (mCommentIDArrayList.contains(x.getKey())) {
Log.v("Comment_Already_Added", x.getKey());
} else {
Log.v("Child_Added_Called", "Child Added Called");
mCommentIDArrayList.add(x.getKey());
String commentID = (String) dataSnapshot.child(COMMENTS_LABEL).child(x.getKey()).child("COMMENT").getValue();
Log.v("New_Comment", "The new comment is " + commentID);
String userID = (String) dataSnapshot.child(COMMENTS_LABEL).child(x.getKey()).child("USER_ID").getValue();
Log.v("New_User_ID", "The new userID is " + userID);
mCommentArrayList.add(0, new Comments(mUserAvatar, userID, commentID));
mCommentAdapter.notifyDataSetChanged();
}
}
}
My RecyclerView Adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<Comments> mDataSet;
// 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
protected ImageView userAvatar;
protected TextView userID;
protected TextView userComment;
public ViewHolder(View v) {
super(v);
userAvatar = (ImageView) v.findViewById(R.id.profile_image);
userID = (TextView) v.findViewById(R.id.user_ID);
userComment = (TextView) v.findViewById(R.id.user_comment_textview);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(ArrayList<Comments> myDataset) {
mDataSet = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.individual_comment, parent, false);
// set the view's size, margins, paddings and layout parameters
return new ViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
//The OutOfBoundsException is pointing here
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Comments comment = mDataSet.get(position);
holder.userComment.setText(comment.getUserComment());
holder.userID.setText("User " + position);
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataSet.size();
}
}

Categories

Resources