Guys the Adapter in that case is showing the images but not the name(note im using the caption in the data but that is cuz is not repaired but it is still String)
layout_grid_imageview.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">
<com.test.mine.Utils.SquareImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:id="#+id/gridImageView"/>
<ProgressBar
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerInParent="true"
android:id="#+id/gridImageProgressbar"/>
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Name of The Picture"
android:id="#+id/txt_grid_name_ingredient"/>
</androidx.cardview.widget.CardView>
</RelativeLayout>
I want on the place of the "Name of the picture" to set custom name from data. But i cant do it somehow
This is my adapter GridImageAdapter.java
public class GridImageAdapter extends ArrayAdapter<String>{
private LayoutInflater mInflater;
private int layoutResource;
private String mAppend;
private ArrayList<String> imgURLs;
private ArrayList<String> imgNames;
public GridImageAdapter(Context context, int layoutResource, String append, ArrayList<String> imgURLs, ArrayList<String> imgNames){
super(context, layoutResource, imgURLs);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.layoutResource = layoutResource;
mAppend = append;
this.imgURLs = imgURLs;
this.imgNames = imgNames;
}
private static class ViewHolder{
TextView ingredientName;
SquareImageView image;
ProgressBar mProgressBar;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
/*
Viewholder build pattern (Similar to recyclerview)
*/
final ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(layoutResource, parent, false);
holder = new ViewHolder();
holder.ingredientName = convertView.findViewById(R.id.txt_grid_name_ingredient);
holder.image = (SquareImageView) convertView.findViewById(R.id.gridImageView);
holder.mProgressBar = (ProgressBar) convertView.findViewById(R.id.gridImageProgressbar);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
String imgURL = getItem(position);
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(mAppend + imgURL, holder.image, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.VISIBLE);
}
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
});
return convertView;
}
}
And this is the profile where everything shoud be shown
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.bumptech.glide.Glide;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.test.mine.R;
import com.test.mine.Utils.GridImageAdapter;
import com.test.mine.models.Comments;
import com.test.mine.models.Likes;
import com.test.mine.models.Photo;
import com.test.mine.models.Users;
public class ProfileFragment extends Fragment {
private static final int NUM_GRID_COLUMNS = 2;
private static final String TAG ="mProfileFragment" ;
ImageView account_setting_menu;
Button editProfile;
ImageView profilePhoto;
GridView mGridRecipesView;
TextView posts,followers,followings,name, description,website,username;
LinearLayout follower,following;
String noFollowers,noFollowings;
DatabaseReference databaseReference;
private ProgressBar mProgressBar;
private LinearLayout profileItemsView;
#Nullable
#Override
public View onCreateView(#NonNull final LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profile,null);
return v;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
account_setting_menu = (ImageView) view.findViewById(R.id.account_settingMenu);
editProfile = (Button)view.findViewById(R.id.edit_profile);
profilePhoto = (ImageView)view.findViewById(R.id.user_img);
mGridRecipesView = (GridView) view.findViewById(R.id.gridview1);
posts = (TextView)view.findViewById(R.id.txtPosts);
followers = (TextView)view.findViewById(R.id.txtFollowers);
followings = (TextView)view.findViewById(R.id.txtFollowing);
name = (TextView)view.findViewById(R.id.display_name);
description = (TextView)view.findViewById(R.id.description);
website = (TextView)view.findViewById(R.id.website);
username = (TextView)view.findViewById(R.id.profileName);
follower = (LinearLayout)view.findViewById(R.id.FragmentProfile_followerLinearLayout);
following = (LinearLayout)view.findViewById(R.id.FragmentProfile_followingLinearLayout);
mProgressBar = (ProgressBar) view.findViewById(R.id.profileProgressBar);
profileItemsView = view.findViewById(R.id.layout_profile_books_view);
// Retrieving Photos and displaying in profile
tempGridSetup();
// Retrieving data
String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
databaseReference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
databaseReference.keepSynced(true);
addEventListener();
account_setting_menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent =new Intent(getActivity(),Account_Settings.class);
startActivity(intent);
}
});
editProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),EditProfile.class);
startActivity(intent);
}
});
follower.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(),FollowersFollowing.class);
intent.putExtra("id",FirebaseAuth.getInstance().getCurrentUser().getUid());
intent.putExtra("title","Followers");
intent.putExtra("number",noFollowers);
startActivity(intent);
}
});
following.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(),FollowersFollowing.class);
intent.putExtra("id",FirebaseAuth.getInstance().getCurrentUser().getUid());
intent.putExtra("title","Following");
intent.putExtra("number",noFollowings);
startActivity(intent);
}
});
}
private void addEventListener(){
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
final Users user = snapshot.getValue(Users.class);
Log.i(TAG, "ID: " + user.getUser_id());
posts.setText(user.getPosts());
noFollowers = user.getFollowers();
noFollowings = user.getFollowing();
followers.setText(noFollowers);
followings.setText(noFollowings);
name.setText(user.getFullName());
description.setText(user.getDiscription());
website.setText(user.getWebsite());
username.setText(user.getUsername());
Glide.with(ProfileFragment.this)
.load(user.getProfilePhoto())
.into(profilePhoto);
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.i(TAG, "ID: " + "canceled");
}
});
}
private void tempGridSetup(){
Log.d(TAG, "setupGridView: Setting up image grid.");
final ArrayList<Photo> photos = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.keepSynced(true);
Query query = reference
.child("User_Photo")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for ( DataSnapshot singleSnapshot : snapshot.getChildren()){
Photo photo = new Photo();
Map<String, Object> objectMap = (HashMap<String, Object>) singleSnapshot.getValue();
Log.d(TAG, "setupGridView(objectMap)"+objectMap.get("caption"));
photo.setCaption(objectMap.get("caption").toString());
photo.setTags(objectMap.get("tags").toString());
photo.setPhoto_id(objectMap.get("photo_id").toString());
photo.setUser_id(objectMap.get("user_id").toString());
photo.setDate_Created(objectMap.get("date_Created").toString());
photo.setImage_Path(objectMap.get("image_Path").toString());
List<Comments> comments = new ArrayList();
for (DataSnapshot dSnapshot : singleSnapshot
.child("comments").getChildren()){
Comments comment = new Comments();
comment.setUser_id(dSnapshot.getValue(Comments.class).getUser_id());
comment.setComment(dSnapshot.getValue(Comments.class).getComment());
comment.setDate_created(dSnapshot.getValue(Comments.class).getDate_created());
comments.add(comment);
}
photo.setComments(comments);
List<Likes> likesList = new ArrayList<Likes>();
for (DataSnapshot dSnapshot : singleSnapshot
.child("likes").getChildren()){
Likes like = new Likes();
like.setUser_id(dSnapshot.getValue(Likes.class).getUser_id());
likesList.add(like);
}
photo.setLikes(likesList);
photos.add(photo);
// photos.add(singleSnapshot.getValue(Photo.class));
}
//setup our image grid
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth/NUM_GRID_COLUMNS;
mGridRecipesView.setColumnWidth(imageWidth);
mGridRecipesView.setNumColumns(NUM_GRID_COLUMNS);
ArrayList<String> imgUrls = new ArrayList();
ArrayList<String> imgNames = new ArrayList<>();
for(int i = 0; i < photos.size(); i++){
imgUrls.add(photos.get(i).getImage_Path());
imgNames.add(photos.get(i).getCaption());
}
GridImageAdapter adapter = new GridImageAdapter(getActivity(),R.layout.layout_grid_imageview,
"", imgUrls, imgNames);
mGridRecipesView.setAdapter(adapter);
mGridRecipesView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ViewPostFragment fragment = new ViewPostFragment();
Bundle args = new Bundle();
args.putParcelable("PHOTO", photos.get(position));
Log.d(TAG, "getPhotoFromBundle(PHOTO): arguments: " + photos.get(position));
fragment.setArguments(args);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(ProfileFragment.this.getId(), fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d(TAG, "onCancelled: query cancelled.");
}
});
}
#Override
public void onResume() {
super.onResume();
addEventListener();
this.getView().setFocusableInTouchMode(true);
this.getView().requestFocus();
this.getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return false;
}
});
}
}
Related
I'm a beginner in Java and I'm trying to create a listener in my DialogFragment to notice my fragment that some book was removed. When the user removes a book, I want to call the removeBook method in BookFragment and update the recyclerview.
Here is my BookDialogFragment.java:
package com.compose.dietapp.ui.books;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import java.util.Objects;
public class BookDialogFragment extends DialogFragment {
private final String nameToDelete;
private final int position;
private static String MESSAGE_TO_DIALOG_FRAGMENT;
public BookDialogFragment(String nameToDelete, int position) {
this.nameToDelete = nameToDelete;
this.position = position;
}
public static BookDialogFragment newInstance(String title, String nameToDelete, int position) {
BookDialogFragment frag = new BookDialogFragment(nameToDelete, position);
if (Objects.equals(nameToDelete, "none")) {
MESSAGE_TO_DIALOG_FRAGMENT = "Book removed!";
} else {
MESSAGE_TO_DIALOG_FRAGMENT = "Are you sure you want to remove the book '"
+ nameToDelete
+ "'?";
}
Bundle args = new Bundle();
args.putString("title", title);
frag.setArguments(args);
return frag;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
assert getArguments() != null;
String title = getArguments().getString("title");
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setTitle(title);
alertDialogBuilder.setMessage(MESSAGE_TO_DIALOG_FRAGMENT);
if (Objects.equals(MESSAGE_TO_DIALOG_FRAGMENT, "Book removed!")) {
alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog != null) {
dialog.dismiss();
}
}
});
} else {
alertDialogBuilder.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// here I want to callback my fragment
BookFragment deleteBook = new BookFragment();
deleteBook.removeBook(nameToDelete, position);
Bundle result = new Bundle();
result.putBoolean("value", true);
getParentFragmentManager().setFragmentResult("removed", result);
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog != null) {
dialog.dismiss();
}
}
});
}
return alertDialogBuilder.create();
}
#Override
public void onStart() {
super.onStart();
((AlertDialog) Objects.requireNonNull(getDialog())).getButton(AlertDialog.BUTTON_NEGATIVE)
.setTextColor(Color.rgb(128, 128, 128));
}
}
And here is my BookFragment.java:
package com.compose.dietapp.ui.books;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.compose.dietapp.R;
import com.compose.dietapp.database.DatabaseAccess;
import com.compose.dietapp.databinding.FragmentBookBinding;
import java.util.ArrayList;
public class BookFragment extends Fragment{
#SuppressLint("StaticFieldLeak")
private static Activity activity;
private RecyclerView recyclerView;
private final ArrayList<Book> itensBook = new ArrayList<Book>();
private BookAdapter bookAdapter;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
activity = this.getActivity();
View v = inflater.inflate(R.layout.fragment_book, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.book_recycler);
instanciateBooks();
return v;
}
private void instanciateBooks() {
ArrayList<ArrayList<String>> bookDatabaseValues = getDatabaseData();
if (recyclerView != null && bookDatabaseValues != null) {
createItemBook(bookDatabaseValues);
createRecyclerViewBook();
}
}
public void removeBook(String nameToDelete, int position) {
getChildFragmentManager().setFragmentResultListener("removed",
this, new FragmentResultListener() {
#Override
public void onFragmentResult(#NonNull String requestKey, #NonNull Bundle bundle) {
String result = bundle.getString("value");
Log.i("result", result);
}
});
}
private void createRecyclerViewBook() {
recyclerView.setHasFixedSize(true);
bookAdapter = new BookAdapter(activity, itensBook);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(activity,
LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(bookAdapter);
}
private void createItemBook(ArrayList<ArrayList<String>> bookDatabaseValues) {
for (int i = 0; i < bookDatabaseValues.size(); i++) {
itensBook.add(new Book(
String.valueOf(bookDatabaseValues.get(i).get(0)),
String.valueOf(bookDatabaseValues.get(i).get(1)),
String.valueOf(bookDatabaseValues.get(i).get(2)),
String.valueOf(bookDatabaseValues.get(i).get(3)),
String.valueOf(bookDatabaseValues.get(i).get(4))
));
}
}
public static ArrayList<ArrayList<String>> getDatabaseData() {
if (activity != null) {
return getArrayListsFromDatabase();
}
return null;
}
private static ArrayList<ArrayList<String>> getArrayListsFromDatabase() {
DatabaseAccess databaseAccess = openDatabase();
ArrayList<ArrayList<String>> books = databaseAccess.getBook();
closeDatabase(databaseAccess);
return books;
}
private static void closeDatabase(DatabaseAccess databaseAccess) {
databaseAccess.close();
}
#NonNull
private static DatabaseAccess openDatabase() {
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(activity);
databaseAccess.open();
return databaseAccess;
}
}
Here is my BookAdapter.java:
package com.compose.dietapp.ui.books;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import com.compose.dietapp.R;
import java.io.InputStream;
import java.util.ArrayList;
public class BookAdapter extends RecyclerView.Adapter<BookViewHolder> {
public static FragmentManager supportFragment;
private final Context context;
private final ArrayList<Book> itens;
public BookAdapter(Context context, ArrayList<Book> itens) {
this.context = context;
this.itens = itens;
}
#NonNull
#Override
public BookViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_recycler_book, parent, false);
BookViewHolder viewHolder = new BookViewHolder(view);
supportFragment = ((AppCompatActivity)context).getSupportFragmentManager();
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull BookViewHolder bookViewHolder, int position) {
Book book = itens.get(position);
bookViewHolder.nome.setText(book.getName());
bookViewHolder.bookType.setText(book.getBookType());
imageInstanciate(bookViewHolder);
}
private void imageInstanciate(#NonNull BookViewHolder bookViewHolder) {
new DownloadImageFromInternet((ImageView) bookViewHolder.bookImage)
.execute("https://pbs.twimg.com/profile_images/630285593268752384/iD1MkFQ0.png");
}
private class DownloadImageFromInternet extends AsyncTask<String, Void, Bitmap> {
ImageView imageView;
public DownloadImageFromInternet(ImageView imageView) {
this.imageView = imageView;
}
protected Bitmap doInBackground(String... urls) {
String imageURL = urls[0];
Bitmap bimage = null;
try {
InputStream in = new java.net.URL(imageURL).openStream();
bimage = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error Message", e.getMessage());
e.printStackTrace();
}
return bimage;
}
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
}
#Override
public int getItemCount() {
return itens.size();
}
}
Here is my BookViewHolder.java:
package com.compose.dietapp.ui.books;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import com.compose.dietapp.R;
public class BookViewHolder extends RecyclerView.ViewHolder {
TextView nome;
TextView bookType;
ImageView bookImage;
public BookViewHolder(#NonNull View itemView) {
super(itemView);
nome = itemView.findViewById(R.id.nome);
bookType = itemView.findViewById(R.id.email);
bookImage = itemView.findViewById(R.id.book_image);
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
int position = getLayoutPosition();
return true;
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String nomeDelete = nome.getText().toString();
int position = getLayoutPosition();
FragmentManager fm = BookAdapter.supportFragment;
BookDialogFragment bookDialogFragment =
BookDialogFragment.newInstance("Atenção:", nomeDelete, position);
bookDialogFragment.show(fm, "fragment_alert");
}
});
}
}
I've seen other similar solutions, but I didn't get to implement them in my code. Can anyone help me?
Going through your code, it doesn't seem like you're using Navigation Component. So let's do it this way.
Your BookDialogFragment is a child fragment to BookFragment. So basically, you should set a result in your dialog when remove button is clicked. Then set up a result listener code in you parent fragment (BookFragment), so as to get immediate result to act upon.
First part, set a result when remove is clicked
NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
...
if (Objects.equals(MESSAGE_TO_DIALOG_FRAGMENT, "Book removed!")) {
...
} else {
alertDialogBuilder.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// here I want to callback my fragment
BookFragment deleteBook = new BookFragment();
deleteBook.removeBook(nameToDelete, position);
Bundle result = new Bundle();
result.putBoolean("value", true);
getParentFragmentManager().setFragmentResult("removed", result);
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
...
}
}
}
Then, listen for and act on the result in you BookFragment, wherever you want to, with these lines.
getChildFragmentManager().setFragmentResultListener("removed", this, new FragmentResultListener() {
#Override
public void onFragmentResult(#NonNull String requestKey, #NonNull Bundle bundle) {
// We use a Boolean here, but any type that can be put in a Bundle is supported
Boolean result = bundle.getString("value");
// Do something with the result
}
});
PS: You can use constant variables where you have "removed" and "value" for accuracy.
Hope this helps :)
I am trying to send the user to another activity when he clicks on the picture inside the recycle view after gathering the position, the problem whatever I do i still gitting null on the Adapter when using context, please find the codes below and describe to me what is the thing that I missed ?!
the problem is in the codes of onclick method ( last one ):-
package com.example.boc.Teachers;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.boc.R;
import com.example.boc.main.DashboardActivity;
import java.util.ArrayList;
public class TeachersAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private LayoutInflater mInflater;
private ArrayList<TeachersModel> items;
private TeacherMain mActivity;
private Context context;
public TeachersAdapter(ArrayList<TeachersModel> data, TeacherMain activity) {
this.items = data;
this.mActivity = activity;
this.mInflater = LayoutInflater.from(mActivity);
}
public void addItem(TeachersModel result) {
items.add(result);
}
public TeachersAdapter(Context context) {
this.context = context;
}
public void setInflater(LayoutInflater layoutInflater){
this.mInflater =layoutInflater;
}
public void replaceItems(ArrayList<TeachersModel> newItems) {
this.items.clear();
for(TeachersModel item: newItems)
this.items.add(item);
}
public void insertItem(TeachersModel item) {
items.add(0, item);
}
public void clearItems(){
items.clear();
}
public void AddResults(ArrayList<TeachersModel> result) {
items.addAll(result);
}
public TeachersModel getItemsAt(int position){
return items.get(position);
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
TeachersModel model = items.get(position);
MessageViewHolder messageViewHolder = (MessageViewHolder) holder;
messageViewHolder.imageViewIcon.setBackgroundResource(model.getImage());
messageViewHolder.textViewName.setText(model.getName());
messageViewHolder.textViewStatus.setText(model.getStatus());
messageViewHolder.textViewMobile.setText(model.getMobile());
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rootCategoryView = mInflater.inflate(R.layout.row_item_teachers, parent, false);
return new MessageViewHolder(rootCategoryView, this);
}
private class MessageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView imageViewIcon;
private TextView textViewName;
private TextView textViewStatus;
private TextView textViewMobile;
private CardView cardView;
private MessageViewHolder(View itemView, TeachersAdapter adapter) {
super(itemView);
imageViewIcon = (ImageView) itemView.findViewById(R.id.imageViewIcon);
textViewName = (TextView) itemView.findViewById(R.id.textViewName);
textViewStatus = (TextView) itemView.findViewById(R.id.textViewStatus);
textViewMobile = (TextView) itemView.findViewById(R.id.textViewMobile);
cardView = (CardView) itemView.findViewById(R.id.cardView);
cardView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final int pos = getAdapterPosition();
if (pos == 0) {
imageViewIcon.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent( context, DashboardActivity.class );
context.startActivity( intent );
}
} );
Toast.makeText(mActivity, "Selected Item Position "+pos, Toast.LENGTH_SHORT).show();
}
}
}
}
I am assuming you are using the constrcutor without passing a context:
//update the constructor to take a context
public TeachersAdapter(ArrayList<TeachersModel> data, TeacherMain activity , Context context) {
this.items = data;
this.mActivity = activity;
this.mInflater = LayoutInflater.from(mActivity);
//add this
this.context = context;
}
Set the click listener in onBindViewHolder:
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
....
....
....
messageViewHolder.imageViewIcon.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, DashboardActivity.class );
context.startActivity(intent);
}
});
}
When you create the adapter in your activity, make sure to pass the correct context:
adapter = new TeachersAdapter(... , .... , getApplicationContext());
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
In my chat App FriendsFragment is shwoing blank. If I want to reflect that then, I have run the app, open the Friends tab in my app and after Instant run in Android studio and it will reflect. If it will not, then I have to add Log statement anywhere in my FriendsFragment, and run Instant run with exctly the open tab of friendsfragmet.
Why I'm telling you to add Log statement is necessary because I found this bug that whenever I change something on my Friends Fragment and then run Instant run, then only it will show the Fragment part. And I have to do this every time, otherwise it won't show. Add Log statement and remove second time, or change tag or change message, do something that makes the changes, and must run Instant run (that Yellow symbol like booster).
NOTE: I'm still doing this thing, I observe this problem by myself and I also don't know why I have to change something every time to show this Fragment? I also built the similar fragment in this same app, but for that there is no problem!
FriendFragment
package com.jimmytrivedi.lapitchat;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class FriendsFragment extends Fragment {
private RecyclerView FriendRecyclerView;
private DatabaseReference databaseReference, UsersDatabaseReference;
private FirebaseAuth mAuth;
private String currentUID;
private View MainView;
public FriendsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
MainView = inflater.inflate(R.layout.fragment_friend, container, false);
FriendRecyclerView = MainView.findViewById(R.id.FriendRecyclerView);
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
currentUID = mAuth.getCurrentUser().getUid();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Friends").child(currentUID);
databaseReference.keepSynced(true);
UsersDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
UsersDatabaseReference.keepSynced(true);
}
FriendRecyclerView.setHasFixedSize(true);
FriendRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
Log.d("wihddiewd", "Is it going?");
return MainView;
}
#Override
public void onStart() {
super.onStart();
Query query = FirebaseDatabase. getInstance()
.getReference()
.child("Friends")
.limitToLast(50);
FirebaseRecyclerOptions<Friends> options = new FirebaseRecyclerOptions.Builder<Friends>()
.setQuery(query, Friends.class)
.build();
final FirebaseRecyclerAdapter<Friends, FriendsViewHolder> FriendsRecyclerViewAdapter = new
FirebaseRecyclerAdapter<Friends, FriendsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final FriendsViewHolder holder, int position, #NonNull Friends model) {
holder.setDate(model.getDate());
final String listUID = getRef(position).getKey();
UsersDatabaseReference.child(listUID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
final String userName = dataSnapshot.child("Name").getValue().toString();
String thumbImage = dataSnapshot.child("thumbImage").getValue().toString();
String userOnline = dataSnapshot.child("Online").getValue().toString();
holder.setName(userName);
holder.setThumbImage(thumbImage, getContext());
holder.setUserOnline(userOnline);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence options[] = new CharSequence[]{"Open profile", "Send message"};
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
Intent intent = new Intent(getContext(), ProfileActivity.class);
intent.putExtra("userID", listUID);
startActivity(intent);
}
if (which == 1) {
Intent intent = new Intent(getContext(), ChatActivity.class);
intent.putExtra("userID", listUID);
intent.putExtra("userName", userName);
startActivity(intent);
}
}
});
builder.show();
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public FriendsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_single_layout, parent, false);
return new FriendsViewHolder(view);
}
};
FriendRecyclerView.setAdapter(FriendsRecyclerViewAdapter);
FriendsRecyclerViewAdapter.startListening();
}
public static class FriendsViewHolder extends RecyclerView.ViewHolder {
View mView;
public FriendsViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDate(String date) {
TextView userStatusView = mView.findViewById(R.id.userStatus);
userStatusView.setText(date);
}
public void setName(String name) {
TextView userNameView = mView.findViewById(R.id.userName);
userNameView.setText(name);
}
public void setThumbImage(String thumbImage, Context context) {
CircleImageView circleImageView = mView.findViewById(R.id.userImage);
Picasso.get().load(thumbImage).placeholder(R.drawable.defaultimage)
.into(circleImageView);
}
public void setUserOnline(String online) {
ImageView userOnline = mView.findViewById(R.id.online);
if (online.equals("true")) {
userOnline.setVisibility(View.VISIBLE);
} else {
userOnline.setVisibility(View.INVISIBLE);
}
}
}
}
Update
I know this is weird bug. But basically when I open my app and in app firends tab (which is FriendsFragment.java), it is showing blank. So I tried to debug that is there any mistake on my code or not? But I didn't find. But while debugging time, when I go to my firends tab in my mobile app, and put any log statement in Android Studio (because when I add/remove something so Android Studio will understand that some changes made happen, and then I run Instant run(not normal run) then FriendFragment will reflect and it shows the user list.
And I have to do this every time, (means I have to add something/remove something, that consider changes for Android Studio) then only FriendsFragment will show the users list. And even if I not open my Friends tab, but open something else in app and than run (instant run) that is also not work! Only when I just go to friends tab (that time it is showing blank, but that is okay) and run Instant run, then only it will reflect.
fragment_friends.xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FriendsFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/FriendRecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
users_single_layout.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="wrap_content">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/userImage"
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_marginBottom="15dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:src="#drawable/defaultimage" />
<TextView
android:id="#+id/userName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/userImage"
android:layout_marginStart="99dp"
android:text="Display Name"
android:textColor="#000000"
android:textSize="18dp" />
<TextView
android:id="#+id/userStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/userName"
android:layout_below="#+id/userName"
android:text="User default Status"
android:textSize="15dp" />
<ImageView
android:id="#+id/online"
android:layout_width="8dp"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/userName"
android:layout_marginLeft="10dp"
android:layout_toEndOf="#+id/userName"
android:visibility="invisible"
android:src="#drawable/online" />
</RelativeLayout>
Another Fragment ChatFragment, which is similar to this and working pretty fine).
ChatFragment.java
package com.jimmytrivedi.lapitchat;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
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 com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class ChatFragment extends Fragment {
private RecyclerView ConversationList;
private DatabaseReference ConversationRef, MessageRef, UserRef;
private FirebaseAuth mAuth;
private String currentUID;
private View MainView;
public ChatFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
MainView = inflater.inflate(R.layout.fragment_chat, container, false);
ConversationList = MainView.findViewById(R.id.ConversationList);
mAuth = FirebaseAuth.getInstance();
currentUID = mAuth.getCurrentUser().getUid();
ConversationRef = FirebaseDatabase.getInstance().getReference().child("Chat").child(currentUID);
ConversationRef.keepSynced(true);
UserRef = FirebaseDatabase.getInstance().getReference().child("Users");
UserRef.keepSynced(true);
MessageRef = FirebaseDatabase.getInstance().getReference().child("Messages").child(currentUID);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
ConversationList.setHasFixedSize(true);
ConversationList.setLayoutManager(layoutManager);
return MainView;
}
#Override
public void onStart() {
super.onStart();
Query conversationQuery = ConversationRef.orderByChild("timestamp");
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Chat")
.limitToLast(50);
FirebaseRecyclerOptions<Conversation> options = new FirebaseRecyclerOptions.Builder<Conversation>()
.setQuery(query, Conversation.class)
.build();
FirebaseRecyclerAdapter<Conversation, ConversationViewHolder> ConversationRecyclerViewAdapter = new
FirebaseRecyclerAdapter<Conversation, ConversationViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final ConversationViewHolder holder, int position, #NonNull final Conversation model) {
final String listUID = getRef(position).getKey();
Query lastMessageQuery = MessageRef.child(listUID).limitToLast(1);
lastMessageQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
String data = dataSnapshot.child("message").getValue().toString();
holder.setMassage(data, model.isSeen());
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
UserRef.child(listUID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
final String userName = dataSnapshot.child("Name").getValue().toString();
String userThumb = dataSnapshot.child("thumbImage").getValue().toString();
if (dataSnapshot.hasChild("Online")) {
String userOnline = dataSnapshot.child("Online").getValue().toString();
holder.setUserOnline(userOnline);
}
holder.setName(userName);
holder.setUserImage(userThumb, getContext());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), ChatActivity.class);
intent.putExtra("userID", listUID);
intent.putExtra("userName", userName);
startActivity(intent);
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public ConversationViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_single_layout, parent, false);
return new ConversationViewHolder(view);
}
};
ConversationList.setAdapter(ConversationRecyclerViewAdapter);
ConversationRecyclerViewAdapter.startListening();
}
public static class ConversationViewHolder extends RecyclerView.ViewHolder {
View mView;
public ConversationViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setMassage(String message, boolean isSeen) {
TextView userStatusView = mView.findViewById(R.id.userStatus);
userStatusView.setText(message);
if (!isSeen) {
userStatusView.setTypeface(userStatusView.getTypeface(), Typeface.BOLD);
} else {
userStatusView.setTypeface(userStatusView.getTypeface(), Typeface.NORMAL);
}
}
public void setUserOnline(String online) {
ImageView userOnlineView = mView.findViewById(R.id.online);
if (online.equals("true")) {
userOnlineView.setVisibility(View.VISIBLE);
} else {
userOnlineView.setVisibility(View.INVISIBLE);
}
}
public void setName(String userName) {
TextView userNameView = mView.findViewById(R.id.userName);
userNameView.setText(userName);
}
public void setUserImage(String userThumb, Context context) {
CircleImageView userImageView = mView.findViewById(R.id.userImage);
Picasso.get().load(userThumb).placeholder(R.drawable.defaultimage).into(userImageView);
}
}
}
Friends.java
package com.jimmytrivedi.lapitchat;
public class Friends {
public String date;
public Friends() {
}
public Friends(String date) {
this.date = date;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
SectionPagerAdapter.java
package com.jimmytrivedi.lapitchat;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
RequestFragment requestFragment = new RequestFragment();
return requestFragment;
case 1:
ChatFragment chatFragment = new ChatFragment();
return chatFragment;
case 2:
FriendsFragment friendFragment = new FriendsFragment();
return friendFragment;
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Requests";
case 1:
return "Chats";
case 2:
return "Friends";
default:
return null;
}
}
}
MainActivity.java
package com.jimmytrivedi.lapitchat;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.facebook.login.LoginManager;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseUser currentUser;
private Toolbar toolbar;
private ViewPager viewPager;
private SectionsPagerAdapter sectionsPagerAdapter;
private TabLayout tabLayout;
private DatabaseReference UserDatabaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
if (currentUser == null) {
sendTostart();
} else {
UserDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
UserDatabaseReference.child("Online").setValue("true");
}
viewPager = findViewById(R.id.viewPager);
sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(sectionsPagerAdapter);
toolbar = findViewById(R.id.mainToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home");
tabLayout = findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
}
#Override
protected void onPause() {
super.onPause();
if (currentUser != null) {
UserDatabaseReference.child("Online").setValue(ServerValue.TIMESTAMP);
}
}
private void sendTostart() {
startActivity(new Intent(MainActivity.this, StartActivity.class));
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.logout) {
FirebaseAuth.getInstance().signOut();
LoginManager.getInstance().logOut();
sendTostart();
}
if (item.getItemId() == R.id.settings) {
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
}
if (item.getItemId() == R.id.allUsers) {
startActivity(new Intent(MainActivity.this, UsersActivity.class));
}
return true;
}
}
Use
`viewPager.setOffscreenPageLimit(3);`
after
viewPager.setAdapter(sectionsPagerAdapter);
inside MainActivity.
Use notifyDataSetChanged() after setting adapter to recyclerview.
FriendRecyclerView.setAdapter(FriendsRecyclerViewAdapter);
FriendsRecyclerViewAdapter.notifyDataSetChanged();
My RecyclerView have two problems :
The first problem is when i am finished working with its activity and press back button it creates the same activity again but after removing some row (Mostly from the end) ,, I don't know if the problem is it creates the view on multiple phases or what .
The second problem is when i press some button(Like button for example) it recreates the activity with the new result at each time it is pressed .
here is my Adapter
package com.example.agh.grad.Adapters;
import android.Manifest; import android.app.Activity; import
android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.support.v4.app.ActivityCompat; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.example.agh.grad.ItemClickListner; import com.example.agh.grad.Models.Services; import com.example.agh.grad.R; import com.example.agh.grad.SearchServices; import com.example.agh.grad.ServiceDetail; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import org.parceler.Parcels; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by cz on 17/06/17. */ public class recylerServiceAdapter extends RecyclerView.Adapter<recylerServiceAdapter.ViewHolder> { ArrayList<Services> service; Context context; ItemClickListner clickListner; public recylerServiceAdapter(ArrayList<Services> service, Context context) { this.service = service; this.context = context; } #Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_recyler_services, parent, false); ViewHolder viewHolder = new ViewHolder(v); context= parent.getContext(); return viewHolder; }
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.tvServiceName.setText(service.get(position).getName());
holder.tvServiceDisrption.setText(service.get(position).getServiceShortDesrption());
holder.tvServiceProvider.setText(service.get(position).getServiceProvider());
holder.tvLikeCounter.setText(String.valueOf(service.get(position).getLikes()));
holder.tvDislikeCounter.setText(String.valueOf(service.get(position).getDislikes()));
holder.tvLocationDescrption.setText(service.get(position).getLocationAddress());
holder.tvServiceName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/* Intent myIntent= new Intent(context,SearchServices.class);
context.startActivity(myIntent);*/
}
});
holder.btnLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final FirebaseDatabase firedatabase = FirebaseDatabase.getInstance();
DatabaseReference ref = firedatabase.getReference("Services");
DatabaseReference wantedService = ref.child(String.valueOf(service.get(holder.getAdapterPosition()).getName()));
final Long uplikes= service.get(holder.getAdapterPosition()).getLikes()+1;
wantedService.child("likes").setValue(uplikes, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
holder.tvLikeCounter.setText(String.valueOf(uplikes));
}
});
// TODO: 11/10/17 update on the database
//// TODO: 05/12/17 Check state of buttons and act upon it
holder.btnLike.setClickable(false);//// TODO: 05/12/17 set a clicked icon
holder.btnDislike.setClickable(false);
}
});
holder.btnDislike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final FirebaseDatabase firedatabase = FirebaseDatabase.getInstance();
DatabaseReference ref = firedatabase.getReference("Services");
DatabaseReference wantedService = ref.child(String.valueOf(service.get(holder.getAdapterPosition()).getName()));
final Long dislikes= service.get(holder.getAdapterPosition()).getLikes()-1;
wantedService.child("likes").setValue(dislikes, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
holder.tvLikeCounter.setText(String.valueOf(dislikes));
}
});
}
});
holder.btnCall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + service.get(holder.getAdapterPosition()).getPhoneNumber()));
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Ask for permission
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
context.startActivity(callIntent);
}
});
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent= new Intent(context,ServiceDetail.class);
myIntent.putExtra(SearchServices.PARCELER_TAG, Parcels.wrap(service.get(holder.getAdapterPosition()) ));
context.startActivity(myIntent);
((Activity)context).finish();
}
});
}
#Override
public int getItemCount() {
return service.size();
}
public void setClickListener(ItemClickListner itemClickListener) {
this.clickListner = itemClickListener;
}
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView (R.id.serviceName) TextView tvServiceName;
#BindView (R.id.serviceProvider)TextView tvServiceProvider;
#BindView (R.id.serviceShortDescrption)TextView tvServiceDisrption;
#BindView (R.id.tvLikeCounter)TextView tvLikeCounter;
#BindView (R.id.tvDislikeCounter)TextView tvDislikeCounter ;
#BindView (R.id.locationDescrption)TextView tvLocationDescrption;
#BindView (R.id.btnLike) Button btnLike;
#BindView (R.id.btnDislike) Button btnDislike;
#BindView (R.id.btnCall) Button btnCall;
#BindView (R.id.serviceCard) CardView cardView;
public ViewHolder(View itemView) {
super(itemView);
itemView.setTag(itemView);
ButterKnife.bind(this, itemView);
}
}
}
and here is my activity
public class MainActivity extends AppCompatActivity {
List<String> arrayServices = new ArrayList<>();
RecyclerView recyclerViewServices;
recylerServiceAdapter recylerServiceAdapter;
ArrayList<Services> newServices;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = this.getIntent();
// arrayServices= intent.getStringArrayListExtra("newServices");
// System.out.println(arrayServices.size());
newServices = Parcels.unwrap(intent.getParcelableExtra(SearchServices.PARCELER_TAG)) ;
Log.e( "onCreate: ",newServices.toString() );
recyclerViewServices = (RecyclerView) findViewById(R.id.recylerViewServiceDetail);
recyclerViewServices.setLayoutManager(new LinearLayoutManager(this));
recylerServiceAdapter = new recylerServiceAdapter(newServices, getApplicationContext());
recyclerViewServices.setAdapter(recylerServiceAdapter);
}
}
and my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"
android:background="#color/lightPrimary"
tools:context="com.example.agh.grad.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recylerViewServiceDetail"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="5dp"
tools:layout_editor_absoluteY="5dp" />
</RelativeLayout>
instead of using this
holder.tvServiceName.setText(service.get(position).getName());
use
holder.tvServiceName.setText(service.get(getAdapterPosition())
.getName());
Instead of using this in onClick
holder.getAdapterPosition()
use
public void onBindViewHolder(final ViewHolder holder,final int position)
position
Changing activity launch mode to android:launchMode="singleTask" solved the problem
I created a small application where I have a list of products and for each of the product I have an expiry time. If the user chooses to like a certain product(showTimerPost), the expiry time of the product will increase lets say 5 second. I tried it with a handler and it actually worked but my app started to run really slow maybe because it was changing the UI every second. I am really stuck with this problem for 1 month. Help will be appreciated.
package com.blueflair.incre;
import com.blueflair.incre.app.AppController;
import com.blueflair.incre.data.FeedItem;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
LocalUserData userLocalStore;
long postExpiry;
String timerFormat;
private int defaultPostIncrementation = 900000;
private List<FeedItem> feedItems;
boolean favourite;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private long timeDiff;
private final List<ViewHolder> lstHolders;
private int avatarSize;
Handler handler = new Handler();
private Runnable timerRunnable = new Runnable() {
#Override
public void run() {
for (final ViewHolder holder : lstHolders) {
holder.showTimerPost.postDelayed(new Runnable() {
#Override
public void run() {
long currentTime = System.currentTimeMillis();
currentTime--;
holder.showTimerPost.setText(String.valueOf(holder.updateTimeRemaining(currentTime)));
notifyDataSetChanged();
}
}, 2000);
}
}
};
public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
lstHolders = new ArrayList<>();
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.feed_item, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
final FeedItem item = feedItems.get(position);
holder = new ViewHolder();
userLocalStore = new LocalUserData(activity);
final User user = userLocalStore.getLoggedInUser();
postExpiry = item.getPostExpiry();
avatarSize = activity.getResources().getDimensionPixelSize(R.dimen.feed_avater_size);
holder.name = (TextView) convertView.findViewById(R.id.userFeedName);
holder.timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
holder.statusMsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
holder.profilePic = (ImageView) convertView
.findViewById(R.id.profilePic);
holder.profilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle args= new Bundle();
args.putInt("userId", item.getUserId());
Fragment profileViewFragment = new ProfileViewFragment();
profileViewFragment.setArguments(args);
FragmentTransaction ft = ((MainActivity)activity).getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.slide_in_done, R.anim.slide_out_send);
ft.replace(R.id.container_body, profileViewFragment);
ft.addToBackStack(null);
ft.commit();
}
});
holder.feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
String username = "#"+item.getUserName();
holder.name.setText(username);
convertView.setTag(holder);
synchronized ( lstHolders) {
lstHolders.add(holder);
}
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeCreated()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
holder.timestamp.setText(timeAgo);
holder.showTimerPost = (Button) convertView.findViewById(R.id.showPostTimer);
handler.post(timerRunnable);
holder.showTimerPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
item.setIncrementToExpiry(50000);
notifyDataSetChanged();
}
});
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getPostMessage())) {
holder.statusMsg.setText(item.getPostMessage());
holder.statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.statusMsg.setVisibility(View.GONE);
}
// Feed image
if (item.getUserImage() != null) {
holder.feedImageView.setImageUrl(item.getUserImage(), imageLoader);
holder.feedImageView.setVisibility(View.VISIBLE);
holder.feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
holder.feedImageView.setVisibility(View.GONE);
}
//Setting the timer adapter for the post and their respective contents
holder.setData(item);
return convertView;
}
private class ViewHolder {
FeedItem item;
public TextView name;
public TextView timestamp;
public TextView statusMsg;
public ImageView profilePic;
public FeedImageView feedImageView;
public Button showTimerPost;
public void setData(FeedItem item) {
this.item = item;
updateTimeRemaining(System.currentTimeMillis());
}
public String updateTimeRemaining(long currentTime) {
timeDiff = (item.getPostExpiry()+400000000) - currentTime;
if (timeDiff > 0) {
timerFormat = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(timeDiff),
TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)),
TimeUnit.MILLISECONDS.toSeconds(timeDiff) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeDiff)));
showTimerPost.setText(timerFormat);
return timerFormat;
} else {
//Delete feed items when post is expired
showTimerPost.setText("Expired!");//only to explimify
}
return timerFormat;
}
}
}