Check user online or offline icons - java

I have chat app and i have fragment and show in it my friends , and currently i think to add online and offline feature next to user name in my friend fragment, I wrote the code and it working without problem , But i need to add icon online or offline next to The Full name of users, In layout i added the icons but i can't control these in code, I want if user online.. online icon set visibilty visible and offline icon set visibilty invisible and i want if user offline.. online icon set invisible and offline icon set visible.. this is my problem just!
Note: The icons is ImageView...
I wrote comment above my problems in fisrt class and in layout xml..
I have to class the first class(FriendsFragment):
public class FriendsFragment extends Fragment {
public static int setOnlineSta;
RecyclerView results_list;
DatabaseReference mUDB,mUDBSec;
FirebaseUser mCurrentUser;
FriendsAdapter friendsAdapter;
ArrayList<String> fullNameList,userStatusList, userIdList, profileImageList;
View mMainView;
public FriendsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMainView = inflater.inflate(R.layout.fragment_friends, container, false);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String current_uid = mCurrentUser.getUid();
mUDB =
FirebaseDatabase.getInstance()
.getReference().child("Friends").child(current_ui
d);
mUDB.keepSynced(true);
mUDBSec = FirebaseDatabase.getInstance().getReference();
mUDBSec.keepSynced(true);
results_list = (RecyclerView) mMainView.findViewById(R.id.users_list);
results_list.setHasFixedSize(true);
results_list.setLayoutManager(new LinearLayoutManager(getActivity()));
results_list.addItemDecoration(new DividerItemDecoration(getActivity(),
LinearLayoutManager.VERTICAL));
fullNameList = new ArrayList<>();
userStatusList = new ArrayList<>();
userIdList = new ArrayList<>();
profileImageList = new ArrayList<>();
setAdapter();
return mMainView;
}
private void setAdapter() {
mUDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
final String uid = snapshot.getKey();
DatabaseReference userRef = mUDBSec.child("Users").child(uid);
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String uidSec = uid;
userIdList.add(uidSec);
String full_name = dataSnapshot.child("name").getValue(String.class);
String user_status = dataSnapshot.child("status").getValue(String.class);
String profile_pic = dataSnapshot.child("image").getValue(String.class);
fullNameList.add(full_name);
userStatusList.add(user_status);
profileImageList.add(profile_pic);
if (dataSnapshot.hasChild("online"))
{
// My Problem Here
Boolean userOnline_Check = (Boolean)
dataSnapshot.child("online").getValue();
if (userOnline_Check == true)
{
}
if (userOnline_Check == false)
{
}
}
friendsAdapter = new FriendsAdapter(getActivity(), fullNameList,
userStatusList, userIdList, profileImageList);
results_list.setAdapter(friendsAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}}
Second Class(FriendsAdapter):
public class FriendsAdapter extends
RecyclerView.Adapter<FriendsAdapter.FriendViewHolder> {
Context context;
ArrayList<String> fullNameList,userStatusList, userIdList,profileImageList;
class FriendViewHolder extends RecyclerView.ViewHolder
{
ImageView profileImage;
ImageView active_emo, not_active_emo;
TextView full_name, user_status,user_id;
public FriendViewHolder(View itemView) {
super(itemView);
full_name = (TextView) itemView.findViewById(R.id.user_single_name);
user_status = (TextView) itemView.findViewById(R.id.username_friend);
user_id = (TextView) itemView.findViewById(R.id.user_single_id);
profileImage = (ImageView) itemView.findViewById(R.id.user_single_image);
active_emo = (ImageView) itemView.findViewById(R.id.active_state);
not_active_emo = (ImageView) itemView.findViewById(R.id.not_active_state);
}
}
public FriendsAdapter(Context context, ArrayList<String> fullNameList,
ArrayList<String> userStatusList, ArrayList<String> userIdList,
ArrayList<String> profileImageList) {
this.context = context;
this.fullNameList = fullNameList;
this.userStatusList = userStatusList;
this.userIdList = userIdList;
this.profileImageList = profileImageList;
}
#Override
public FriendsAdapter.FriendViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view =
LayoutInflater.from(context).inflate(R.layout.users_single_layout, parent,
false);
return new FriendsAdapter.FriendViewHolder(view);
}
#Override
public void onBindViewHolder(final FriendsAdapter.FriendViewHolder holder,
final int position) {
holder.full_name.setText(fullNameList.get(position));
holder.user_status.setText(userStatusList.get(position));
holder.user_id.setText(userIdList.get(position));
Glide.with(context).load(profileImageList.get(position)).into(holder.profile
Image);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence options[] = new CharSequence[]{"Open Profile", "Send message"};
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if(i == 0){
Intent profileIntent = new Intent(context, UserProfile.class);
profileIntent.putExtra("USER_ID",String.valueOf(userIdList.get(position)));
context.startActivity(profileIntent);
}
if(i == 1){
Intent chatIntent = new Intent(context, Search.class);
chatIntent.putExtra("USER_ID",String.valueOf(userIdList.get(position)));
context.startActivity(chatIntent);
}
}
});
builder.show();
}
});
}
#Override
public int getItemCount() {
return fullNameList.size();
}}
My Layout code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/user_single_image"
android:layout_width="65dp"
android:layout_height="65dp"
android:padding="2dp"
android:src="#drawable/profile_default" />
<LinearLayout
android:layout_width="233dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/user_single_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Full name"
android:textColor="#color/bluePrim"
android:textSize="20sp" />
<TextView
android:id="#+id/username_friend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="User Name" />
<TextView
android:id="#+id/user_single_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="User Id"
android:visibility="gone" />
</LinearLayout>
<-- the icons below !-->
<ImageView
android:id="#+id/active_state"
android:layout_width="20dp"
android:layout_height="20dp"
android:src="#drawable/active"
android:visibility="invisible" />
<ImageView
android:id="#+id/not_active_state"
android:layout_width="20dp"
android:layout_height="20dp"
android:src="#drawable/notactive"
android:visibility="invisible" />
</LinearLayout>
</LinearLayout>
Thank you..

Related

I do not get any results from the recycler on Android studio

Well i think i got everything as they should be , i don't really know what i did wrong with the recycler but i still go error like "No adapter attached; skipping layout"
I NOTICED THAT ON UsersAdapter.java on the line "itemView.setOnClickListener(view -> onUserClickListener.onUserClicked(getAdapterPosition()));". getadapterposition is deprecated. Would that be the problem ?
Usersadapter.java
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.UserHolder> {
private final ArrayList<User> users;
private final Context context;
private final OnUserClickListener onUserClickListener;
public UsersAdapter(ArrayList<User> users, Context context, OnUserClickListener onUserClickListener) {
this.users = users;
this.context = context;
this.onUserClickListener = onUserClickListener;
}
interface OnUserClickListener{
void onUserClicked(int position);
}
#NonNull
#Override
public UserHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.user_holder,parent, false);
return new UserHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UserHolder holder, int position) {
holder.txtUsername.setText(users.get(position).getUsername());
Glide.with(context).load(users.get(position).getProfile_img()).error(R.drawable.account_img).placeholder(R.drawable.account_img).into(holder.profile_thumbnail);
}
#Override
public int getItemCount() {
return users.size();
}
class UserHolder extends RecyclerView.ViewHolder{
TextView txtUsername ;
ImageView profile_thumbnail;
public UserHolder(#NonNull View itemView){
super(itemView);
itemView.setOnClickListener(view -> onUserClickListener.onUserClicked(getAdapterPosition()));
txtUsername = itemView.findViewById(R.id.txtUsername);
profile_thumbnail = itemView.findViewById(R.id.profile_thumbnail);
}
}
}
user_holder.xml
<androidx.cardview.widget.CardView
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
app:cardBackgroundColor="#color/Color_grey"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="10dp"
android:layout_marginTop="10dp"
app:cardCornerRadius="14dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="7dp">
<androidx.cardview.widget.CardView
android:layout_width="70dp"
app:cardCornerRadius="180dp"
android:layout_height="70dp">
<ImageView
android:id="#+id/profile_thumbnail"
android:scaleType="centerCrop"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</androidx.cardview.widget.CardView>
<TextView
android:id="#+id/txtUsername"
android:layout_width="wrap_content"
android:layout_marginStart="20dp"
android:layout_gravity="center"
android:textColor="#color/white"
android:layout_height="wrap_content"
/>
</LinearLayout>
</androidx.cardview.widget.CardView>
activity_friends.xml
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
/>
FriendsActivity.java
public class FriendsActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ArrayList<User> users;
private ProgressBar progressBar_connectivity;
private UsersAdapter userAdapter;
UsersAdapter.OnUserClickListener onUserClickListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_friends);
progressBar_connectivity = findViewById(R.id.progressBar_connectivity);
users = new ArrayList<>();
recyclerView = findViewById(R.id.recycler);
onUserClickListener = position -> Toast.makeText(FriendsActivity.this,"Tapped this User "+users.get(position).getUsername(),Toast.LENGTH_SHORT).show();
getUsers();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.profile_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item){
if(item.getItemId() == R.id.menu_item_profile){
startActivity(new Intent(FriendsActivity.this, Profile.class));
}
return super.onOptionsItemSelected(item);
}
private void getUsers(){
FirebaseDatabase.getInstance().getReference("user").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
users.add(dataSnapshot.getValue(User.class));
}
userAdapter = new UsersAdapter(users, FriendsActivity.this,onUserClickListener);
recyclerView.setLayoutManager(new LinearLayoutManager(FriendsActivity.this));
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(userAdapter);
userAdapter.notifyDataSetChanged();
progressBar_connectivity.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
I did try to add on my code this one , i saw from an other topic-question , but it didn't help , i did even move the getUsers(); on any other caller except onCreate, still same results.
llm.setOrientation(LinearLayoutManager.VERTICAL);
list.setLayoutManager(llm);
list.setAdapter( adapter );

RecyclerView in Android Studio shows some empty lists along with the required lists. The recycler view should display all available audio in the phone

I am trying to make a musicplayer project in Android Studio. I used RecyclerView to display all the audio files present in the phone with a music icon along with the song's name as an item. The problem is the output on certain devices change in the sense that the recycler view shows empty lists with only the music icon on the screen(that are not playable) and upon scrolling, the audio files present in the phone are displayed in the successive lists with the empty lists still at the top. Why are the empty lists displayed and that too only on some devices?
MainActivity.java
public class MainActivity extends AppCompatActivity implements SongsAdapter.SongsViewHolder.OnSongListener {
List<Songs> songs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Dexter.withContext(this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#RequiresApi(api = Build.VERSION_CODES.Q)
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
songs= Songs.getSongs(getApplicationContext());
RecyclerView recyclerView = findViewById(R.id.recyclerView);
SongsAdapter songsAdapter = new SongsAdapter(songs,MainActivity.this,MainActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(songsAdapter);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
android.os.Process.killProcess(android.os.Process.myPid());
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
})
.check();
}
#Override
public void onSongClick(int position) {
Songs currentSong = songs.get(position);
Intent intent = new Intent(MainActivity.this,PlaySongsActivity.class);
intent.putExtra("SongName",currentSong.getSongName());
intent.putExtra("Uri",currentSong.getUri());
MainActivity.this.startActivity(intent);
}
}
Custom Adapter for recycler view - SongsAdapter.java
public class SongsAdapter extends RecyclerView.Adapter<SongsAdapter.SongsViewHolder>{
private final List<Songs> allSongs;
private SongsViewHolder.OnSongListener mOnSongListener;
Context context;
public SongsAdapter(List<Songs> allSongs, Context context, SongsViewHolder.OnSongListener songListener)
{
this.allSongs = allSongs;
this.context = context;
this.mOnSongListener = songListener;
}
#NonNull
#Override
public SongsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View listItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.songs_list,parent,false);
return new SongsViewHolder(listItem,mOnSongListener);
}
#Override
public void onBindViewHolder(#NonNull SongsViewHolder holder, int position) {
final Songs currentSong = allSongs.get(position);
holder.audio_image.setImageResource(R.drawable.music_icon);
holder.songName.setText(currentSong.getSongName());
}
#Override
public int getItemCount() {
return allSongs.size();
}
public static class SongsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView songName;
public ImageView audio_image;
OnSongListener onSongListener;
public SongsViewHolder(#NonNull View itemView, OnSongListener onSongListener) {
super(itemView);
this.audio_image = itemView.findViewById(R.id.audio_image);
this.songName = itemView.findViewById(R.id.song_name);
this.onSongListener = onSongListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onSongListener.onSongClick(getAdapterPosition());
}
public interface OnSongListener
{
void onSongClick(int position);
}
}
}
To retrieve the audios present in the phone - Songs.java
public class Songs {
private final Uri uri;
private final String songName;
public Songs(Uri uri, String songName) {
this.uri = uri;
this.songName = songName;
}
//Method to get all the audio files from the device
#RequiresApi(api = Build.VERSION_CODES.Q)
public static List<Songs> getSongs(Context context) {
List<Songs> songsList = new ArrayList<Songs>();
ContentResolver contentResolver = context.getContentResolver();
Uri externalContentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] projection = new String[]{
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.TITLE,
};
String sortOrder = MediaStore.Video.Media.TITLE + " ASC";
Cursor cursor = contentResolver.query(
externalContentUri, // Uri
projection, // Projection
null, // Selection
null, // Selection args
sortOrder // Sor order
);
if(!cursor.moveToFirst()) //No music files are present
{
//Create an alertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.dialog_message).setTitle(R.string.dialog_title);
builder.setCancelable(false);
builder.setPositiveButton("OK", (dialog, which) -> android.os.Process.killProcess(android.os.Process.myPid()));
AlertDialog alert = builder.create();
alert.show();
}
else
{
int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
int nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
while(cursor.moveToNext())
{
long id = cursor.getLong(idColumn);
String song_name = cursor.getString(nameColumn);
Uri contentUri = ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
songsList.add(new Songs(contentUri, song_name));
}
}
return songsList;
}
public String getSongName() { return this.songName; }
public Uri getUri() {
return this.uri;
}
}
activity_main.xml
<?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"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#color/light_azure"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
List Items Layout - songs_list.xml
<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:id="#+id/items_layout"
android:padding="16dp">
<ImageView
android:id="#+id/audio_image"
android:layout_width="50dp"
android:layout_height="50dp"
android:contentDescription="audio Icon" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:paddingLeft="16dp">
<TextView
android:id="#+id/song_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/white"
android:textSize="16sp"
android:textStyle="bold"
android:ellipsize="marquee"
android:singleLine="true"
/>
</LinearLayout>
</LinearLayout>
I think that if you try these modifications your lists will display properly, first add this method to your adapter:
public void updateSongs(List<Songs> newSongsList) {
this.allSongs = newSongsList;
this.notifyDataSetChanged();
}
Then in the main activity:
public class MainActivity extends AppCompatActivity implements SongsAdapter.SongsViewHolder.OnSongListener {
List<Songs> songs;
//keep reference to your adapter here, instantiate in onCreate()
SongsAdapter songsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerView);
//instantiate adapter with an empty list, update when you have data
songsAdapter = new SongsAdapter(Collections.emptyList(),MainActivity.this,MainActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(songsAdapter);
Dexter.withContext(this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#RequiresApi(api = Build.VERSION_CODES.Q)
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
songs= Songs.getSongs(getApplicationContext());
//now just update your list
songsAdapter.updateSongs(songs);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
android.os.Process.killProcess(android.os.Process.myPid());
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
})
.check();
}
#Override
public void onSongClick(int position) {
Songs currentSong = songs.get(position);
Intent intent = new Intent(MainActivity.this,PlaySongsActivity.class);
intent.putExtra("SongName",currentSong.getSongName());
intent.putExtra("Uri",currentSong.getUri());
MainActivity.this.startActivity(intent);
}
}

RecyclerView not shows all items

I create a RecyclerView to show some test post for my app. But when i run my app i can see only the username and not the test post imageView when i have create on my resource file. I start learning today about RecyclerView and i have a lot of problems with this view.
NOTE: i don't want to show any image from any url for now, but only the image when i already save in my drawable folder. And i know when is not reason to add the getImageUrl method in the model but maybe i will need it in the production, and that's the reason when i don't remove this method
HomeActivity code:
public class HomeActivity extends AppCompatActivity {
public Uri imguri;
DatabaseReference mRef;
final StorageReference mStorageRef = FirebaseStorage.getInstance().getReference("images");
List<PostModel> postList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
final RecyclerView recyclerView = findViewById(R.id.recyclerView);
RecyclerView.Adapter recyclerAdapter;
final FirebaseAuth mAuth = FirebaseAuth.getInstance();
final FirebaseUser user = mAuth.getCurrentUser();
final ImageButton new_post = findViewById(R.id.new_post_btn);
final ImageButton settings = findViewById(R.id.settingsButton);
if (user == null) {
finish();
startActivity(new Intent(HomeActivity.this, MainActivity.class));
}
mRef = FirebaseDatabase.getInstance().getReference("users");
postList = new ArrayList<>();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
for (int i = 0; i < 3; i++) {
PostModel postModel = new PostModel("user " + i, "hello world");
postList.add(postModel);
}
recyclerAdapter = new RecyclerAdapter(postList, this);
recyclerView.setAdapter(recyclerAdapter);
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(HomeActivity.this,SettingsActivity.class));
}
});
new_post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fileChoose();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable #org.jetbrains.annotations.Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null){
imguri = data.getData();
}
}
public String getFileExtension(Uri uri){
ContentResolver cr = getContentResolver();
MimeTypeMap typeMap = MimeTypeMap.getSingleton();
return typeMap.getExtensionFromMimeType(cr.getType(uri));
}
public void FileUpload(){
StorageReference ref = mStorageRef.child(System.currentTimeMillis() + "." + getFileExtension(imguri));
ref.putFile(imguri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
//Uri downloadUrl = taskSnapshot.getDownloadUrl();
Toast.makeText(HomeActivity.this, "Meme image successfully uploaded.", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(HomeActivity.this, "error: " + exception, Toast.LENGTH_SHORT).show();
}
});
}
public void fileChoose(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(intent.ACTION_GET_CONTENT);
startActivityForResult(intent,1);
}
}
Adapter code:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder>{
List<PostModel> postList;
Context context;
public RecyclerAdapter(List<PostModel> postList, Context context) {
this.postList = postList;
this.context = context;
}
#NonNull
#NotNull
#Override
public ViewHolder onCreateViewHolder(#NonNull #NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.post_item,parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull #NotNull ViewHolder holder, int position) {
PostModel postModel = postList.get(position);
holder.username.setText(postModel.getName());
}
#Override
public int getItemCount() {
return postList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView username;
ImageView postImg;
public ViewHolder(#NonNull #NotNull View itemView) {
super(itemView);
username = itemView.findViewById(R.id.post_username);
postImg = itemView.findViewById(R.id.post_image);
}
}
}
XML resource file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:padding="15dp"
app:cardCornerRadius="20dp"
android:layout_gravity="center_horizontal"
app:cardElevation="20dp"
android:outlineSpotShadowColor="#color/teal_200">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TextView
android:id="#+id/post_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginStart="10dp"
android:layout_marginTop="5dp"
android:clickable="true"
android:focusable="true"
android:text="By george sepetadelis"
android:textColor="#color/black"
android:textSize="17sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/post_image"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
<ImageView
android:id="#+id/post_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/post_username"
tools:srcCompat="#drawable/m1" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
And also my model code:
public class PostModel {
String name;
String imgUrl;
public PostModel(String name, String imgUrl) {
this.name = name;
this.imgUrl = imgUrl;
}
public String getName() {
return name;
}
public String getImgUrl() {
return imgUrl;
}
}
Change tools:srcCompat to app:scrCompat because tools namespace is used only to preview the content in the Android studio preview tab and when you run the app, attributes with tools namespace is removed from the xml file
Check the official docs for more information on tools ns

payload shows correct data but dors not update arraylist

So, I have a three items in a recyclerview and I want to check if one of the field is unique or not in my case it's name. all the fields are shown correctly on the screen but whenever I call checkValidation it always returns false even when two names are not the same. I have a list and whenever I call from the activity it shows some different values as not how it is on the screen. If there is anything you didn't get kindly please comment.
dear community I really need help here..
Let me know what part you really didn't get.. :/
MainActivity.java
public MainActivity extends AppCompatActivity implements someinterface
..
..
#OnClick(R.id.activity_detailed_proceed)
void goToOrderPage() {
if (checkValidation()) {
startActivity(new Intent(MainActivity.this, Destination.class));
} else {
SameNameAlertDialogFragment sameNameAlertDialogFragment = new SameNameAlertDialogFragment();
sameNameAlertDialogFragment.show(getSupportFragmentManager(), "ERROR DIALOG");
}
}
..
..
boolean checkValidation() {
//
ArrayList<PersonFriends> personList = personAdapter.getPersonList();
ArrayList<String> namesList = new ArrayList<>();
for (int i = 0; i < personList.size(); i++) {
namesList.add(personList.get(i).getName());
System.out.println(personList.get(i).getName());
}
boolean corrent = true;
Set<String> set = new HashSet<String>(namesList);
if (set.size() < namesList.size()) {
//duplicates found
Log.d(TAG, "False was called here");
return false;
}
return true;
}
PersonAdapter personAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_selected_therapy);
ButterKnife.bind(this);
ArrayList<PersonFriends> personList = new ArrayList<>();
personAdapter = new PersonAdapter(this, this);
personRecyclerview.setAdapter(personAdapter);
personRecyclerview.setNestedScrollingEnabled(false);
personRecyclerview.setLayoutManager(new LinearLayoutManager(this));
}
some interface setup to get the name and duration
#Override
public void onPersonDetailClicked(int position, View view) {
if (view.getId() == R.id.person_name) {
adapterPosition = position;
EnterPersonDialogFragment enterPersonDialogFragment = new EnterPersonDialogFragment();
enterPersonDialogFragment.show(getSupportFragmentManager(), "PERSONS SELECTED");
}
if (view.getId() == R.id.delete_person) {
personAdapter.removeItem(position);
// personAdapter.setPersonList(personList);
// personAdapter.notifyItemRemoved(position);
}
if (view.getId() == R.id.person_duration) {
adapterPosition = position;
DurationDialogFragment durationDialogFragment = new DurationDialogFragment();
durationDialogFragment.show(getSupportFragmentManager(), "DURATION SELECTED");
}
}
#Override
public void enteredInName(String name) {
//change the list that is inside the adapter.
personAdapter.getPersonList().get(adapterPosition).setName(name);
personAdapter.notifyItemChanged(adapterPosition, PersonAdapter.PAYLOAD_NAME);
}
#Override
public void durationSelectedIs(String duration) {
personAdapter.getPersonList().get(adapterPosition).setduration(duration);
personAdapter.notifyItemChanged(adapterPosition, PersonAdapter.PAYLOAD_DURATION);
}
PersonAdapter.java
public class PersonAdapter extends RecyclerView.Adapter<PersonAdapter.PersonViewHolder> {
public static final String PAYLOAD_NAME = "PAYLOAD_NAME";
public static final String PAYLOAD_DURATION = "PAYLOAD_DURATION";
public static final String PAYLOAD_DATE = "PAYLOAD_DATE";
public static final String TAG = PersonAdapter.class.getSimpleName();
Context context;
ArrayList<PersonFriends> personList;
onPersonItemClicked onPersonItemClicked;
public PersonAdapter(Context context, onPersonItemClicked personItemClickListener) {
this.context = context;
onPersonItemClicked = personItemClickListener;
}
public void setPersonList(ArrayList<PersonFriends> personList) {
this.personList = personList;
notifyDataSetChanged();
}
public ArrayList<PersonFriends> getPersonList() {
return this.personList;
}
public void removeItem(int position) {
personList.remove(position);
notifyItemRemoved(position);
}
#NonNull
#Override
public PersonAdapter.PersonViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.item_persons_details, parent, false);
return new PersonViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PersonAdapter.PersonViewHolder holder, int position) {
PersonFriends Person = personList.get(position);
holder.personName.setText(Person.getName());
holder.personDate.setText(Person.getDate());
holder.personDuration.setText(Person.getduration());
if (position == 0) {
holder.deleteFab.hide();
}
}
#Override
public void onBindViewHolder(#NonNull PersonViewHolder holder, int position, #NonNull List<Object> payloads) {
if (!payloads.isEmpty()) {
final PersonFriends item = personList.get(position);
for (final Object payload : payloads) {
if (payload.equals(PAYLOAD_NAME)) {
// in this case only name will be updated
holder.personName.setText(item.getName());
} else if (payload.equals(PAYLOAD_DURATION)) {
// only age will be updated
holder.personDuration.setText(item.getduration());
} else if (payload.equals(PAYLOAD_DATE)) {
holder.personDate.setText(item.getDate());
}
}
} else {
// in this case regular onBindViewHolder will be called
super.onBindViewHolder(holder, position, payloads);
}
}
#Override
public int getItemCount() {
return personList.size();
}
public interface onPersonItemClicked {
void onPersonDetailClicked(int position, View view);
}
class PersonViewHolder extends RecyclerView.ViewHolder {
private final View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
onPersonItemClicked.onPersonDetailClicked(getAdapterPosition(), view);
}
};
#BindView(R.id.person_name)
TextView personName;
#BindView(R.id.person_date)
TextView personDate;
#BindView(R.id.person_duration)
TextView personDuration;
#BindView(R.id.delete_person)
FloatingActionButton deleteFab;
public PersonViewHolder(#NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
personName.setOnClickListener(onClickListener);
personDate.setOnClickListener(onClickListener);
personDuration.setOnClickListener(onClickListener);
deleteFab.setOnClickListener(onClickListener);
}
}
}
item_persons_details.xml
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center|top"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:orientation="vertical"
android:scrollbars="none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/person_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="24dp"
android:background="#drawable/bg_rounded_30"
android:padding="8dp"
android:paddingStart="16dp"
android:paddingEnd="16dp"
android:text="NAME">
</TextView>
<TextView
android:id="#+id/person_duration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:background="#drawable/bg_rounded_30"
android:drawableEnd="#drawable/ic_bottom_arrow"
android:drawablePadding="5dp"
android:padding="8dp"
android:text="DURATION">
</TextView>
<TextView
android:id="#+id/person_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:background="#drawable/bg_rounded_30"
android:drawableEnd="#drawable/ic_bottom_arrow"
android:drawablePadding="4dp"
android:padding="8dp"
android:text="MYDATE">
</TextView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/delete_person"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|center"
android:layout_margin="4dp"
android:backgroundTint="#color/colorBackground"
android:foregroundGravity="right"
android:outlineSpotShadowColor="#color/white"
android:src="#drawable/ic_bin"
android:tint="#color/colorBlack"
app:backgroundTint="#color/white"
app:fabCustomSize="30dp"
app:layout_constraintBottom_toBottomOf="#id/material_card_layout"
app:layout_constraintStart_toStartOf="#id/material_card_layout"
app:layout_constraintTop_toBottomOf="#id/material_card_layout"
app:maxImageSize="20dp" />
</LinearLayout>
</HorizontalScrollView>

Button located in ListView row always fired in the last row

I have a listview (not recyclerView) in which each row has a buttons,couple of textviews and an EditText.
Once I click on the specific button("editTremp") I want the EditText to go into edit mode.
My problem is: every time I press the button (no matter in wich row) it fired only on the last row in the listview, and not in the specific row where the button is located. I've seen a lot of answers but no one works for me.
how can i fix it?
this is the layout for listview_row
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/listrow_drawable"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:elevation="5dp"
android:paddingBottom="5dp" >
<EditText
android:enabled="false"
android:background="#color/transparent"
style="#android:style/Widget.TextView"
android:gravity="right"
android:id="#+id/user_name"
android:textColor="#color/black"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="90dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="5dp"
android:layout_alignStart="#+id/user_msg"
android:layout_toStartOf="#+id/user_image"
android:layout_alignParentEnd="true" />
<TextView
android:id="#+id/user_date_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:layout_alignParentLeft="true"
android:layout_marginTop="8dp"
android:layout_marginLeft="10dp"
/>
<TextView
android:id="#+id/user_phone"
android:autoLink="phone"
android:linksClickable="true"
android:layout_width="wrap_content"
android:textColor="#color/black"
android:layout_height="wrap_content"
android:layout_below="#+id/user_name"
android:layout_alignParentRight="true"
android:layout_marginBottom="5dp"
android:layout_marginRight="10dp"
android:visibility="gone"
/>
<TextView
android:id="#+id/user_msg"
android:textColor="#color/black"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:layout_marginRight="90dp"
android:layout_marginLeft="10dp"
android:layout_marginBottom="2dp"
android:layout_below="#+id/user_name" />
<TextView
android:id="#+id/user_extra"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:gravity="right"
android:layout_marginRight="90dp"
android:layout_marginLeft="10dp"
android:layout_below="#+id/user_msg" />
<ImageButton
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#mipmap/ic_remove"
android:id="#+id/remove"
android:layout_alignParentStart="true"
android:visibility="gone"
android:layout_marginLeft="5dp"
android:layout_below="#+id/user_extra"/>
<ImageButton
android:layout_width="30dp"
android:layout_height="30dp"
android:id="#+id/edit"
android:background="#mipmap/ic_edit"
android:layout_toEndOf="#+id/remove"
android:visibility="gone"
android:layout_below="#+id/user_extra"
android:layout_marginLeft="5dp"/>
<ImageButton
android:layout_width="30dp"
android:layout_height="30dp"
android:id="#+id/phone_btn"
android:background="#mipmap/ic_phone"
android:onClick="makePhoneCall"
android:layout_marginLeft="5dp"
android:layout_below="#+id/user_extra"/>
<ImageButton
android:background="#mipmap/ic_launcher_submittext"
android:layout_toEndOf="#+id/edit"
android:visibility="gone"
android:layout_below="#+id/user_extra"
android:layout_marginLeft="5dp"
android:id="#+id/submitText"
android:layout_width="30dp"
android:layout_height="30dp" />
<TextView
android:id="#+id/user_uid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/user_date_time"
android:layout_alignStart="#+id/user_msg"
android:text="hello"
android:visibility="gone"/>
<ImageView
android:id="#+id/user_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/user_photo_drawable"
android:src="#drawable/ic_action_car"
android:layout_marginRight="10dp"
android:layout_alignTop="#+id/user_name"
android:layout_alignParentEnd="true"
android:layout_marginTop="5dp"/>
</RelativeLayout>
this is my custom adapter and the button click for "editTremp" located here
public class personalZoneAdapter extends ArrayAdapter<TrempData> {
private TextView msg , extra,phone ,date_time ,uid ;
private EditText name ;
private ImageButton deleteTremp , editTremp , phoneBtn , submitText ;
private ImageView sideview;
private int layoutResource;
private FirebaseAuth firebaseAuth;
private DatabaseReference mDatabase;
public personalZoneAdapter(Context context, int layoutResource, ArrayList<TrempData> list) {
super(context, layoutResource, list);
this.layoutResource = layoutResource;
firebaseAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Posts");
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
final LayoutInflater Inflater = LayoutInflater.from(getContext());
view = Inflater.inflate(layoutResource, null);
}
final TrempData data = getItem(position);
//data.setPos(position);
//int[] androidColors = getContext().getResources().getIntArray(R.array.androidcolors);
//int randomAndroidColor = androidColors[new Random().nextInt(androidColors.length)];
if (data != null) {
name = (EditText) view.findViewById(R.id.user_name);
phone = (TextView) view.findViewById(R.id.user_phone);
date_time = (TextView) view.findViewById(R.id.user_date_time);
msg = (TextView) view.findViewById(R.id.user_msg);
extra = (TextView) view.findViewById(R.id.user_extra);
uid = (TextView) view.findViewById(R.id.user_uid);
deleteTremp = (ImageButton)view.findViewById(R.id.remove);
editTremp = (ImageButton)view.findViewById(R.id.edit);
phoneBtn = (ImageButton)view.findViewById(R.id.phone_btn);
submitText = (ImageButton)view.findViewById(R.id.submitText);
sideview = (ImageView)view.findViewById(R.id.user_image);
if (name != null & phone != null & msg != null & date_time != null & uid != null) {
name.setText(data.get_name());
//name.setTextColor(randomAndroidColor);
phone.setText(data.get_phone());
date_time.setText(data.get_timestamp());
msg.setText(data.get_from() + "--> " + data.get_to() + ", " + data.get_date() + ", " + data.get_time());
uid.setText(data.get_uid());
editTremp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitText.setVisibility(View.VISIBLE);
name.setBackground(new ColorDrawable(WHITE));
name.setEnabled(true);
name.setCursorVisible(true);
name.setFocusableInTouchMode(true);
name.setInputType(InputType.TYPE_CLASS_TEXT);
name.requestFocus();
}
});
submitText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDatabase.child("Posts").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
TrempData tremp = getItem(position);
if (ds.getKey().toString().equals(tremp.get_key())) {
name.setEnabled(false);
String new_name = name.getText().toString();
name.setBackground(new ColorDrawable(TRANSPARENT));
submitText.setVisibility(View.GONE);
data.set_name(new_name);
mDatabase.child(ds.getKey().toString()).child("_name").setValue(new_name);
notifyDataSetChanged();
//Toast.makeText(getContext(),"הטרמפ עודכן בהצלחה" + position,Toast.LENGTH_SHORT).show();
break;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
phoneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + data.get_phone()));
getContext().startActivity(i);
}
});
deleteTremp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
TrempData tremp = getItem(position);
if (ds.getKey().toString().equals(tremp.get_key())) {
mDatabase.child(ds.getKey().toString()).removeValue();
notifyDataSetChanged();
//Toast.makeText(getContext(),"הטרמפ נמחק בהצלחה",Toast.LENGTH_SHORT).show();
break;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getContext(),"ישנה בעיה. אנא נסה שוב",Toast.LENGTH_SHORT).show();
}
});
}
});
if(data.get_extras().length() == 0) extra.setVisibility(View.GONE);
extra.setText("הערות:" + " " + data.get_extras());
if(firebaseAuth.getCurrentUser().getUid().equals(uid.getText())){
deleteTremp.setVisibility(View.VISIBLE);
editTremp.setVisibility(View.VISIBLE);
phoneBtn.setVisibility(View.GONE);
sideview.setColorFilter(Color.rgb(255,164,30));
}
else{
submitText.setVisibility(View.GONE);
deleteTremp.setVisibility(View.GONE);
editTremp.setVisibility(View.GONE);
phoneBtn.setVisibility(View.VISIBLE);
sideview.setColorFilter(Color.rgb(176,176,176));
}
}
}
return view;
}
}
and this is the activity
public class PersonalZone extends AppCompatActivity {
private ListView personalzone_lv;
private personalZoneAdapter adapter;
private ArrayList<TrempData> personaldataArrayList = new ArrayList<>();
private FirebaseAuth mAuth;
private DatabaseReference mDatabase;
private FloatingActionButton logoutbtn , addbtn , userprofileBtn;
public PersonalZone(){}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_personal_zone);
mAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference();
logoutbtn = (FloatingActionButton) findViewById(R.id.logout);
addbtn = (FloatingActionButton) findViewById(R.id.floatingAdd);
userprofileBtn = (FloatingActionButton) findViewById(R.id.profile);
personalzone_lv = (ListView)findViewById(R.id.myzone_listview);
adapter = new personalZoneAdapter(this,R.layout.personal_zone_listview_row,personaldataArrayList);
personalzone_lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
updateMyZone();
personalzone_lv.setEmptyView(findViewById(R.id.emptylist));
logoutbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.signOut();
}
});
addbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
Addtremp trempDialog = new Addtremp();
trempDialog.show(manager, "Addtremp");
}
});
userprofileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(PersonalZone.this, UserProfile.class));
}
});
}
public void updateMyZone(){
mDatabase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
personaldataArrayList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
TrempData trempData2 = ds.getValue(TrempData.class);
if (mAuth.getCurrentUser().getUid().toString().equals((ds.getValue(TrempData.class).get_uid()))) {
personaldataArrayList.add(0, trempData2);
personalzone_lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
personaldataArrayList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
TrempData trempData2 = ds.getValue(TrempData.class);
if (mAuth.getCurrentUser().getUid().toString().equals((ds.getValue(TrempData.class).get_uid()))) {
personaldataArrayList.add(0, trempData2);
personalzone_lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
/*#Override
public void onBackPressed() {
this.finish();
overridePendingTransition (R.anim.slide_out, R.anim.slide_out);
}*/
}
UPDATE:
the solution with ViewHolder works great!!
this is the new adapter code with the ViewHolder. if you have any suggestion for improvmment it will be great!
public class personalZoneAdapter extends ArrayAdapter<TrempData> {
static class ViewHolderItem{
private TextView msg , extra,phone ,date_time ,uid ;
private EditText name ;
private ImageButton deleteTremp , editTremp , phoneBtn , submitText ;
private ImageView sideview;
}
private int layoutResource;
private FirebaseAuth firebaseAuth;
private DatabaseReference mDatabase;
public personalZoneAdapter(Context context, int layoutResource, ArrayList<TrempData> list) {
super(context, layoutResource, list);
this.layoutResource = layoutResource;
firebaseAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Posts");
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolderItem viewHolder;
if (view == null) {
final LayoutInflater Inflater = LayoutInflater.from(getContext());
view = Inflater.inflate(layoutResource, null);
viewHolder = new ViewHolderItem();
viewHolder.name = (EditText) view.findViewById(R.id.user_name);
viewHolder.phone = (TextView) view.findViewById(R.id.user_phone);
viewHolder.date_time = (TextView) view.findViewById(R.id.user_date_time);
viewHolder.msg = (TextView) view.findViewById(R.id.user_msg);
viewHolder.extra = (TextView) view.findViewById(R.id.user_extra);
viewHolder.uid = (TextView) view.findViewById(R.id.user_uid);
viewHolder.deleteTremp = (ImageButton)view.findViewById(R.id.remove);
viewHolder.editTremp = (ImageButton)view.findViewById(R.id.edit);
viewHolder.phoneBtn = (ImageButton)view.findViewById(R.id.phone_btn);
viewHolder.submitText = (ImageButton)view.findViewById(R.id.submitText);
viewHolder.sideview = (ImageView)view.findViewById(R.id.user_image);
view.setTag(viewHolder);
}
else{
viewHolder = (ViewHolderItem) convertView.getTag();
}
final TrempData data = getItem(position);
//data.setPos(position);
//int[] androidColors = getContext().getResources().getIntArray(R.array.androidcolors);
//int randomAndroidColor = androidColors[new Random().nextInt(androidColors.length)];
if (data != null) {
if (viewHolder.name != null & viewHolder.phone != null & viewHolder.msg != null & viewHolder.date_time != null & viewHolder.uid != null) {
viewHolder.name.setText(data.get_name());
viewHolder.name.setTag(data._name);
//name.setTextColor(randomAndroidColor);
viewHolder.phone.setText(data.get_phone());
viewHolder.name.setTag(data._phone);
viewHolder.date_time.setText(data.get_timestamp());
viewHolder.name.setTag(data._timestamp);
viewHolder.msg.setText(data.get_from() + "--> " + data.get_to() + ", " + data.get_date() + ", " + data.get_time());
viewHolder.uid.setText(data.get_uid());
viewHolder.name.setTag(data._uid);
viewHolder.editTremp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.submitText.setVisibility(View.VISIBLE);
viewHolder.name.setBackground(new ColorDrawable(WHITE));
viewHolder.name.setEnabled(true);
viewHolder.name.setCursorVisible(true);
viewHolder.name.setFocusableInTouchMode(true);
viewHolder.name.setInputType(InputType.TYPE_CLASS_TEXT);
viewHolder.name.requestFocus();
}
});
viewHolder.submitText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
TrempData tremp = getItem(position);
if (ds.getKey().toString().equals(tremp.get_key())) {
viewHolder.name.setEnabled(false);
String new_name = viewHolder.name.getText().toString();
viewHolder.name.setBackground(new ColorDrawable(TRANSPARENT));
viewHolder.submitText.setVisibility(View.GONE);
data.set_name(new_name);
mDatabase.child(ds.getKey().toString()).child("_name").setValue(new_name);
notifyDataSetChanged();
//Toast.makeText(getContext(),"הטרמפ עודכן בהצלחה" + position,Toast.LENGTH_SHORT).show();
break;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
viewHolder.phoneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + data.get_phone()));
getContext().startActivity(i);
}
});
viewHolder.deleteTremp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
TrempData tremp = getItem(position);
if (ds.getKey().toString().equals(tremp.get_key())) {
mDatabase.child(ds.getKey().toString()).removeValue();
notifyDataSetChanged();
//Toast.makeText(getContext(),"הטרמפ נמחק בהצלחה",Toast.LENGTH_SHORT).show();
break;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getContext(),"ישנה בעיה. אנא נסה שוב",Toast.LENGTH_SHORT).show();
}
});
}
});
if(data.get_extras().length() == 0) viewHolder.extra.setVisibility(View.GONE);
viewHolder.extra.setText("הערות:" + " " + data.get_extras());
if(firebaseAuth.getCurrentUser().getUid().equals(viewHolder.uid.getText())){
viewHolder.deleteTremp.setVisibility(View.VISIBLE);
viewHolder.editTremp.setVisibility(View.VISIBLE);
viewHolder.phoneBtn.setVisibility(View.GONE);
viewHolder.sideview.setColorFilter(Color.rgb(255,164,30));
}
else{
viewHolder.submitText.setVisibility(View.GONE);
viewHolder.deleteTremp.setVisibility(View.GONE);
viewHolder.editTremp.setVisibility(View.GONE);
viewHolder.phoneBtn.setVisibility(View.VISIBLE);
viewHolder. sideview.setColorFilter(Color.rgb(176,176,176));
}
}
}
return view;
}
}
you can use Recycleview and set custom adapter:
Adapter:
public class TestAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context ctx;
public ArrayList<String> mListItem;
ArrayList<String> item;
public TestAdapter(Context ctx, ArrayList<String> mListItem) {
this.ctx = ctx;
this.mListItem = mListItem;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(ctx).inflate(R.layout.row_watch_company, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ViewHolder mViewHolder = (ViewHolder)holder;
mViewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do your task
}
});
}
#Override
public int getItemCount() {
return 10;
}
class ViewHolder extends RecyclerView.ViewHolder {
Button button;
public ViewHolder(View rowView) {
super(rowView);
button = (Button)rowView.findViewById(R.id.button);
}
}
}
Recyclerview in fragment / activity:
rvAdvisor = (RecyclerView) view.findViewById(R.id.rvAdvisor);
rvAdvisor.setLayoutManager(new LinearLayoutManager(getActivity()));
rvAdvisor.setAdapter(new TestAdapter (getActivity());//pass data here

Categories

Resources