I have made a meme app, which fetches image url from an API and i m parsing them and showing in recyler view using Glide , in my item layout i have two buttons one for sharing and one for download Image , i want when user clicks the download button the images get download to the user phone.
Help me how i can implement this.
MyAdapter class
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
Context context;
ArrayList<Model> modelArrayList;
public Adapter(Context context, ArrayList<Model> modelArrayList) {
this.context = context;
this.modelArrayList = modelArrayList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_layout, parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
String url = modelArrayList.get(position).getUrl();
holder.setImage(url);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent sharing = new Intent (Intent.ACTION_SEND);
sharing.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sharing.setType("text/plain");
String subject = "Hey Man just look at this coll meme click the link " +url;
sharing.putExtra(Intent.EXTRA_TEXT,subject);
context.startActivity(Intent.createChooser(sharing,"Shring using"));
}
});
holder.buttonDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
#Override
public int getItemCount() {
return modelArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
Button button,buttonDownload;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
button = itemView.findViewById(R.id.button);
buttonDownload = itemView.findViewById(R.id.btn_download);
}
void setImage(String link){
Glide.with(context).load(link).into(imageView);
}
}
}
My model class
public class Model {
String url;
public Model(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
My item_layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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">
<ImageView
android:id="#+id/imageView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_margin="8dp"
app:layout_constraintBottom_toTopOf="#+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_launcher_background"
tools:ignore="VectorDrawableCompat" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="104dp"
android:layout_marginLeft="104dp"
android:layout_marginBottom="28dp"
android:text="Share"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/btn_download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="71dp"
android:layout_marginRight="71dp"
android:layout_marginBottom="28dp"
android:text="Download"
android:textColor="#0B0B0B"
app:backgroundTint="#12E71A"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
My mainactivity.java
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
Adapter adapter;
ArrayList<Model> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recylerview_id);
arrayList = new ArrayList<>();
String url = "https://meme-api.herokuapp.com/gimme/30";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("memes");
for (int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String url = jsonObject.getString("url");
Model m = new Model(url);
arrayList.add(m);
}
adapter = new Adapter(MainActivity.this,arrayList);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
}
}
Glide allows to load a Bitmap.
you can save Bitmap to file, and then just pass file path to another screen.
Here you can find detailed tutorial, how to store image to file with Glide library:
https://medium.com/#akshayranagujjar/how-to-save-image-to-storage-using-glide-in-android-fa26c842f212
And don't forget about storage permissions.
Related
I'm having trouble getting my image to output. I want to output the data from a API in a recycler view using retrofit and Gson. I've read through the documentation and some stackoverflow pages. I am not using a third party library (such as picasso) so I am using AsyncTask. The photo class is the typical POJO class, and I put the internet permission. Here is the code:
RecyclerViewAdapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> {
List<Photo> photos;
ClickListener ClickListener;
public RecyclerViewAdapter(List<Photo> photos, ClickListener ClickListener) {
this.photos = photos;
this.ClickListener = ClickListener;
}
interface ClickListener {
void getItem(int position);
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.child_view, parent, false);
return new RecyclerViewHolder(view, ClickListener);
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, #SuppressLint("RecyclerView") int position) {
holder.title.setText(photos.get(position).title);
holder.albumid.setText(photos.get(position).albumId);
holder.regid.setText(photos.get(position).id);
new Thread(new Runnable(){
#Override
public void run() {
holder.circleImageView.setImageBitmap(getBitmapFromURL(photos.get(position).thumbnailUrl));
holder.imageView.setImageBitmap(getBitmapFromURL(photos.get(position).url));
}
}).start();
}
#Override
public int getItemCount() {
return photos.size();
}
class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title, albumid, regid;
ImageView imageView;
ClickListener ClickListener;
CircleImageView circleImageView;
public RecyclerViewHolder(View itemView, ClickListener ClickListener) {
super(itemView);
title = itemView.findViewById(R.id.title);
albumid = itemView.findViewById(R.id.albumid);
regid = itemView.findViewById(R.id.id);
imageView = itemView.findViewById(R.id.url);
circleImageView = itemView.findViewById(R.id.thumb);
this.ClickListener = ClickListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
ClickListener.getItem(getAdapterPosition());
}
}
public static Bitmap getBitmapFromURL(String src) {
try {
Log.e("src",src);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap","returned");
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception",e.getMessage());
return null;
}
}
}
Main Activity
public class MainActivity extends AppCompatActivity implements RecyclerViewAdapter.ClickListener {
ApiInterface apiInterface;
RecyclerView mRecyclerView;
List<Photo> photos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
apiInterface = ApiClient.getClient().create(ApiInterface.class);
apiInterface.getPhotos().enqueue(new Callback<List<Photo>>() {
#Override
public void onResponse(Call<List<Photo>> call, Response<List<Photo>> response) {
photos = response.body();
mRecyclerView.setAdapter(new RecyclerViewAdapter(photos, MainActivity.this));
}
#Override
public void onFailure(Call<List<Photo>> call, Throwable t) {
}
});
}
#Override
public void getItem(int position) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this)
.setTitle(photos.get(position).title)
.setMessage(photos.get(position).url)
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog.show();
}
}
APIClient
public class ApiClient {
private static final String BASE_URL = "https://jsonplaceholder.typicode.com/";
private static Retrofit retrofit = null;
public static Retrofit getClient(){
if (retrofit == null){
retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}
APIInterface
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface ApiInterface {
#GET("/photos")
Call<List<Photo>> getPhotos();
#GET("/photos/{id}")
Call<Photo> getPhoto(#Path("id") int id);
#GET("/photos")
Call<Photo> getPhotoUsingQuery(#Query("id") int id);
}
Child View
<?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:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/thumb"
android:layout_width="138dp"
android:layout_height="match_parent"
app:civ_border_color="#FF000000"
app:civ_border_width="2dp" />
<LinearLayout
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView" />
<TextView
android:id="#+id/albumid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView" />
<TextView
android:id="#+id/id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView" />
</LinearLayout>
<ImageView
android:id="#+id/url"
android:layout_width="50dp"
android:layout_height="120dp"
android:layout_weight="1" />
</LinearLayout>
I am working on a firebase project but I am facing a problem like when I upload an image on firebase I am not getting it in my original apk. I upload an image on firebase and save its URL in the firebase database and then when I load it with the Recycler view and Glide library it stuck on the placeholder image but did not load the original image. Can anyone help me to solve this problem I provided my source code below:-
EventActivity:-
public class EventActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ImageAdapter imageAdapter;
private DatabaseReference mDatabaseRef;
private List<Upload> mUploads;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
mDatabaseRef = FirebaseDatabase.getInstance().getReference("NotifyImages");
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mUploads = new ArrayList<>();
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Upload upload = postSnapshot.getValue(Upload.class);
mUploads.add(upload);
}
imageAdapter = new ImageAdapter(EventActivity.this, mUploads);
mRecyclerView.setAdapter(imageAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Upload class:-
public class Upload {
private String mName;
private String mImageUri;
public Upload() {
}
public Upload(String name, String ImageUri) {
if (name.trim().equals("")) {
name = "No name";
}
mName = name
;
mImageUri = ImageUri;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getImageUri() {
return mImageUri;
}
public void setImageUri(String ImageUri) {
mImageUri = ImageUri;
}
}
Image Adapter:-
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context mContext;
private List<Upload> mUploads;
public ImageAdapter(Context context, List<Upload> uploads) {
mContext = context;
mUploads = uploads;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
// Glide.with(mContext)
// .load(uploadCurrent.getImageUri())
// .centerCrop()
// .into(holder.imageView);
Glide.with(mContext)
.load(uploadCurrent.getImageUri())
.placeholder(R.mipmap.ic_launcher_round)
.centerCrop()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_view_name);
imageView = itemView.findViewById(R.id.image_upload);
}
}
}
activity_event.xml:-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
ImageItem.xml:-
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/text_view_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="8dp"
android:layout_marginBottom="80dp"
android:text="Name"
android:textColor="#color/ColorRed"
android:textSize="20sp" />
<ImageView
android:id="#+id/image_upload"
android:layout_width="match_parent"
android:layout_height="300dp"
/>
</LinearLayout>
</androidx.cardview.widget.CardView>
You can easily copy my code and test it. Please answer me if you find a solution.
Please make changes in your UploadFile() Function :
fireRef.putFile(ImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
}
} , 5000);
Toast.makeText(MainActivity.this, "Upload Successfull", Toast.LENGTH_SHORT).show();
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
Upload upload = new Upload(mainEditTextNotify.getText().toString().trim(),
downloadUrl.toString());
String uploadId = mDataRef.push().getKey();
mDataRef.child(uploadId).setValue(upload);
}
})
The above code will provide you proper uri of image which you can store inside Database.
It will provide you proper uri which will help to load images in Glide.
But i suggest to store filepath from Firebase Storage. Cause if uri token expires then you need generate uri token and change with old one.
I'm trying fetch all documents using FirestoreRecyclerAdapter here if there are 7 documents the RecyclerView items successfully populates with 7 items but here problem is the items which are having a text view are not getting populated with document names. Please take a look at my source code:
FriendsResponse Class:
#IgnoreExtraProperties
public class FriendsResponse {
FirebaseFirestore db;
public String getTable1() {
return Table1;
}
public void setTable1(String table1) {
Table1 = table1;
}
private String Table1;
public FriendsResponse() {
}
public FriendsResponse(String Table1) {
this.Table1 = Table1;
}
}
TableList Fragment where recyclerview is initialized:
public class TableListFragment extends Fragment{
private FirebaseFirestore db;
private FirestoreRecyclerAdapter adapter;
String documentnm;
RecyclerView recyclerView;
FloatingActionButton addt;
private StaggeredGridLayoutManager _sGridLayoutManager;
public static TableListFragment newInstance() {
TableListFragment fragment = new TableListFragment();
return fragment;
}
public TableListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tablelist, container, false);
recyclerView = view.findViewById(R.id.rectab);
addt=view.findViewById(R.id.addtab);
init();
getFriendList();
addt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
private void init(){
_sGridLayoutManager = new StaggeredGridLayoutManager(3,
StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(_sGridLayoutManager);
db = FirebaseFirestore.getInstance();
}
private void getFriendList(){
Query query = db.collection("Order");
FirestoreRecyclerOptions<FriendsResponse> response = new FirestoreRecyclerOptions.Builder<FriendsResponse>()
.setQuery(query, FriendsResponse.class)
.build();
adapter = new FirestoreRecyclerAdapter<FriendsResponse, FriendsHolder>(response) {
#Override
public void onBindViewHolder(FriendsHolder holder, int position, FriendsResponse model) {
holder.exname.setText(model.getTable1());
holder.itemView.setOnClickListener(v -> {
Snackbar.make(recyclerView, model.getTable1(), Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
});
}
#Override
public FriendsHolder onCreateViewHolder(ViewGroup group, int i) {
View view = LayoutInflater.from(group.getContext())
.inflate(R.layout.list_item, group, false);
return new FriendsHolder(view);
}
#Override
public void onError(FirebaseFirestoreException e) {
Log.e("error", e.getMessage());
}
};
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
public class FriendsHolder extends RecyclerView.ViewHolder {
TextView exname;
public FriendsHolder(View itemView) {
super(itemView);
exname= itemView.findViewById(R.id.topicname);
}
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
This is the code of list_item:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView android:id="#+id/cardvw"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="6dp"
card_view:cardElevation="3dp"
card_view:cardUseCompatPadding="true"
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto">
<LinearLayout android:orientation="vertical" android:padding="5dp" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/topiclogo"
android:layout_width="match_parent"
android:layout_gravity="center"
android:src="#drawable/table"
android:layout_height="wrap_content"
/>
<TextView android:textSize="15sp"
android:textStyle="bold"
android:textAlignment="center"
android:textColor="#ffffa200"
android:id="#+id/topicname"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v7.widget.CardView>
As I understand, you want to set the id of the document to that TextView. So because those names are actually documents ids, you should use the following lines of code inside onBindViewHolder() method:
String id = getSnapshots().getSnapshot(position).getId();
holder.exname.setText(id);
The POJO class that you are using is useful when getting the properties of the documents, not to get the document ids.
I have a recycle view which populates data from a server, the components inside are a textView and a Switch. The server can return n number of data. How can i set a unique id to the Switch2 when I am populating the data, because later I will need to set a listener to the Switches, My server actually returns a unique id but I'm not so sure on how to set it to the Switch2, or is there any alternate parameters that can be used to identify the Switch?
layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="wrap_content"
tools:layout_editor_absoluteY="81dp">
<android:android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="1dp"
card_view:cardUseCompatPadding="true"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Switch
android:id="#+id/switch2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left|center_vertical"
android:paddingLeft="5dip"
android:layout_marginTop="16dp"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="254dp" />
<TextView
android:id="#+id/user_set_light_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:fontFamily="sans-serif"
android:text="TextView"
android:textSize="20dp"
tools:layout_editor_absoluteX="27dp"
tools:layout_editor_absoluteY="23dp" />
</RelativeLayout>
</android:android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>
adapter
public class populateLights_adapter extends RecyclerView.Adapter<populateLights_adapter.ViewHolder> {
private List<populate_lights> listItems;
private Context context;
public populateLights_adapter(List<populate_lights> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.addlight_items, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
populate_lights listItem = listItems.get(position);
holder.lightText.setText(listItem.getLightName());
holder.status.setChecked(listItem.getState());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView lightText;
public Switch status;
public ViewHolder(View itemView) {
super(itemView);
lightText = (TextView) itemView.findViewById(R.id.user_set_light_id);
status = (Switch) itemView.findViewById(R.id.switch2);
}
}
}
java class
public class populate_lights {
private String lightName;
private boolean state;
public populate_lights(String lightName, boolean state){
this.lightName = lightName;
this.state = state;
}
public String getLightName(){
return lightName;
}
public boolean getState(){
return state;
}
}
main
public class lightsControl extends Fragment {
View myView;
public static final String URL = "serverurl.com";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<populate_lights> listItems;
private Switch mySwitch;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.lightscontrol, container, false);
recyclerView = (RecyclerView) myView.findViewById(R.id.lightsView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
listItems = new ArrayList<>();
loadData();
adapter = new populateLights_adapter(listItems, myView.getContext());
recyclerView.setAdapter(adapter);
return myView;
}
private void loadData(){
final ProgressDialog progressDialog = new ProgressDialog(myView.getContext());
progressDialog.setMessage("Loading");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
Snackbar mySnackbar = Snackbar.make(myView, "Data Fetched!", Snackbar.LENGTH_SHORT);
mySnackbar.show();
Log.v("DATA_RESPONSE", response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("lightData");
for(int i=0;i<array.length();i++){
JSONObject obj = array.getJSONObject(i);
Log.v("LIGHT ID ", "index=" + obj.getString("LightID"));
Log.v("Value ", "index=" + obj.getBoolean("Value"));
populate_lights popLights = new populate_lights(
obj.getString("LightID"), //unique id
obj.getBoolean("Value") //value returns true, or false
);
listItems.add(popLights);
}
adapter = new populateLights_adapter(listItems, myView.getContext());
recyclerView.setAdapter(adapter);
}
catch(Exception e){
e.printStackTrace();
}
}},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Snackbar mySnackbar = Snackbar.make(myView, "Oops, there was an error communicating with our server, try again", Snackbar.LENGTH_SHORT);
mySnackbar.show();
Log.v("LoginFormERROR", "index=" + error);
progressDialog.dismiss();
}
}
)
};
RequestQueue requestQueue = Volley.newRequestQueue(myView.getContext());
requestQueue.add(stringRequest);
}
public void showErrorAlert(){
AlertDialog.Builder builder1 = new AlertDialog.Builder(myView.getContext());
builder1.setMessage("Opps, something went wring");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Main Menu",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
getActivity().onBackPressed();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
screenshot
See if this code prints the right position in the logs. Put this inside the constructor of the view holder in the adapter class:
status.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
Log.d("Position: ", String.valueOf(getLayoutPosition()));
}
});
I am developing an android app, where I am trying to implement one feature for Image gallary. Now, initially, I want to show some image url with their title name. I am using hashmap for mapping title with their image.I have the model class with two String fields url and title. But The problem is I am very new in the development field and now sure how to show the title based on image click. Here is my model Class
public class ImageModel implements Parcelable {
String name, url;
public ImageModel() {
}
protected ImageModel(Parcel in) {
name = in.readString();
url = in.readString();
}
public static final Creator<ImageModel> CREATOR = new Creator<ImageModel>() {
#Override
public ImageModel createFromParcel(Parcel in) {
return new ImageModel(in);
}
#Override
public ImageModel[] newArray(int size) {
return new ImageModel[size];
}
};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(url);
}
}
Now the Main activity where I create a Hashmap with image and title to show those into views.
public class MainActivity extends AppCompatActivity {
GalleryAdapter mAdapter;
RecyclerView mRecyclerView;
ArrayList<ImageModel> data = new ArrayList<>();
ArrayList<HashMap<String, String>> arrayList = new ArrayList<>();
HashMap<String, String> h1 = new HashMap<>();
String[] imgUrls = {"https://images.unsplash.com/photo-1444090542259-0af8fa96557e?q=80&fm=jpg&w=1080&fit=max&s=4b703b77b42e067f949d14581f35019b",
"https://images.unsplash.com/photo-1439546743462-802cabef8e97?dpr=2&fit=crop&fm=jpg&h=725&q=50&w=1300",
"https://images.unsplash.com/photo-1441155472722-d17942a2b76a?q=80&fm=jpg&w=1080&fit=max&s=80cb5dbcf01265bb81c5e8380e4f5cc1"};
String[] imgNames = {"name1","name2","name3"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int i = 0; i < 3; i++) { //change size according to your size.
ImageModel imageModel = new ImageModel();
imageModel.setName(imgNames[i]);
imageModel.setUrl(imgUrls[i]);
data.add(imageModel);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mRecyclerView = (RecyclerView) findViewById(R.id.list);
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
mRecyclerView.setHasFixedSize(true);
mAdapter = new GalleryAdapter(MainActivity.this, data);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this,
new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putParcelableArrayListExtra("data", data);
intent.putExtra("pos", position);
startActivity(intent);
}
}));
}
}
GalleryAdapterCode
public class GalleryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
List<ImageModel> data = new ArrayList<>();
public GalleryAdapter(Context context, List<ImageModel> data) {
this.context = context;
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder;
View v;
v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_item, parent, false);
viewHolder = new MyItemHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Glide.with(context).load(data.get(position).getUrl())
.thumbnail(0.5f)
.override(200,200)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(((MyItemHolder) holder).mImg);
((MyItemHolder) holder).mTextView.setText(data.get(position).getName());
}
#Override
public int getItemCount() {
return data.size();
}
public static class MyItemHolder extends RecyclerView.ViewHolder {
ImageView mImg;
TextView mTextView;
public MyItemHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.textView);
mImg = (ImageView) itemView.findViewById(R.id.item_img);
}
}
}
My XML Class for item list row is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<ImageView
android:id="#+id/item_img"
android:layout_width="match_parent"
android:layout_height="188dp"
android:adjustViewBounds="true"
android:background="#color/colorAccent"
android:contentDescription="#string/app_name"
android:scaleType="centerCrop"
android:src="#drawable/placeholder" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#7000"
android:orientation="vertical"
android:padding="10dp"
android:layout_alignBottom="#+id/item_img"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/textView"
android:text="Headline"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:textSize="15dp"
android:textStyle="normal|bold"
/>
</LinearLayout>
</RelativeLayout>
Create two String arrays one containing image urls and other names in MainActivity.
String[] imgUrls = {"url1","url2","url3"};
String[] imgNames = {"name1","name2","name3"};
Iterate over those arrays and create a list of the model class.
ArrayList<ImageModel> data = new ArrayList<ImageModel>();
for (int i = 0; i < 3; i++) { //change size according to your size.
ImageModel imageModel = new ImageModel();
imageModel.setName(imgNames[i]);
imageModel.setUrl(imgUrls[i]);
data.add(imageModel);
}
mAdapter = new GalleryAdapter(MainActivity.this, data);
mRecyclerView.setAdapter(mAdapter);
Add a TextView in your RecyclerView row layout R.layout.list_item.
In your adapter use this TextView to set name of image.
public static class MyItemHolder extends RecyclerView.ViewHolder {
ImageView mImg;
TextView mTextView;
public MyItemHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.item_textview);
mImg = (ImageView) itemView.findViewById(R.id.item_img);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Glide.with(context).load(data.get(position).getUrl())
.thumbnail(0.5f)
.override(200,200)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(((MyItemHolder) holder).mImg);
holder.mTextView.setText(data.get(position).getName());
}
Rest of your code will be the same.