I've been getting an error (in my FirebaseRecyclerAdapter) saying that the class must be declared abstract or implement method 'onCreateViewHolder(ViewGroup, int) in 'Adapter', as well as Method does not override superclass on the "Override" just below that code.
However, I have no idea how to change my code to get rid of that error. Can someone please help me? I would really appreciate the help. Thank you!
DiaryActivity.java package com.shiminu1521462c.fyp_2;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
public class DiaryActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private DatabaseReference fNotesDatabase;
private RecyclerView mNotesList;
private GridLayoutManager gridLayoutManager;
private DatabaseReference noteRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_diary);
mNotesList = (RecyclerView) findViewById(R.id.notes_list);
gridLayoutManager = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false);
mNotesList.setHasFixedSize(true);
mNotesList.setLayoutManager(gridLayoutManager);
mNotesList.addItemDecoration(new GridSpacingDecoration(2, dpToPx(10), true));
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes").child(mAuth.getCurrentUser().getUid());
}
loadData();
}
#Override
public void onStart() {
super.onStart();
}
private void loadData() {
Query query = fNotesDatabase.orderByValue();
FirebaseRecyclerAdapter<NoteModel, NoteViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<NoteModel, NoteViewHolder>(
NoteModel.class,
R.layout.single_note_layout,
NoteViewHolder.class,
query
) {
#Override
protected void populateViewHolder(final NoteViewHolder viewHolder, NoteModel model, int position) {
final String noteId = getRef(position).getKey();
fNotesDatabase.child(noteId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("title") && dataSnapshot.hasChild("timestamp")) {
String title = dataSnapshot.child("title").getValue().toString();
String timestamp = dataSnapshot.child("timestamp").getValue().toString();
viewHolder.setNoteTitle(title);
//viewHolder.setNoteTime(timestamp);
GetTimeAgo getTimeAgo = new GetTimeAgo();
viewHolder.setNoteTime(getTimeAgo.getTimeAgo(Long.parseLong(timestamp), getApplicationContext()));
viewHolder.noteCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(DiaryActivity.this, DiaryNewNoteActivity.class);
intent.putExtra("noteId", noteId);
startActivity(intent);
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mNotesList.setAdapter(firebaseRecyclerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.diary_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.new_note_button:
Intent newIntent = new Intent(DiaryActivity.this, DiaryNewNoteActivity.class);
startActivity(newIntent);
break;
}
return true;
}
/**
* Converting dp to pixel
*/
private int dpToPx(int dp) {
Resources r = getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
}
com.firebase.ui.database.FirebaseRecyclerAdapter is abstract.
If you want to extend it (as you do with an anonymous class in your method loadData()) you have to implement all its abstract methods. In that case apparently onCreateViewHolder(ViewGroup, int).
Add this method implementation to your anonymous class and you are done.
Related
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. :-)
I've been working on a Android Project (A Basic College Information App), I have three main activities, the user goes in like, Goal/Course Select activity-> CollegeList activity-> College Details Activity. Now When I press back on College Details Activity it crashes with this Error:
Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
Below are the files/code which I think might be responsible for this.....
CollegeListActivity.java file
package com.anurag.college_information.activities;
import static com.anurag.college_information.activities.CareerGoalActivity.GOAL;
import static com.anurag.college_information.activities.CareerGoalActivity.SHARED_PREFS;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.anurag.college_information.R;
import com.anurag.college_information.adapters.RecyclerAdapter;
import com.anurag.college_information.models.ModelClass;
import java.util.ArrayList;
import java.util.List;
public class CollegeListActivity extends AppCompatActivity {
private RecyclerAdapter.RecyclerViewClickListener listener;
//ListView collegeList;
TextView collegeListTitle;
Button courseChange;
RecyclerView recyclerView;
LinearLayoutManager LayoutManager;
RecyclerAdapter recyclerAdapter;
List<ModelClass> cList;
String courseName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_college_list);
collegeListTitle = findViewById(R.id.college_list_title);
courseChange = findViewById(R.id.btn_change_course);
//collegeListTitle.setText(goal + "Colleges");
collegeListTitle.setText(getIntent().getStringExtra("Title") + " Colleges");
initData();
initRecyclerView();
//collegeList = findViewById(R.id.lv_college_list);
courseChange.setTransformationMethod(null);
courseChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
Intent i = new Intent(CollegeListActivity.this, CareerGoalActivity.class);
startActivity(i);
//finish();
}
});
}
private void initData() {
cList = new ArrayList<>();
courseName = getIntent().getStringExtra("Title");
switch (courseName) {
case "BE/BTech":
cList.add(new ModelClass("https://images.static-collegedunia.com/public/college_data/images/campusimage/1479294300b-5.jpg", "A.P. Shah College of Engineering", "Thane", "8.0"));
break;
case "Pharmacy":
cList.add(new ModelClass("https://images.static-collegedunia.com/public/college_data/images/campusimage/14382400753.jpg", "Bombay College Of Pharmacy", "Mumbai", "9.0"));
break;
}
}
private void initRecyclerView() {
setOnClickListener();
recyclerView = findViewById(R.id.recycler_view);
LayoutManager = new LinearLayoutManager(this);
LayoutManager.setOrientation(RecyclerView.VERTICAL);
recyclerView.setLayoutManager(LayoutManager);
recyclerAdapter = new RecyclerAdapter(cList, listener);
recyclerView.setAdapter(recyclerAdapter);
}
private void setOnClickListener() {
listener = new RecyclerAdapter.RecyclerViewClickListener() {
#Override
public void onClick(View v, int position) {
Intent i = new Intent(CollegeListActivity.this, CollegeDetailsActivity.class);
startActivity(i);
}
};
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
RecyclerAdapter.java
package com.anurag.college_information.adapters;
import android.content.Context;
import android.content.Intent;
import android.telecom.Call;
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.recyclerview.widget.RecyclerView;
import com.anurag.college_information.activities.CollegeDetailsActivity;
import com.anurag.college_information.models.ModelClass;
import com.anurag.college_information.R;
import com.squareup.picasso.Picasso;
import java.util.List;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private List<ModelClass> collegeList ;
private RecyclerViewClickListener listener;
List<String> imageUrl, collegeName, collegeLocation, collegeRating;
public RecyclerAdapter(List<ModelClass> collegeList, RecyclerViewClickListener listener){
this.collegeList=collegeList;
this.listener = listener;
}
#NonNull
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.college_list_single_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerAdapter.ViewHolder holder, int position) {
String imageLink = collegeList.get(position).getImageLink();
//int img = collegeList.get(position).getCollegeImage();
String cName = collegeList.get(position).getCollegeName();
String cRating = collegeList.get(position).getCollegeRating();
String cLocation = collegeList.get(position).getLocation();
Picasso.get().load(imageLink).into(holder.imageView);
//holder.setData(img, cName, cRating);
holder.setData(imageLink, cName, cLocation ,cRating);
}
#Override
public int getItemCount() {
return collegeList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView imageView;
private TextView collegeName, collegeRating, collegeLocation;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.college_image);
collegeName = itemView.findViewById(R.id.college_name);
collegeRating = itemView.findViewById(R.id.college_rating);
collegeLocation = itemView.findViewById(R.id.college_location);
itemView.setOnClickListener(this);
}
public void setData(String imageLink, String cName, String cLocation, String cRating) {
//imageView.setImageResource(img);
Picasso.get().load(imageLink).error(R.drawable.error).into(imageView);
collegeName.setText(cName);
collegeRating.setText(cRating);
collegeLocation.setText(cLocation);
}
#Override
public void onClick(View v) {
listener.onClick(v, getAdapterPosition());
Intent i = new Intent(v.getContext(), CollegeDetailsActivity.class);
i.putExtra("collegeImage", collegeList.get(getAdapterPosition()).getImageLink());
i.putExtra("collegeName", collegeList.get(getAdapterPosition()).getCollegeName());
i.putExtra("collegeRating", collegeList.get(getAdapterPosition()).getCollegeRating());
i.putExtra("collegeLocation", collegeList.get(getAdapterPosition()).getLocation());
v.getContext().startActivity(i);
}
}
public interface RecyclerViewClickListener{
void onClick(View v, int position);
}
}
CollegeDetailsActivity.java
package com.anurag.college_information.activities;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.anurag.college_information.R;
import com.squareup.picasso.Picasso;
public class CollegeDetailsActivity extends AppCompatActivity {
Button btnApply;
ImageView dCollegeImage;
TextView dCollegeName, dCollegeRating, dCollegeLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_college_details);
dCollegeImage = findViewById(R.id.details_college_image);
dCollegeName = findViewById(R.id.details_college_name);
dCollegeRating = findViewById(R.id.details_college_rating);
dCollegeLocation = findViewById(R.id.details_college_location);
btnApply = findViewById(R.id.btn_apply);
Intent i = getIntent();
String cn = i.getStringExtra("collegeName");
String cr = i.getStringExtra("collegeRating");
String ci = i.getStringExtra("collegeImage");
String cl = i.getStringExtra("collegeLocation");
Picasso.get().load(ci).error(R.drawable.error).into(dCollegeImage);
dCollegeName.setText(cn);
dCollegeRating.setText(cr);
dCollegeLocation.setText(cl);
btnApply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "The institute will be notified, of your application", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "The college will contact you, Thank you", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onBackPressed() {
Intent i = new Intent(CollegeDetailsActivity.this, CollegeListActivity.class);
startActivity(i);
}
}
This is the Error Screenshot:
I'm pretty new to android I've just worked on just 4 to 5 projects,
Any Assistance will be appreciated, Thank You
The commented Out code, is just a normal listview I implemented just In Case, I have to remove the recycler view.
This will probably go away if you don't override onBackPressed in CollegeDetailsActivity. Instead of going back to an activity that had a valid "Title" string extra, the code you posted will go to a new activity where "Title" isn't defined, then get a NullPointerException since courseName will be null in initData (which the error message tells you results in an error on line 81 in that method). Using a null string in a switch results in that type of error
Just remove your onBackPressed entirely in CollegeDetailsActivity.
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
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
I need help, I am making a simple application, and I donĀ“t know how to return to the MainActivity the string from the spinner and the name of the person when i click in the "Aceptar" button.
MainActivity.java
package com.example.holaamigos;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
public final static String EXTRA_SALUDO = "com.example.holaamigos.SALUDO";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtNombre = (EditText)findViewById(R.id.TxtNombre);
final Button btnHola = (Button)findViewById(R.id.BtnHola);
final CheckBox checkbox1 =(CheckBox)findViewById(R.id.checkBox1);
checkbox1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0,
boolean checked) {
if (checked)
{
Toast.makeText(checkbox1.getContext(), "Activo", Toast.LENGTH_LONG).show();
btnHola.setVisibility(0);
btnHola.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ActivitySaludo.class);
String saludo = txtNombre.getText().toString();
intent.putExtra(EXTRA_SALUDO, saludo);
startActivity(intent);
}
});
}
else
{
Toast.makeText(checkbox1.getContext(), "Inactivo", Toast.LENGTH_SHORT).show();
btnHola.setVisibility(View.INVISIBLE);
}
}
});
}
public void HobbyReturn(int requestcode, int resultadocode, Intent data) {
if (resultadocode == ActivitySaludo.ACEPTAR_OK); {
String string = data.getStringExtra(ActivitySaludo.ACEPTAR_OK);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
ActivitySaludo
package com.example.holaamigos;
import com.example.holaamigos.R.string;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class ActivitySaludo extends Activity {
public static final String ACEPTAR_OK = "com.example.holaamigos.ACEPTAR_OK";
String myspinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saludo);
Intent intent = getIntent();
String saludo = intent.getStringExtra(MainActivity.EXTRA_SALUDO);
TextView txtCambiado = (TextView) findViewById(R.id.TxtSaludo);
txtCambiado.setText(getString(R.string.hola_saludo) + " " + saludo);
final Spinner spinner = (Spinner)findViewById(R.id.SpinnerSaludo);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.hobby, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener () {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
parent.getItemAtPosition(pos);
myspinner = spinner.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
//another call
}
});
final Button BtnAceptar=(Button) findViewById(R.id.buttonAceptar);
BtnAceptar.setOnClickListener(new OnClickListener (){
#Override
public void onClick(View v) {
Intent iboton = new Intent();
iboton.putExtra("HOBBY", myspinner);
setResult(ACEPTAR_OK, iboton);
finish();
}
});
}
}
You need to start your second activity with the flag that you are waiting for a result, so instead of startActivity you need to make use of startActivityForResult.
If you need a little bit more information take a look at this tutorial it should cover all you need to get things working.