Application crash during Item click of recyclerView [duplicate] - java

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed last year.
My Application is crashed when I click on ItemView of RecyclerView, There is no error showing in code.
The data are load in toast but not pass to the other class or what don't know, but when I click any Item the appliaction is crash..
This is my Main RecyclerView Class
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Admin extends AppCompatActivity {
Button addUser;
RecyclerView mainUserRecyclerView;
UserAdapter adapter;
FirebaseDatabase database;
ArrayList<UserInfo> userInfoArrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
mainUserRecyclerView = findViewById(R.id.mainUserRecyclerView);
mainUserRecyclerView.setLayoutManager(new LinearLayoutManager(this));
addUser = findViewById(R.id.addUserBtn);
database= FirebaseDatabase.getInstance();
DatabaseReference reference = database.getReference().child("userInfo");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
UserInfo userInfo = dataSnapshot.getValue(UserInfo.class);
userInfoArrayList.add(userInfo);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Admin.this,"Failed to get data",Toast.LENGTH_SHORT).show();
}
});
adapter = new UserAdapter(Admin.this,userInfoArrayList);
mainUserRecyclerView.setAdapter(adapter);
}
public void setAddUser(View view){
Intent intent = new Intent(this,user_detail.class);
startActivity(intent);
}
}
This is my Adapter Class
package com.example.rent;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.viewHolder> {
Context admin;
ArrayList<UserInfo> userInfoArrayList;
public UserAdapter(Admin admin, ArrayList<UserInfo> userInfoArrayList) {
this.admin = admin;
this.userInfoArrayList = userInfoArrayList;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(admin).inflate(R.layout.user_list_item,parent,false);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UserAdapter.viewHolder holder, int position) {
UserInfo userInfo = userInfoArrayList.get(position);
holder.user_name.setText(userInfo.getShopName());
holder.itemView.setOnClickListener(v -> {
Intent intent = new Intent(admin,Display_User.class);
//Toast.makeText(admin, ""+userInfo.getOneMonthRent(), Toast.LENGTH_SHORT).show();
intent.putExtra("Name",userInfo.getShopName());
intent.putExtra("Rent",userInfo.getOneMonthRent());
intent.putExtra("Complex",userInfo.getComplexName());
intent.putExtra("PaidRent",userInfo.getPaidAmount());
intent.putExtra("DMonth",userInfo.getDefaultMonth());
intent.putExtra("PendingRent",userInfo.getPendingAmount());
admin.startActivity(intent);
});
}
#Override
public int getItemCount() {
return userInfoArrayList.size();
}
public static class viewHolder extends RecyclerView.ViewHolder {
TextView user_name;
public viewHolder(#NonNull View itemView) {
super(itemView);
user_name = itemView.findViewById(R.id.tvUserName);
}
}
}
And The display User class where I have to fetch the data
package com.example.rent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class Display_User extends AppCompatActivity {
TextView tvName,tvRent,tvComplex,tvPaidRent,tvDefaultMonth,tvPendingRent;
String Sname, rent, complex, paidRent, defaultMonth, pendingRent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_user);
Sname = getIntent().getStringExtra("Name");
rent = getIntent().getStringExtra("Rent");
complex = getIntent().getStringExtra("Complex");
paidRent = getIntent().getStringExtra("PaidRent");
defaultMonth = getIntent().getStringExtra("DMonth");
pendingRent = getIntent().getStringExtra("Pending");
tvName = findViewById(R.id.tvName);
tvName.setText(Sname);
tvRent = findViewById(R.id.tvRent);
tvRent.setText(rent);
tvComplex = findViewById(R.id.tvComplex);
tvComplex.setText(complex);
tvPaidRent = findViewById(R.id.tvPaidRent);
tvPaidRent.setText(paidRent);
tvDefaultMonth = findViewById(R.id.tvDefault);
tvDefaultMonth.setText(defaultMonth);
tvPendingRent = findViewById(R.id.tvPending);
tvPendingRent.setText(pendingRent);
}
}

Have you declared the Activity on the manifest file? And the intent ?

Related

onclicklistner on videoview in recyclerview

hi i am building a app where, i show videos from firebase to videoview which is in recyclerview in gridlayout form, means at each fragment there are two videos shown, i want to add on clicklisten to them as when someone click on it, a new activity opens and at that activity, the same video is shown in fullscreen (vertically). i used putextra to transfer my data, but i am getting error, "uristring",
bellow is my code
Adapter code
package com.example.godhelpme.Adapter;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;
import com.example.godhelpme.Fragments.HomeFragment;
import com.example.godhelpme.FullScreen;
import com.example.godhelpme.LoginActivity;
import com.example.godhelpme.MainActivity;
import com.example.godhelpme.Model.Post;
import com.example.godhelpme.Model.User;
import com.example.godhelpme.R;
import com.example.godhelpme.StartActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder>{
private Context mContext;
private List<Post> mPosts;
private FirebaseUser firebaseUser;
public PostAdapter(Context mContext, List<Post> mPosts) {
this.mContext = mContext;
this.mPosts = mPosts;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.upload_item, parent,false);
return new PostAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
Post post = mPosts.get(position);
try {
String link = post.getVideourl();
MediaController mediaController = new MediaController(mContext);
mediaController.setAnchorView(holder.video1);
Uri video = Uri.parse(link);
holder.video1.setMediaController(mediaController);
holder.video1.setVideoURI(video);
holder.video1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
try {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
}
mediaPlayer.setVolume(0f, 0f);
mediaPlayer.setLooping(false);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
mediaController.setVisibility(View.GONE);
}
});
holder.video1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.start(); }
});
holder.id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(view.getContext(),FullScreen.class);
in.putExtra(" videourl", post.getVideourl());
in.putExtra("publisher", post.getPublisher());
in.putExtra("postid", post.getPostid());
view.getContext().startActivity(in);
}
});
}catch (Exception e){
Toast.makeText(mContext,e.getMessage(), Toast.LENGTH_SHORT).show();
}
FirebaseDatabase.getInstance().getReference().child("Users").child(post.getPublisher())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
holder.id.setText(user.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return mPosts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public VideoView video1;
public TextView id;
public ViewHolder(#NonNull View itemView) {
super(itemView);
video1 = itemView.findViewById(R.id.video1);
id = itemView.findViewById(R.id.id);
}
}
}
THAT ACTIVITY CODE WHERE I WANT TO SHOW
package com.example.godhelpme;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import com.example.godhelpme.Model.Post;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
public class FullScreen extends AppCompatActivity {
VideoView videoFull;
TextView idFull;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_full_screen);
videoFull = findViewById(R.id.videoFull);
idFull = findViewById(R.id.idFull);
Intent in = getIntent();
try{
String ttr = in.getStringExtra("videourl");
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoFull);
Uri video1 = Uri.parse(ttr);
videoFull.setMediaController(mediaController);
videoFull.setVideoURI(video1);
}catch (Exception e){
Toast.makeText(this,e.getMessage(), Toast.LENGTH_SHORT).show();
}
videoFull.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.start(); }
});
idFull.setText(in.getStringExtra("publisher"));
}
}
PLEASE HELP GUYS PLEASE
It took me three days to figure out what's the problem in my code. After knowing my mistake i am feeling very ashamed as well as happy that i figured, it out.
the mistake is in the adapter code,
in.putExtra(" videourl", post.getVideourl());
String ttr = in.getStringExtra("videourl");
the difference between above two code line is the, in first line there is space before the videourl and in the second line there is no space before videourl, and that's a problem. :-)

No setter/field for url found on class com.example.scheduletask.model.Task can't retrieve data from firebase database to detail activity

im trying to retrieve data from firebase to detail activity. On the listview, it show perfectly. But when i click, the detail activity opened but still empty. All it says "W/ClassMapper: No setter/field for url found on class com.example.scheduletask.model.Task". I thought the setter on model task wasn't used, but i don't know... im sorry, i don't understand, i don't know what i missed:( any help is appreciated, thank youuu
TaskActivity.java
package com.example.scheduletask;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.scheduletask.adapter.MatkulAdapter;
import com.example.scheduletask.adapter.TaskAdapter;
import com.example.scheduletask.adapter.TaskDetailAdapter;
import com.example.scheduletask.database.FirebaseTaskHelper;
import com.example.scheduletask.model.Matkul;
import com.example.scheduletask.model.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Iterator;
public class TaskActivity extends AppCompatActivity {
DatabaseReference databaseReference;
ListView listViewTask;
FloatingActionButton fabAddTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
databaseReference = FirebaseDatabase.getInstance().getReference("Task");
listViewTask = findViewById(R.id.tasklist);
showData();
fabAddTask = findViewById(R.id.fab_addtask);
fabAddTask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TaskActivity.this, CreateTaskActivity.class);
startActivity(intent);
}
});
listViewTask.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String subjectTask = ((TextView)view.findViewById(R.id.txt_subjectlisttask)).getTag().toString();
Intent taskDetail = new Intent(TaskActivity.this, TaskDetailActivity.class);
taskDetail.putExtra("subjectTask", subjectTask);
startActivity(taskDetail);
}
});
}
private void showData() {
final ArrayList<String> subjectTask = new ArrayList<>();
final ArrayList<String> taskDueDate = new ArrayList<>();
final ArrayList<String> taskDescription = new ArrayList<>();
final ArrayList<String> imageURL = new ArrayList<>();
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> snapshotIterable = dataSnapshot.getChildren();
Iterator<DataSnapshot> iterator = snapshotIterable.iterator();
while (iterator.hasNext()){
Task value = iterator.next().getValue(Task.class);
assert value != null;
subjectTask.add(value.getSubjectTask());
taskDescription.add(value.getTaskDescription());
taskDueDate.add(value.getTaskDueDate());
imageURL.add(value.getImageURL());
((TaskAdapter)listViewTask.getAdapter()).notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
listViewTask.setAdapter(new TaskAdapter(subjectTask, taskDescription, taskDueDate, imageURL, this));
}
#Override
protected void onResume() {
super.onResume();
showData();
}
}
Task.java (this is the model)
package com.example.scheduletask.model;
public class Task {
private String taskDueDate;
public String getTaskDueDate() {
return taskDueDate;
}
public void setTaskDueDate(String taskDueDate) {
this.taskDueDate = taskDueDate;
}
private String subjectTask;
public String getTaskDescription() {
return taskDescription;
}
public void setTaskDescription(String taskDescription) {
this.taskDescription = taskDescription;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
private String taskDescription;
private String imageURL;
public String getSubjectTask() {
return subjectTask;
}
public void setSubjectTask(String subjectTask) {
this.subjectTask = subjectTask;
}
}
TaskDetailActivity.java
package com.example.scheduletask;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.example.scheduletask.model.Task;
import com.github.barteksc.pdfviewer.PDFView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
public class TaskDetailActivity extends AppCompatActivity {
EditText edtSubject, edtDueDate, edtDescription;
ImageView filePhoto;
ProgressBar progressBarDetail;
Button btnEdit, btnDelete;
DatabaseReference databaseReference;
private String photoURL, subjectTask;
Button btnViewPDF;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_detail);
databaseReference = FirebaseDatabase.getInstance().getReference("Task");
subjectTask = getIntent().getExtras().getString("subjectTask");
progressBarDetail = findViewById(R.id.progressbardetail);
progressBarDetail.setVisibility(View.INVISIBLE);
readData();
findAllViewsID();
}
private void readData() {
progressBarDetail.setVisibility(View.VISIBLE);
Query findQuery = databaseReference.orderByKey().equalTo(subjectTask);
findQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot getSnapshot : dataSnapshot.getChildren()){
edtSubject.setText(getSnapshot.child("subjectTask").getValue().toString());
edtDescription.setText(getSnapshot.child("taskDescription").getValue().toString());
edtDueDate.setText(getSnapshot.child("taskDueDate").getValue().toString());
photoURL = getSnapshot.child("imageURL").getValue().toString();
Picasso.get().load(photoURL).fit().into(filePhoto);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
progressBarDetail.setVisibility(View.INVISIBLE);
}
});
progressBarDetail.setVisibility(View.INVISIBLE);
}
private void findAllViewsID() {
edtSubject = findViewById(R.id.edt_updatetasksubject);
edtDescription = findViewById(R.id.edt_updatetaskdescription);
edtDueDate = findViewById(R.id.edt_updateduedatetime);
filePhoto = findViewById(R.id.iv_taskphotoinput);
btnViewPDF = findViewById(R.id.btn_viewpdf);
btnDelete = findViewById(R.id.btn_deletetask);
btnEdit = findViewById(R.id.btn_edittask);
}
}
TaskAdapter.java
package com.example.scheduletask.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.scheduletask.R;
import com.example.scheduletask.TaskActivity;
import com.example.scheduletask.TaskDetailActivity;
import com.example.scheduletask.model.Task;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class TaskAdapter extends BaseAdapter {
private ArrayList<String> subjectTask;
private ArrayList<String> taskDescription;
private ArrayList<String> taskDueDate;
private ArrayList<String> imageURL;
private AppCompatActivity activity;
public TaskAdapter(ArrayList<String> subjectTask, ArrayList<String> taskDescription, ArrayList<String> taskDueDate, ArrayList<String> imageURL, AppCompatActivity activity) {
this.subjectTask = subjectTask;
this.taskDescription = taskDescription;
this.taskDueDate = taskDueDate;
this.imageURL = imageURL;
this.activity = activity;
}
Context ctx;
ArrayList<Task> tasks;
#Override
public int getCount() {
return subjectTask.size();
}
#Override
public Object getItem(int position) {
return subjectTask.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public TaskAdapter(#NonNull Context ctx, ArrayList<Task> tasks) {
this.ctx = ctx;
this.tasks = tasks;
}
public View getView(int position, View view, ViewGroup parent) {
view = LayoutInflater.from(activity.getApplicationContext())
.inflate(R.layout.list_task, parent, false);
view.findViewById(R.id.txt_subjectlisttask).setTag(String.valueOf(subjectTask.get(position)));
((TextView)view.findViewById(R.id.txt_subjectlisttask)).setText(String.valueOf(subjectTask.get(position)));
((TextView)view.findViewById(R.id.txt_duedatetasklist)).setText(String.valueOf(taskDueDate.get(position)));
return view; }
}
Here is the logcat when i click the task listview
And this is my database

How to set up notifications with sound/vibration and button logo change?

I am trying to set up notification, but I can't add what I want: I would like the notification coming with sound/vibration, changing also the notification button logo.
Can anyone help me to setup notification? I am trying but it's not working.
The code below is working fine: no error. All notifications are shown, but with no sound / vibration.
package com.example.mfree.Fragment;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.mfree.Adapter.NotificationAdapter;
import com.example.mfree.Model.Notification;
import com.example.mfree.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class NotificationFragment extends Fragment {
private RecyclerView recyclerView;
NotificationAdapter notificationAdapter;
private List<Notification>notificationList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_notification, container, false);
recyclerView=view.findViewById(R.id.recyler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager=new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
notificationList=new ArrayList<>();
notificationAdapter=new NotificationAdapter(getContext(),notificationList);
recyclerView.setAdapter(notificationAdapter);
readNotification();
return view;
}
private void readNotification() {
FirebaseUser firebaseUser= FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Notifications").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
notificationList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren())
{
Notification notification=snapshot.getValue(Notification.class);
notificationList.add(notification);
}
Collections.reverse(notificationList);
notificationAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
**NotificationAdapter**
package com.example.mfree.Adapter;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.mfree.Fragment.PostDetailsFragment;
import com.example.mfree.Fragment.ProfileFragment;
import com.example.mfree.Model.Notification;
import com.example.mfree.Model.Post;
import com.example.mfree.Model.User;
import com.example.mfree.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
public class NotificationAdapter extends RecyclerView.Adapter<NotificationAdapter.ViewHolder>{
private Context mContext;
private List<Notification>mNotification;
public NotificationAdapter(Context mContext, List<Notification> mNotification) {
this.mContext = mContext;
this.mNotification = mNotification;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(mContext).inflate(R.layout.notification_item,parent,false);
return new NotificationAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final Notification notification=mNotification.get(position);
holder.text.setText(notification.getText());
getUserInfo(holder.image_profile,holder.username,notification.getUserid());
if (notification.isIspost()){
holder.post_image.setVisibility(View.VISIBLE);
getPostImage(holder.post_image,notification.getPostid());
}else {
holder.post_image.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(notification.isIspost()){
SharedPreferences.Editor editor=mContext.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit();
editor.putString("postid",notification.getPostid());
editor.apply();
((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container
,new PostDetailsFragment()).commit();
}else {
SharedPreferences.Editor editor=mContext.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit();
editor.putString("profileid",notification.getUserid());
editor.apply();
((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container
,new ProfileFragment()).commit();
}
}
});
}
#Override
public int getItemCount() {
return mNotification.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView image_profile,post_image;
TextView username,text;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image_profile=itemView.findViewById(R.id.image_profile);
post_image=itemView.findViewById(R.id.image_post);
username=itemView.findViewById(R.id.username);
text=itemView.findViewById(R.id.comment);
}
}
private void getUserInfo (final ImageView imageView, final TextView username, String publisherid){
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users").child(publisherid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
try{
User user=dataSnapshot.getValue(User.class);
Glide.with(mContext.getApplicationContext()).load(user.getImageurl()).into(imageView);
username.setText(user.getUsername());
}catch (Exception e)
{
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getPostImage(final ImageView imageView, String postid){
DatabaseReference reference=FirebaseDatabase.getInstance().getReference("posts").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
try {
Post post=dataSnapshot.getValue(Post.class);
Glide.with(mContext.getApplicationContext()).load(post.getPostimage()).into(imageView);
}catch (Exception e){
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
If what you are trying to make is an in-app notification system, you can try ringing the sound on your own using RingtoneManager and Ringtone class as :
// to play sound for your custom notification on its arrival
Uri notificationToneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone notificationTone = RingtoneManager.getRingtone(this, notificationToneUri);
notificationTone.play();
//to stop
notificationTone.stop();
See this link for vibration

MVVM firebase user authentification

Since I am new to MVVM and Firebase, I tried creating a simple app, that signs up a User. The SignUp worked, but a weird error and crash of the application came with it. Since I am also trying to understand MVVM, I would appreciate tipps for better code. Anything that makes this better helps. Thanks
MainActivity
package com.example.testingapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
MainViewmodel model;
EditText editEmail;
EditText editPassword;
Button btnSignUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editEmail = findViewById(R.id.editEmail);
editPassword = findViewById(R.id.editPassword);
btnSignUp = findViewById(R.id.btnSignUp);
btnSignUp.setOnClickListener(this);
model = ViewModelProviders.of(this).get(MainViewmodel.class);
}
#Override
public void onClick(View view) {
model.email = editEmail.getText().toString().trim();
model.password = editPassword.getText().toString().trim();
model.signUp();
}
}
MainViewmodel
package com.example.testingapp;
import androidx.lifecycle.ViewModel;
public class MainViewmodel extends ViewModel {
repo repository;
String email;
String password;
public MainViewmodel(){
if(repository == null){
repository = new repo();
}
}
public void signUp(){
repository.firebaseSignUp(email, password);
}
}
Repo
package com.example.testingapp;
import android.util.Log;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import java.util.concurrent.Executor;
import static android.content.ContentValues.TAG;
public class repo {
FirebaseAuth mAuth = FirebaseAuth.getInstance();
public void firebaseSignUp(String email, String password){
Log.d(TAG, "firebaseSignUp: Success" + email + password);
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener((Executor) this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
}
});
}
}
you can remove (Executor) this,. for me it is work.

String in Database and Drawable Image in drawable folder

How can I get String from my database and combine it with Image from my drawable folder. Help Please.
this is my main activity.
package com.apk.foodanalyzer.healthandnutrifactsanalyzer;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.goactivity.DatabaseHelper;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.goactivity.GoItem;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.goactivity.ListGoAdapter;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.growactivity.GrowDatabaseHelper;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.growactivity.GrowItem;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.growactivity.ListGrowAdapter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
/**
* Created by Pavilion on 11/18/2015.
*/
public class Grow extends AppCompatActivity {
private ListView listviewGrow;
private ListGrowAdapter adapter;
private List<GrowItem> mGrowItemList;
private GrowDatabaseHelper mDBHelper;
private SearchView searchtext;
Integer[] imgid = {R.drawable.carp,R.drawable.catfish, R.drawable.cavalla };
#Override
protected void onCreate(Bundle savedInstanceState) {
searchtext = (SearchView) findViewById(R.id.search_text);
super.onCreate(savedInstanceState);
setContentView(R.layout.grow_layout);
listviewGrow = (ListView)findViewById(R.id.listview_growtable);
mDBHelper = new GrowDatabaseHelper(this);
mGrowItemList = mDBHelper.getListGrow();
adapter = new ListGrowAdapter(imgid, this, mGrowItemList);
listviewGrow.setAdapter(adapter);
listviewGrow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View row, int position, long index) {
Toast.makeText(getApplicationContext(), "Position " + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Grow.this, GrowValueActivityContent.class);
intent.putExtra("RowId", position);
startActivity(intent);
}
});
}
This is my Adapter. I don't know what to revised this. Hope you would help me.
package com.apk.foodanalyzer.healthandnutrifactsanalyzer.growactivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.R;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.goactivity.GoItem;
import java.util.List;
/**
* Created by Pavilion on 12/1/2015.
*/
public class ListGrowAdapter extends BaseAdapter {
private Context mContext;
private List<GrowItem> mGrowItemList;
private final Integer[] imgid;
public ListGrowAdapter(Integer[] imgid, Context mContext, List<GrowItem> mGrowItemList) {
this.imgid = imgid;
this.mContext = mContext;
this.mGrowItemList = mGrowItemList;
}
#Override
public int getCount() {
return mGrowItemList.size();
}
#Override
public GrowItem getItem(int position) {
return mGrowItemList.get(position);
}
#Override
public long getItemId(int position) {
return mGrowItemList.get(position).getRowId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
GrowItem item = getItem(position);
View vv = View.inflate(mContext, R.layout.go_listview, null);
TextView tvFoodDescription = (TextView)vv.findViewById(R.id.txtvw_fooddescription);
ImageView imgFoodImage = (ImageView)vv.findViewById(R.id.food_image);
tvFoodDescription.setText(item.getFoodDescription());
imgFoodImage.setImageResource(imgid[position]);
return vv;
}
}

Categories