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
Related
This is my adapter and I save my image string type in Responsemodel class.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.myviewholder>
{
List<ResponseModel> data;
private final IOtobusSaatleriInterface iOtobusSaatleriInterface;
Context context;
public MyAdapter(List<ResponseModel> data, IOtobusSaatleriInterface iOtobusSaatleriInterface, Context context) {
this.data = data;
this.iOtobusSaatleriInterface = iOtobusSaatleriInterface;
this.context = context;
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.singlerowdesign,parent,false);
return new myviewholder(view,iOtobusSaatleriInterface);
}
#Override
public void onBindViewHolder(#NonNull myviewholder holder, int position) {
holder.t1.setText(data.get(position).getName());
holder.t2.setText(data.get(position).getDesig());
Glide.with(holder.t1.getContext())
.load("http://example.site/Gurpinar/images/" +data.get(position).getImage()).into(holder.img);
}
#Override
public int getItemCount() {
return null!=data?data.size():0;
}
class myviewholder extends RecyclerView.ViewHolder{
ImageView img;
TextView t1,t2;
public myviewholder(#NonNull View itemView, IOtobusSaatleriInterface iOtobusSaatleriInterface) {
super(itemView);
img = itemView.findViewById(R.id.img);
t1 = itemView.findViewById(R.id.t1);
t2 = itemView.findViewById(R.id.t2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (iOtobusSaatleriInterface != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION);
iOtobusSaatleriInterface.onItemClick(position);
Intent intent = new Intent(context,deneme.class);
intent.putExtra("name",data.get(position).getName());
intent.putExtra("resim","http://example.site/Gurpinar/images/");
context.startActivity(intent);
}
}
});
}
}
}
and my new empty activity
public class deneme extends AppCompatActivity {
TextView textView;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deneme);
textView = findViewById(R.id.textView);
imageView = findViewById(R.id.imageView);
Intent intent = getIntent();
String name = intent.getStringExtra("name");
String goruntu = intent.getStringExtra("resim");
String.valueOf(Glide.with(imageView).load(goruntu));
textView.setText(name);
}
}
And my new empty activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".deneme">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5sp"
android:gravity="left"
android:text="TextView"
android:textColor="#494545"
android:textSize="25sp"
app:layout_constraintBottom_toTopOf="#+id/imageView" />
</LinearLayout>
My problem is I can access name data but image cannot be displayed.
How can I access the selected photo? I take the photos in mysql database and with the url recyclerview.
Perhaps you can pass the image as a Base64 in the Intent and create in the new Activity a Imagefile from this String.
Create as Base64 String:
How to get raw string of an image from Bitmap in android?
Create the Imagefile again from the String:
Create image file from raw string data
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);
}
}
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..
I am trying to open a full size image when I click on CardView. I have managed to open new activity but don't know how to show image in it
NewsletterActivity.java
public class NewsletterActivity extends AppCompatActivity {
List<NewsletterAdapter> NewsletterAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
String GET_JSON_DATA_HTTP_URL =
"http://academypk.info/eleganceschool/jsonfiles/getnewsletter.php";
String JSON_IMAGE_TITLE_NAME = "quarter";
String JSON_YEAR = "year";
String JSON_IMAGE_URL = "path";
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_newsletter);
NewsletterAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
JSON_DATA_WEB_CALL();
}
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
NewsletterAdapter NewsletterAdapter2 = new NewsletterAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
NewsletterAdapter2.setImageTitleName(json.getString(JSON_IMAGE_TITLE_NAME));
NewsletterAdapter2.setYear(json.getString(JSON_YEAR));
NewsletterAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
NewsletterAdapter1.add(NewsletterAdapter2);
}
recyclerViewadapter = new
NewsletterRecyclerViewAdapter(NewsletterAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
NewsletterAdaptor.java
public class NewsletterAdapter {
public String ImageServerUrl;
public String ImageTitleName;
public String year;
public String getImageServerUrl() {
return ImageServerUrl;
}
public void setImageServerUrl(String imageServerUrl) {
this.ImageServerUrl = imageServerUrl;
}
public String getImageTitleName() {
return ImageTitleName;
}
public void setImageTitleName(String ImageTitleName) {
this.ImageTitleName = ImageTitleName;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
}
NewsletterRecyclerViewAdaptor.java
public class NewsletterRecyclerViewAdapter extends
RecyclerView.Adapter<NewsletterRecyclerViewAdapter.ViewHolder> {
Context context;
List<NewsletterAdapter> getNewsletterAdapter;
ImageLoader imageLoader1;
public NewsletterRecyclerViewAdapter(List<NewsletterAdapter>
getNewsletterAdapter, Context context){
super();
this.getNewsletterAdapter = getNewsletterAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.newsletter_recyclerview_items, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
NewsletterAdapter getNewsletterAdapter1 = getNewsletterAdapter.get(position);
imageLoader1 = ServerImageParseAdapter.getInstance(context).getImageLoader();
imageLoader1.get(getNewsletterAdapter1.getImageServerUrl(),
ImageLoader.getImageListener(
Viewholder.networkImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.networkImageView.setImageUrl(getNewsletterAdapter1.getImageServerUrl(), imageLoader1);
Viewholder.ImageTitleNameView.setText(getNewsletterAdapter1.getImageTitleName());
Viewholder.YearView.setText(getNewsletterAdapter1.getYear());
}
#Override
public int getItemCount() {
return getNewsletterAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleNameView;
public TextView YearView;
public NetworkImageView networkImageView ;
public ViewHolder(View itemView) {
super(itemView);
ImageTitleNameView = (TextView) itemView.findViewById(R.id.textView_item) ;
YearView = (TextView) itemView.findViewById(R.id.textView_item1) ;
networkImageView = (NetworkImageView) itemView.findViewById(R.id.VollyNetworkImageView1) ;
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), SecondPage.class);
v.getContext().startActivity(intent);
Toast.makeText(v.getContext(), "Image not found", Toast.LENGTH_SHORT).show();
}
});
}
}
}
ServerImageParseAdaptor.java
public class ServerImageParseAdapter {
public static ServerImageParseAdapter SIAdapter;
public static Context context1;
public RequestQueue requestQueue1;
public ImageLoader Imageloader1;
public Cache cache1 ;
public Network networkOBJ ;
LruCache<String, Bitmap> LRUCACHE = new LruCache<String, Bitmap>(30);
private ServerImageParseAdapter(Context context) {
this.context1 = context;
this.requestQueue1 = RQ();
Imageloader1 = new ImageLoader(requestQueue1, new ImageLoader.ImageCache() {
#Override
public Bitmap getBitmap(String URL) {
return LRUCACHE.get(URL);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
LRUCACHE.put(url, bitmap);
}
});
}
public ImageLoader getImageLoader() {
return Imageloader1;
}
public static ServerImageParseAdapter getInstance(Context SynchronizedContext) {
if (SIAdapter == null) {
SIAdapter = new ServerImageParseAdapter(SynchronizedContext);
}
return SIAdapter;
}
public RequestQueue RQ() {
if (requestQueue1 == null) {
cache1 = new DiskBasedCache(context1.getCacheDir());
networkOBJ = new BasicNetwork(new HurlStack());
requestQueue1 = new RequestQueue(cache1, networkOBJ);
requestQueue1.start();
}
return requestQueue1;
}
}
SecondPage.java
public class SecondPage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_page);
}
}
Activity_Newsletter.xml
<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="info.techabyte.parentsapp.newsletter.NewsletterActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/newsletterheading"
android:background="#color/colorAccent"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#color/colorHeadings"
android:gravity="center_horizontal" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
Newsletter_recyclerview_items.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="3dp"
card_view:contentPadding="3dp"
card_view:cardCornerRadius="3dp"
card_view:cardMaxElevation="3dp"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/VollyNetworkImageView1"
android:layout_width="150dp"
android:layout_height="100dp"
android:src="#mipmap/ic_launcher"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/quarter"
android:id="#+id/textView_item"
android:layout_centerVertical="false"
android:layout_toRightOf="#+id/VollyNetworkImageView1"
android:layout_toEndOf="#+id/VollyNetworkImageView1"
android:layout_marginLeft="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/year"
android:id="#+id/textView_item1"
android:layout_centerVertical="false"
android:layout_toRightOf="#+id/VollyNetworkImageView1"
android:layout_toEndOf="#+id/VollyNetworkImageView1"
android:layout_below="#+id/textView_item"
android:layout_marginLeft="20dp"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
Secondpage.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#ffffff"
android:layout_height="match_parent">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/VollyNetworkImageView1"
android:layout_width="150dp"
android:layout_height="100dp"
android:src="#mipmap/ic_launcher"/>
</LinearLayout>
you can use intent to pass url to other activity
like this paste belowe code where you click in cardview or in which click event your want go to other activity
Intent i = new Intent(MainActivity.this, LoginActivity.class);
i.putExtra("url", your_image_usr);
startActivity(i);
and recieve image url in your other activity like this means your imageview activity
Intent i =getIntent();
String url = i.getStringExtra("url");
and open image using this glide library to show image
compile this in your gradle file file
compile 'com.github.bumptech.glide:glide:4.0.0-RC0'
load image like this
ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
GlideApp
.with(this)
.load(url)
.centerCrop()
.placeholder(R.drawable.loading_spinner)
.into(imageView);
Here is the code where i put it
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleNameView;
public TextView YearView;
public NetworkImageView networkImageView ;
public ViewHolder(View itemView) {
super(itemView);
ImageTitleNameView = (TextView) itemView.findViewById(R.id.textView_item) ;
YearView = (TextView) itemView.findViewById(R.id.textView_item1) ;
networkImageView = (NetworkImageView) itemView.findViewById(R.id.VollyNetworkImageView1) ;
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), SecondPage.class);
intent.putExtra("path", networkImageView);
startActivity(intent);
Toast.makeText(v.getContext(), "Image not found", Toast.LENGTH_SHORT).show();
}
});
}
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