The code below downloads images from a server and displays them in a recyclerview using php mysql and volley library as seen in the attached image. As of now when one clicks the image only toasts the image name. I want a user to be able to view the full image on click. Sorry to post all the code but its a desperate situation.
RecyclerView code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
CardView code
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="5dp"
card_view:contentPadding="5dp"
card_view:cardCornerRadius="5dp"
card_view:cardMaxElevation="5dp"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ECEFF1">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/VolleyImageView"
android:layout_width="150dp"
android:layout_height="100dp"
android:src="#mipmap/ic_launcher"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"/>
<TextView
android:id="#+id/ImageNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_toEndOf="#+id/VolleyImageView"
android:layout_toRightOf="#+id/VolleyImageView"
android:text="JSon Image Name"
android:textColor="#000"
android:textSize="15dp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
MainActivity
package com.ny.fetchallimages;
import android.os.Bundle;
import org.json.JSONArray;
import java.util.ArrayList;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import java.util.List;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
List<DataAdapter> ListOfdataAdapter;
RecyclerView recyclerView;
String HTTP_JSON_URL = "http://*************.php";
String Image_URL_JSON = "image_data";
String Image_Name_JSON = "image_tag";
JsonArrayRequest RequestOfJSonArray ;
RequestQueue requestQueue ;
View view ;
int RecyclerViewItemPosition ;
RecyclerView.LayoutManager layoutManagerOfrecyclerView;
RecyclerView.Adapter recyclerViewadapter;
ArrayList<String> ImageTitleNameArrayListForClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageTitleNameArrayListForClick = new ArrayList<>();
ListOfdataAdapter = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
layoutManagerOfrecyclerView = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManagerOfrecyclerView);
JSON_HTTP_CALL();
// Implementing Click Listener on RecyclerView.
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
view = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if(view != null && gestureDetector.onTouchEvent(motionEvent)) {
//Getting RecyclerView Clicked Item value.
RecyclerViewItemPosition = Recyclerview.getChildAdapterPosition(view);
// Showing RecyclerView Clicked Item value using Toast.
Toast.makeText(MainActivity.this, ImageTitleNameArrayListForClick.get(RecyclerViewItemPosition), Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
public void JSON_HTTP_CALL(){
RequestOfJSonArray = new JsonArrayRequest(HTTP_JSON_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
ParseJSonResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(RequestOfJSonArray);
}
public void ParseJSonResponse(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitle(json.getString(Image_Name_JSON));
// Adding image title name in array to display on RecyclerView click event.
ImageTitleNameArrayListForClick.add(json.getString(Image_Name_JSON));
GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));
} catch (JSONException e) {
e.printStackTrace();
}
ListOfdataAdapter.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(ListOfdataAdapter, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
RecyclerViewAdapter
package com.ny.fetchallimages;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.android.volley.toolbox.NetworkImageView;
import java.util.List;
import com.android.volley.toolbox.ImageLoader;
import android.content.Context;
import android.view.LayoutInflater;
import androidx.recyclerview.widget.RecyclerView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<DataAdapter> dataAdapters;
ImageLoader imageLoader;
public RecyclerViewAdapter(List<DataAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
DataAdapter dataAdapterOBJ = dataAdapters.get(position);
imageLoader = ImageAdapter.getInstance(context).getImageLoader();
imageLoader.get(dataAdapterOBJ.getImageUrl(),
ImageLoader.getImageListener(
Viewholder.VollyImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.VollyImageView.setImageUrl(dataAdapterOBJ.getImageUrl(), imageLoader);
Viewholder.ImageTitleTextView.setText(dataAdapterOBJ.getImageTitle());
}
#Override
public int getItemCount() {
return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleTextView;
public NetworkImageView VollyImageView ;
public ViewHolder(View itemView) {
super(itemView);
ImageTitleTextView = (TextView) itemView.findViewById(R.id.ImageNameTextView) ;
VollyImageView = (NetworkImageView) itemView.findViewById(R.id.VolleyImageView) ;
}
}
}
ImageAdapter
package com.ny.fetchallimages;
import android.graphics.Bitmap;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.RequestQueue;
import android.content.Context;;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.Cache;
import androidx.collection.LruCache;
import com.android.volley.Network;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.HurlStack;
public class ImageAdapter {
public static ImageAdapter imageAdapter;
public Network networkOBJ ;
public RequestQueue requestQueue1;
public ImageLoader Imageloader1;
public Cache cache1 ;
public static Context context1;
LruCache<String, Bitmap> LRUCACHE = new LruCache<String, Bitmap>(30);
private ImageAdapter(Context context) {
this.context1 = context;
this.requestQueue1 = RequestQueueFunction();
Imageloader1 = new ImageLoader(requestQueue1, new ImageLoader.ImageCache() {
#Override
public Bitmap getBitmap(String URL) {
return LRUCACHE.get(URL);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
LRUCACHE.put(url, bitmap);
}
});
}
public ImageLoader getImageLoader() {
return Imageloader1;
}
public static ImageAdapter getInstance(Context SynchronizedContext) {
if (imageAdapter == null) {
imageAdapter = new ImageAdapter(SynchronizedContext);
}
return imageAdapter;
}
public RequestQueue RequestQueueFunction() {
if (requestQueue1 == null) {
cache1 = new DiskBasedCache(context1.getCacheDir());
networkOBJ = new BasicNetwork(new HurlStack());
requestQueue1 = new RequestQueue(cache1, networkOBJ);
requestQueue1.start();
}
return requestQueue1;
}
}
DataAdapter
package com.ny.fetchallimages;
public class DataAdapter
{
public String ImageURL;
public String ImageTitle;
public String getImageUrl() {
return ImageURL;
}
public void setImageUrl(String imageServerUrl) {
this.ImageURL = imageServerUrl;
}
public String getImageTitle() {
return ImageTitle;
}
public void setImageTitle(String Imagetitlename) {
this.ImageTitle = Imagetitlename;
}
}
This worked by creating a new activity, then in on item click, get the item clicked position URL, send an intent to the activity with the image URL as extras. Get the image url from the intent in the activity then load the image.
Related
I want to display a String of names in the text view of recycler view. the .xml of this step is below
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:id="#+id/youtube_row_card_view"
android:layout_height="120dp"
android:layout_marginLeft="1dp"
android:layout_marginStart="1dp"
android:layout_marginTop="0dp"
android:layout_marginBottom="0dp"
app:cardCornerRadius="10dp"
app:contentPadding="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.youtube.player.YouTubeThumbnailView
android:id="#+id/video_thumbnail_image_view"
android:layout_width="140dp"
android:layout_height="90dp"
android:contentDescription="#string/thumbnail_image_view_desc"
android:scaleType="centerCrop" ></com.google.android.youtube.player.YouTubeThumbnailView>
<TextView
android:id="#+id/icon_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#android:color/black"></TextView>
</LinearLayout>
</androidx.cardview.widget.CardView>
the adapter class CustomAdapter is below
package com.CurrentMediaPakLiveNews;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.viewHolder> {
Context context;
ArrayList<itemModel> items;
public class viewHolder extends RecyclerView.ViewHolder {
public TextView iconName;
public viewHolder(View itemView) {
super(itemView);
this.iconName = itemView.findViewById(R.id.icon_name);
}
}
public CustomAdapter(Context context, ArrayList<itemModel> items) {
this.context = context;
this.items = items;
}
#Override
public viewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.youtube_video_custom_layout, parent, false);
viewHolder viewHolder = new viewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(viewHolder holder, int position) {
TextView iconName =holder.iconName;
holder.iconName.setText(items.get(position).getName());
}
#Override
public int getItemCount() {
return items.size();
}
}
while the itemModel class is declared as:
package com.CurrentMediaPakLiveNews;
public class itemModel {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
the MainActivity declaration for textview is below:
import android.util.Log;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerSupportFragmentX;
import java.util.ArrayList;
import java.util.Collections;
import adapter.SecondYoutubeVideoAdapter;
import adapter.YoutubeVideoAdapter;
import utils.Constants;
import utils.RecyclerViewOnClickListener;
import utils.RecyclerViewOnClickListener2;
public class MainActivity extends AppCompatActivity {
private AdView mAdView;
private AdView mAdView2;
//custom adapter
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView firstrecyclerView;
private RecyclerView secondrecyclerView;
ArrayList<itemModel> items;
String[] iconName = {"GEo","Ary","Sama","Hum","dawn","gnn","aj","92","news1","neo"};
//youtube player fragment
private YouTubePlayerSupportFragmentX youTubePlayerFragment;
private ArrayList<String> youtubeVideoArrayList;
private ArrayList<String> secondyoutubeVideoArrayList;
//youtube player to play video when new video selected
private YouTubePlayer youTubePlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
generateDummyVideoList();
initializeYoutubePlayer();
setUpRecyclerView();
populateRecyclerView();
private void setUpRecyclerView() {
firstrecyclerView = findViewById(R.id.first_recycler_view);
firstrecyclerView.setHasFixedSize(true);
items = new ArrayList<>();
//Horizontal direction recycler view
LinearLayoutManager firstlinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
firstrecyclerView.setLayoutManager(firstlinearLayoutManager);
firstrecyclerView.setItemAnimator(new DefaultItemAnimator());
for (int i = 0; i < iconName.length; i++) {
itemModel itemModel = new itemModel();
itemModel.setName(iconName[i]);
items.add(itemModel);
}
private void populateRecyclerView() {
CustomAdapter adapterf = new CustomAdapter(this, items);
firstrecyclerView.setAdapter(adapterf);
final YoutubeVideoAdapter adapter = new YoutubeVideoAdapter(this, youtubeVideoArrayList);
firstrecyclerView.setAdapter(adapter);
the output is displaying everything except for the TEXTVIEW. no list is being displayed. I have tried ecery solution on stackoverflow regarding dependencies, class import etc but couldnt find any solution. Please can somebody help me in this as I am not a regular developer but a self learner.
My YoutubeVideoAdapter.java is below
package adapter;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubeThumbnailLoader;
import com.google.android.youtube.player.YouTubeThumbnailView;
import com.CurrentMediaPakLiveNews.R;
import java.util.ArrayList;
import holder.YoutubeViewHolder;
import utils.Constants;
/**
* Created by sonu on 10/11/17.
*/
public class YoutubeVideoAdapter extends RecyclerView.Adapter<YoutubeViewHolder> {
private static final String TAG = YoutubeVideoAdapter.class.getSimpleName();
private Context context;
private ArrayList<String> youtubeVideoModelArrayList;
//position to check which position is selected
private int selectedPosition = 0;
public YoutubeVideoAdapter(Context context, ArrayList<String> youtubeVideoModelArrayList) {
this.context = context;
this.youtubeVideoModelArrayList = youtubeVideoModelArrayList;
}
#Override
public YoutubeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.youtube_video_custom_layout, parent, false);
return new YoutubeViewHolder(view);
}
#Override
public void onBindViewHolder(YoutubeViewHolder holder, final int position) {
//if selected position is equal to that mean view is selected so change the cardview color
if (selectedPosition == position) {
holder.youtubeCardView.setCardBackgroundColor(ContextCompat.getColor(context, R.color.colorPrimary));
} else {
//if selected position is not equal to that mean view is not selected so change the cardview color to white back again
holder.youtubeCardView.setCardBackgroundColor(ContextCompat.getColor(context, android.R.color.white));
}
/* initialize the thumbnail image view , we need to pass Developer Key */
holder.videoThumbnailImageView.initialize(Constants.DEVELOPER_KEY, new YouTubeThumbnailView.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, final YouTubeThumbnailLoader youTubeThumbnailLoader) {
//when initialization is sucess, set the video id to thumbnail to load
youTubeThumbnailLoader.setVideo(youtubeVideoModelArrayList.get(position));
youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener() {
#Override
public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
//when thumbnail loaded successfully release the thumbnail loader as we are showing thumbnail in adapter
youTubeThumbnailLoader.release();
}
#Override
public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
//print or show error when thumbnail load failed
Log.e(TAG, "Youtube Thumbnail Error");
}
});
}
#Override
public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
//print or show error when initialization failed
Log.e(TAG, "Youtube Initialization Failure");
}
});
}
#Override
public int getItemCount() {
return youtubeVideoModelArrayList != null ? youtubeVideoModelArrayList.size() : 0;
}
/**
* method the change the selected position when item clicked
* #param selectedPosition
*/
public void setSelectedPosition(int selectedPosition) {
this.selectedPosition = selectedPosition;
//when item selected notify the adapter
notifyDataSetChanged();
}
}
You are applying differente adapters to the same recyclerview, which means the last one that will be visible will be the last one.
You can see it here:
CustomAdapter adapterf = new CustomAdapter(this, items);
firstrecyclerView.setAdapter(adapterf);
final YoutubeVideoAdapter adapter = new YoutubeVideoAdapter(this, youtubeVideoArrayList);
firstrecyclerView.setAdapter(adapter);
If you notice, you are doing firstrecyclerView.setAdapter(adapterf) where you attach the CustomAdapter. Then, you do again firstrecyclerView.setAdapter(adapter) where you attach the YoutubeVideoAdapter. Only the last adapter will take place, since it overrides the previous one.
EDIT:
As I can understand, you want to render a view where you display an YoutubeThumbnail and a TextView underneath that thumbnail. In your CustomAdapter, you are using a list of itemModel. Consider adding an attribute to that itemModel that holds the Youtube video URL. If you do it this way, you can show the thumbnail and the TextView at the same time, you just need to modify your CustomAdapter to the same as your YoutubeVideoAdapter.
I.e:
Your ItemModel would look like this:
public class itemModel {
String name;
String youtubeUrl;
public itemoModel(String name, String youtubeUrl){
this.name = name;
this.youtubeUrl = youtubeUrl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getYoutubeUrl(){
return this.youtubeUrl;
}
public void setYoutubeUrl(String youtubeUrl){
this.youtubeUrl = youtubeUrl;
}
}
And your CustomAdapter:
public class viewHolder extends RecyclerView.ViewHolder {
public TextView iconName;
public YouTubeThumbnailView thumbnail;
public viewHolder(View itemView) {
super(itemView);
this.iconName = itemView.findViewById(R.id.icon_name);
this.thumbnail = itemView.findViewById(R.id.video_thumbnail_image_view);
}
}
#Override
public void onBindViewHolder(viewHolder holder, int position) {
TextView iconName =holder.iconName;
holder.iconName.setText(items.get(position).getName());
YouTubeThumbnailView thumbnail = holder.thumbnail;
String youtubeUrl = items.get(position).getYoutubeUrl();
//Do what you need to do with the youtubeUrl
}
This way you just need to use one adapter and one recyclerView with the code you've already done here:
CustomAdapter adapterf = new CustomAdapter(this, items);
firstrecyclerView.setAdapter(adapterf);
Let me know if it helped you!
I'm new to Android Studio. I'm trying to custom a Fragment automatically created by the IDE using the option create -> new Fragment (List). I'm not able to show the List retrieved from an http page, but if I manually add items to my list, the emulator let me see it. How can I solve this problem?
municipioFragment.java
package com.example.is2_app.ui.municipio;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.is2_app.R;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class municipioFragment extends Fragment {
// TODO: Customize parameters
private int mColumnCount = 1;
private List<News> lstNews;
private OnListFragmentInteractionListener mListener;
public municipioFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lstNews = new ArrayList<>();
getURL();
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_municipio_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
recyclerView.setAdapter(new MymunicipioRecyclerViewAdapter(lstNews, mListener));
}
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnListFragmentInteractionListener {
// TODO: Update argument type and name
void onListFragmentInteraction(News item);
}
public void getURL() {
new Thread(new Runnable() {
#Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
Document doc = Jsoup.connect("http://www.comune.candida.av.it").get();
Element content = doc.getElementById("b370");
Elements subcontent = content.getElementsByTag("p");
String Text = null;
String Href = null;
int i = 0;
for (Element link : subcontent) {
Href = link.attr("href");
Text = link.text();
builder.append("\n").append(Text);
i = i + 1;
lstNews.add(new News(Integer.toString(i), Text));
}
} catch (IOException e) {
builder.append("Error: ").append(e.getMessage()).append("\n");
}
}
}).start();
}
}
MunicipioRecyclerViewAdapter.java
package com.example.is2_app.ui.municipio;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.is2_app.R;
import com.example.is2_app.ui.municipio.municipioFragment.OnListFragmentInteractionListener;
import java.util.List;
public class MymunicipioRecyclerViewAdapter extends RecyclerView.Adapter<MymunicipioRecyclerViewAdapter.ViewHolder> {
private final OnListFragmentInteractionListener mListener;
List<News> mData;
public MymunicipioRecyclerViewAdapter(List<News> mData, OnListFragmentInteractionListener listener) {
this.mData = mData;
this.mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_municipio, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
//holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mData.get(position).getId());
holder.mContentView.setText(mData.get(position).getContent());
}
#Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.item_number);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
fragment_municipio.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/item_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem" />
<TextView
android:id="#+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem" /> </LinearLayout>
fragment_municipio_list.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/list"
android:name="com.example.is2_app.ui.municipioFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
app:layoutManager="LinearLayoutManager"
tools:context=".ui.municipio.municipioFragment"
tools:listitem="#layout/fragment_municipio" />
So getUrl() is running in a Thread. In addition, getting the Document with JSoup is gonna need some time. This means that onCreateView will probably run before your lstNews is filled with the data you are scraping from the Document.
So you want to update your dataset; then, you want to notify your Adapter that your dataset changed.
Add this method to your Adapter
public void updateData(List<News> mData) {
this.mData = mData;
this.notifyDataSetChanged();
}
And after the for loop in getUrl(), you want to do the following:
runOnUiThread(new Runnable() {
#Override
public void run() {
recyclerViewAdapter.updateData(lstNews);
}
});
Where, recyclerViewAdapter is defined alongside recyclerView and initialized in the onCreateView.
So the following line:
recyclerView.setAdapter(new MymunicipioRecyclerViewAdapter(lstNews, mListener));
Will become:
recyclerViewAdapter = new MymunicipioRecyclerViewAdapter(lstNews, mListener);
recyclerView.setAdapter(recyclerViewAdapter);
The code below downloads images from a server and displays them in a recyclerview using php mysql and volley library as seen in the image. As of now when one clicks the image it only toasts the image name. I want a user to be able to view the full image on click. Sorry to post all the code but its a desperate situation.
RECYCLERVIEW CODE
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
CARDVIEW CODE
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="5dp"
card_view:contentPadding="5dp"
card_view:cardCornerRadius="5dp"
card_view:cardMaxElevation="5dp"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ECEFF1">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/VolleyImageView"
android:layout_width="150dp"
android:layout_height="100dp"
android:src="#mipmap/ic_launcher"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"/>
<TextView
android:id="#+id/ImageNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_toEndOf="#+id/VolleyImageView"
android:layout_toRightOf="#+id/VolleyImageView"
android:text="JSon Image Name"
android:textColor="#000"
android:textSize="15dp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
MAIN ACTIVITY
package com.ny.fetchallimages;
import android.os.Bundle;
import org.json.JSONArray;
import java.util.ArrayList;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import java.util.List;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
List<DataAdapter> ListOfdataAdapter;
RecyclerView recyclerView;
String HTTP_JSON_URL = "http://*************.php";
String Image_URL_JSON = "image_data";
String Image_Name_JSON = "image_tag";
JsonArrayRequest RequestOfJSonArray ;
RequestQueue requestQueue ;
View view ;
int RecyclerViewItemPosition ;
RecyclerView.LayoutManager layoutManagerOfrecyclerView;
RecyclerView.Adapter recyclerViewadapter;
ArrayList<String> ImageTitleNameArrayListForClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageTitleNameArrayListForClick = new ArrayList<>();
ListOfdataAdapter = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
layoutManagerOfrecyclerView = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManagerOfrecyclerView);
JSON_HTTP_CALL();
// Implementing Click Listener on RecyclerView.
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
view = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if(view != null && gestureDetector.onTouchEvent(motionEvent)) {
//Getting RecyclerView Clicked Item value.
RecyclerViewItemPosition = Recyclerview.getChildAdapterPosition(view);
// Showing RecyclerView Clicked Item value using Toast.
Toast.makeText(MainActivity.this, ImageTitleNameArrayListForClick.get(RecyclerViewItemPosition), Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
public void JSON_HTTP_CALL(){
RequestOfJSonArray = new JsonArrayRequest(HTTP_JSON_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
ParseJSonResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(RequestOfJSonArray);
}
public void ParseJSonResponse(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitle(json.getString(Image_Name_JSON));
// Adding image title name in array to display on RecyclerView click event.
ImageTitleNameArrayListForClick.add(json.getString(Image_Name_JSON));
GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));
} catch (JSONException e) {
e.printStackTrace();
}
ListOfdataAdapter.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(ListOfdataAdapter, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
RECYCLERVIEWADAPTER
package com.ny.fetchallimages;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.android.volley.toolbox.NetworkImageView;
import java.util.List;
import com.android.volley.toolbox.ImageLoader;
import android.content.Context;
import android.view.LayoutInflater;
import androidx.recyclerview.widget.RecyclerView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<DataAdapter> dataAdapters;
ImageLoader imageLoader;
public RecyclerViewAdapter(List<DataAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
DataAdapter dataAdapterOBJ = dataAdapters.get(position);
imageLoader = ImageAdapter.getInstance(context).getImageLoader();
imageLoader.get(dataAdapterOBJ.getImageUrl(),
ImageLoader.getImageListener(
Viewholder.VollyImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.VollyImageView.setImageUrl(dataAdapterOBJ.getImageUrl(), imageLoader);
Viewholder.ImageTitleTextView.setText(dataAdapterOBJ.getImageTitle());
}
#Override
public int getItemCount() {
return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleTextView;
public NetworkImageView VollyImageView ;
public ViewHolder(View itemView) {
super(itemView);
ImageTitleTextView = (TextView) itemView.findViewById(R.id.ImageNameTextView) ;
VollyImageView = (NetworkImageView) itemView.findViewById(R.id.VolleyImageView) ;
}
}
}
IMAGEADAPTER
package com.ny.fetchallimages;
import android.graphics.Bitmap;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.RequestQueue;
import android.content.Context;;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.Cache;
import androidx.collection.LruCache;
import com.android.volley.Network;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.HurlStack;
public class ImageAdapter {
public static ImageAdapter imageAdapter;
public Network networkOBJ ;
public RequestQueue requestQueue1;
public ImageLoader Imageloader1;
public Cache cache1 ;
public static Context context1;
LruCache<String, Bitmap> LRUCACHE = new LruCache<String, Bitmap>(30);
private ImageAdapter(Context context) {
this.context1 = context;
this.requestQueue1 = RequestQueueFunction();
Imageloader1 = new ImageLoader(requestQueue1, new ImageLoader.ImageCache() {
#Override
public Bitmap getBitmap(String URL) {
return LRUCACHE.get(URL);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
LRUCACHE.put(url, bitmap);
}
});
}
public ImageLoader getImageLoader() {
return Imageloader1;
}
public static ImageAdapter getInstance(Context SynchronizedContext) {
if (imageAdapter == null) {
imageAdapter = new ImageAdapter(SynchronizedContext);
}
return imageAdapter;
}
public RequestQueue RequestQueueFunction() {
if (requestQueue1 == null) {
cache1 = new DiskBasedCache(context1.getCacheDir());
networkOBJ = new BasicNetwork(new HurlStack());
requestQueue1 = new RequestQueue(cache1, networkOBJ);
requestQueue1.start();
}
return requestQueue1;
}
}
DATAADAPTER
package com.ny.fetchallimages;
public class DataAdapter
{
public String ImageURL;
public String ImageTitle;
public String getImageUrl() {
return ImageURL;
}
public void setImageUrl(String imageServerUrl) {
this.ImageURL = imageServerUrl;
}
public String getImageTitle() {
return ImageTitle;
}
public void setImageTitle(String Imagetitlename) {
this.ImageTitle = Imagetitlename;
}
}
just when the user clicked on an item do like me...
Intent i = new Intent(context,BigImageActivity);
intent.putExtra("image_url",iamge_url);
context.startActivity(i);
in big_image_layout.xml
<ImageView
android:id="#+id/iv_big_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
in onCreate BigImageActivity:
String img_url = getIntent.getStringExtra("image_url");
and for showing image use Glide:
Glide.with(context)
.load(img_url)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.dontAnimate()
.into(iv_big_image);
and done!!!
I hope this useful for you.
I made it to show full images by fetching the url and parsing it to a new activity. Thanks for the positive responses
It's my first time on StackOverFlow and Android Java language.
I have a doubt with my prototype app.
I'm going to explain it:
I have a adapter where i apply:
ReDatabaseAdapter
package prototype.es.applicationdb.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import prototype.es.applicationdb.R;
import prototype.es.applicationdb.utils.ImageGetter;
import prototype.es.applicationdb.utils.ReDatabaseEntry;
public class ReDatabaseAdapter extends RecyclerView.Adapter<ReDatabaseAdapter.ReDatabaseViewHolder> {
protected List<ReDatabaseEntry> mDB = null;
public ReDatabaseAdapter(List<ReDatabaseEntry> list){
mDB = new ArrayList<ReDatabaseEntry>(list);
}
#NonNull
#Override
public ReDatabaseViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.view_holder_layout,viewGroup,false);
return new ReDatabaseViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ReDatabaseViewHolder reDatabaseViewHolder, int position) {
ReDatabaseEntry entry = mDB.get(position);
String name = entry.getName();
reDatabaseViewHolder.mName.setText(name);
int icon_id = ImageGetter.getIcon(name);
Context context = reDatabaseViewHolder.itemView.getContext();
reDatabaseViewHolder.mIcon.setImageDrawable(ContextCompat.getDrawable(
context,icon_id));
}
#Override
public int getItemCount() {
// total elements on JSON.
return mDB.size();
}
public class ReDatabaseViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
protected TextView mName = null;
protected ImageView mIcon = null;
public ReDatabaseViewHolder(#NonNull View itemView) {
super(itemView);
mName = itemView.findViewById(R.id.tv_char_name);
mIcon = itemView.findViewById(R.id.iv_char_icon);
mIcon.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int viewId=v.getId();
if(viewId == mIcon.getId()) {
Intent intentToTakePicture = new Intent();
intentToTakePicture.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
MainActivity contextAux = (MainActivity) mContext;
if (intentToTakePicture.resolveActivity(mContext.getPackageManager()) != null) {
contextAux.startActivityForResult(intentToTakePicture, 2);
}
}
}
}
}
In my MainActivity i have:
package prototype.es.applicationdb;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.LinearLayout;
import org.json.JSONException;
import java.io.IOException;
import java.util.List;
import prototype.es.applicationdb.adapter.ReDatabaseAdapter;
import prototype.es.applicationdb.utils.ReDatabaseEntry;
import prototype.es.applicationdb.utils.ReJsonParser;
public class MainActivity extends AppCompatActivity {
protected List<ReDatabaseEntry> mList = null;
protected RecyclerView mRecyclerView = null;
protected ReDatabaseAdapter mAdapter = null;
protected LinearLayoutManager mManager = null;
protected ImageView mPhoto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
mList = ReJsonParser.parseJSONDatabase(getResources().openRawResource(R.raw.sw_db));
} catch(IOException e){
Log.e(getClass().getName(),e.getMessage());
} catch(JSONException e){
Log.e(getClass().getName(),e.getMessage());
}
mRecyclerView = findViewById(R.id.rv_database_viewer);
mAdapter = new ReDatabaseAdapter(mList);
mManager = new LinearLayoutManager(this);
mManager.setOrientation(LinearLayoutManager.HORIZONTAL);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(mManager);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==2 && resultCode == RESULT_OK){
//Get results from data
Bitmap img = (Bitmap) data.getExtras().get("data");
Bitmap bitmap = Bitmap.createScaledBitmap(img, 600, 800, false);
mPhoto = findViewById(R.id.iv_char_icon);
mPhoto.setImageBitmap(bitmap);
}
}
}
Getimage
package prototype.es.applicationdb.utils;
import prototype.es.applicationdb.R;
public class ImageGetter {
public static int getIcon(String name){
switch(name){
case "forest" :
return R.drawable.forest;
case "beach" :
return R.drawable.beach;
case "storms":
return R.drawable.storms;
case "design":
return R.drawable.design;
case "architecture" :
return R.drawable.architecture;
case "technologies":
return R.drawable.technologies;
case "music":
return R.drawable.music;
case "food":
return R.drawable.food;
case "animals":
return R.drawable.animals;
case "countries":
return R.drawable.countries;
case "transport":
return R.drawable.transport;
case "sports":
return R.drawable.sports;
case "fashion":
return R.drawable.fashion;
case "news":
return R.drawable.news;
default:
return R.drawable.defaultIcon;
}
}
}
Layout view_holder:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fl_outer_card"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/card_border">
<ImageView
android:id="#+id/iv_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_gravity="center_horizontal"/>
...
Layout activity_main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/rv_db_viewer"/>
</LinearLayout>
The problem is when i do long scrolling, my Recycler destroy my photo and appear the original picture. The original picture is recovered for adapter called from Parse JSON
How can i maintain my photo? I'm trying create a list where you click one ítem and you can attach a photo in this list and maintain the photo in the list.
I need your help, some idea will be grateful
Thanks in advance!
Hi you follow step by step this, tutorial.
I understand your problem, so please follow this, if you want to required
easy camera code then, click here
Step 1: Create DemoModel.java
import android.graphics.Bitmap;
import android.net.Uri;
public class DemoModel {
private String imagename = "";
private Bitmap imageBitmap= null;
public String getImagename() {
return imagename;
}
public void setImagename(String imagename) {
this.imagename = imagename;
}
public Bitmap getImageBitmap() {
return imageBitmap;
}
public void setImageBitmap(Bitmap imageBitmap) {
this.imageBitmap = imageBitmap;
}
}
Step 2: Create row_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/ivImage"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#mipmap/ic_launcher_round" />
<TextView
android:id="#+id/tvText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_gravity="center_vertical"
android:gravity="center_vertical" />
</LinearLayout>
Step 3 : Create DemoAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class DemoAdapter extends RecyclerView.Adapter<DemoAdapter.ViewHolder>
{
private String TAG = "GroupAdapter";
private Context mContext;
private LayoutInflater infalter;
private ArrayList<DemoModel> mDemoModelArrayList = new ArrayList<DemoModel>();
private View.OnClickListener mItemClickListener;
public DemoAdapter(Context context, View.OnClickListener itemClickListener, ArrayList<DemoModel> demoModelArrayList) {
this.infalter = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mContext = context;
this.mDemoModelArrayList = demoModelArrayList;
this.mItemClickListener = itemClickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.row_item, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(DemoAdapter.ViewHolder holder, int position) {
holder.tvText.setText(mDemoModelArrayList.get(position).getImagename());
holder.ivImage.setImageBitmap(mDemoModelArrayList.get(position).getImageBitmap());
holder.ivImage.setTag(position);
holder.ivImage.setOnClickListener(mItemClickListener);
}
#Override
public int getItemCount() {
return mDemoModelArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView tvText;
private ImageView ivImage;
public ViewHolder(View itemView) {
super(itemView);
tvText = (TextView) itemView.findViewById(R.id.tvText);
ivImage = (ImageView)itemView.findViewById(R.id.ivImage);
}
}
}
Step 4 : Write this code in Our MainActivity.java
import android.content.Intent;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView rvrecylerView;
private DemoAdapter mDemoAdapter;
private ArrayList<DemoModel> mDemoModelArrayList = new ArrayList<DemoModel>();
int positionGl =0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setDummyData();
rvrecylerView = (RecyclerView)findViewById(R.id.rvrecylerView);
LinearLayoutManager mLinearLayout = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false);
mLinearLayout.setSmoothScrollbarEnabled(true);
rvrecylerView.setLayoutManager(mLinearLayout);
rvrecylerView.setItemAnimator(new DefaultItemAnimator());
mDemoAdapter = new DemoAdapter(MainActivity.this,mItemClickListener,mDemoModelArrayList);
rvrecylerView.setAdapter(mDemoAdapter);
}
private void setDummyData() {
for (int i = 0; i < 50; i++) {
DemoModel tempDemoModel = new DemoModel();
tempDemoModel.setImagename("MyName "+i);
mDemoModelArrayList.add(tempDemoModel);
}
}
private View.OnClickListener mItemClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int)v.getTag();
positionGl = position;
openCamera(position);
}
};
private void openCamera(int postion) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 502);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 502 && resultCode == RESULT_OK && data != null) {
Bitmap mphoto = (Bitmap) data.getExtras().get("data");
mDemoModelArrayList.get(positionGl).setImageBitmap(mphoto);
mDemoAdapter.notifyDataSetChanged();
}
}
i have created the online wallpaper application and i used to activity for my app and i use volley and glide for my app but when i use bottom navigation drawer , activity is not useful .
after that i use fragment but now when i run application my recyclerview doesn't show anything
MainFragment.java:
package ir.zooding.wallpaper.activity;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import ir.zooding.wallpaper.R;
import ir.zooding.wallpaper.adapter.GalleryAdapter;
import ir.zooding.wallpaper.app.AppController;
import ir.zooding.wallpaper.model.Image;
import ir.zooding.wallpaper.receiver.ConnectivityReceiver;
public class MainFragment extends Fragment implements ConnectivityReceiver.ConnectivityReceiverListener {
RecyclerView recycler_view;
static final String url="";
ArrayList<Image> images;
GalleryAdapter mAdapter;
ProgressDialog pd;
View v;
public static MainFragment newInstance() {
MainFragment fragment = new MainFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_main, container, false);
Toolbar toolbar=(Toolbar)v.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
recycler_view=(RecyclerView) v.findViewById(R.id.recycler_view);
pd=new ProgressDialog(getActivity());
pd.setCancelable(false);
images=new ArrayList<>();
mAdapter=new GalleryAdapter(getActivity().getApplicationContext(),images);
RecyclerView.LayoutManager mLayoutManager=new GridLayoutManager(getActivity().getApplicationContext(),2);
recycler_view.setLayoutManager(mLayoutManager);
recycler_view.setAdapter(mAdapter);
Log.i("LOG:","stop 1");
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
1);
recycler_view.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(getActivity().getApplicationContext(),recycler_view, new GalleryAdapter.ClickListener() {
#Override
public void onClick(View view, int position) {
Bundle bundle=new Bundle();
bundle.putSerializable("images",images);
bundle.putInt("position",position);
//Log.i("LOG:",""+position);
// FragmentTransaction ft=getFragmentManager().beginTransaction();
android.app.FragmentTransaction ft=getActivity().getFragmentManager().beginTransaction();
SlideshowDialogFragment newFragment=SlideshowDialogFragment.newInstance();
newFragment.setArguments(bundle);
newFragment.show(ft,"slideshow");
}
#Override
public void onLongClick(View view, int position) {
}
}));
checkConnection();
fetchImages();
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(getActivity(), "دسترسی به حافظه داخلی لغو شد!!!", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public void fetchImages()
{
pd.setMessage("در حال بارگزاری ...");
pd.show();
StringRequest req = new StringRequest(url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("", response.toString());
pd.dismiss();
images.clear();
try {
JSONObject object = new JSONObject(response);
JSONArray dataArray = object.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject dataObject = dataArray.getJSONObject(i);
Image image = new Image();
image.setName_client(dataObject.getString("name_client"));
image.setName(dataObject.getString("name"));
// JSONObject url = object.getJSONObject("url");
image.setSmall(dataObject.getString("small"));
image.setOriginal(dataObject.getString("orginal"));
image.setTimestamp(dataObject.getString("timestamp"));
images.add(image);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("LOG:","stop 2");
mAdapter.notifyDataSetChanged();
Log.i("LOG:","stop 3");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("", "Error: " + error.getMessage());
pd.dismiss();
}
});
AppController.getmInstance().addToRequsetQueue(req);
}
// Method to manually check connection status
private void checkConnection() {
boolean isConnected = ConnectivityReceiver.isConnected();
showSnack(isConnected);
}
// Showing the status in Snackbar
private void showSnack(boolean isConnected) {
String message ="";
//View parentLayout = v.findViewById(android.R.id.content);
RelativeLayout parentLayout = (RelativeLayout)v.findViewById(R.id.mroot);
if (!isConnected) {
message = "اتصال شما به اینترنت برقرار نیست!";
Snackbar snackbar = Snackbar
.make(parentLayout, message, Snackbar.LENGTH_LONG)
.setAction("بررسی مجدد", new View.OnClickListener() {
#Override
public void onClick(View view) {
fetchImages();
checkConnection();
}
});
snackbar.setActionTextColor(Color.RED);
snackbar.setActionTextColor(Color.parseColor("#e62d3f"));
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.parseColor("#FFC107"));
snackbar.setDuration(8000);
snackbar.show();
}
}
#Override
public void onResume() {
super.onResume();
// register connection status listener
AppController.getmInstance().setConnectivityListener(this);
}
/**
* Callback will be triggered when there is change in
* network connection
*/
#Override
public void onNetworkConnectionChanged(boolean isConnected) {
showSnack(isConnected);
}
}
GalleryAdapter.java:
package ir.zooding.wallpaper.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import java.util.List;
import ir.zooding.wallpaper.R;
import ir.zooding.wallpaper.model.Image;
import static android.R.animator.fade_in;
public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.MyViewHolder> {
List<Image> images;
Context mContext;
public GalleryAdapter (Context context,List<Image> images){
this.images = images;
mContext = context;
}
#Override
public GalleryAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.gallery_thumbnail,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(GalleryAdapter.MyViewHolder holder, int position) {
Image image = images.get(position);
Glide.with(mContext).load(image.getSmall())
.thumbnail(0.5f)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(R.drawable.loading)
.fitCenter()
.into(holder.thumbnail);
}
#Override
public int getItemCount() {
return images.size();
}
public interface ClickListener{
void onClick (View view,int position);
void onLongClick (View view,int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
GalleryAdapter.ClickListener clickListener;
GestureDetector gestureDetector;
public RecyclerTouchListener(Context context,final RecyclerView recyclerView,final GalleryAdapter.ClickListener clickListener){
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e){
return true;
}
#Override
public void onLongPress(MotionEvent e){
View child = recyclerView.findChildViewUnder(e.getX(),e.getY());
if(child != null && clickListener != null){
clickListener.onLongClick(child,recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(),e.getY());
if(child != null && clickListener != null&& gestureDetector.onTouchEvent(e)){
clickListener.onClick(child,rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public class MyViewHolder extends RecyclerView.ViewHolder{
ImageView thumbnail;
public MyViewHolder(View view) {
super(view);
thumbnail =(ImageView) view.findViewById(R.id.thumbnail);
}
}
}
MainActivity.java:
package ir.zooding.wallpaper.activity;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import ir.adad.client.Adad;
import ir.zooding.wallpaper.R;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Adad.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
BottomNavigationView bottomNavigationView = (BottomNavigationView)
findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener
(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.action_item1:
selectedFragment = MainFragment.newInstance();
break;
case R.id.action_item2:
selectedFragment = CategoryFragment.newInstance();
break;
case R.id.action_item3:
selectedFragment = InfoFragment.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, selectedFragment);
transaction.commit();
return true;
}
});
//Manually displaying the first fragment - one time only
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, MainFragment.newInstance());
transaction.commit();
//Used to select an item programmatically
//bottomNavigationView.getMenu().getItem(2).setChecked(true);
}
}
fragment_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<RelativeLayout
android:id="#+id/mroot"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
/>
</android.support.design.widget.AppBarLayout>
<include
android:id="#+id/include"
layout="#layout/content_main"/>
content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="?attr/actionBarSize">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:scrollbars="vertical"/>
There are Contexts considerations you need to make throught your code. You may be using the wrong Contexts example very big Contexts. For example from what I can see fast one of it is this line in MainFragment.java:
mAdapter=new GalleryAdapter(getActivity().getApplicationContext(),images);
You have passed the application context while you need just Context from Activity. So change that to:
mAdapter=new GalleryAdapter(getActivity(),images); // remove the method getApplicationContext
Try doing that if it will work or else lets try finding more code that may bring a problem.