Adding text to element arraylist - java

I'm creating a listview of an element for my school's project and when I run the app it shows me the element's details. I want it to show a specific text but I can't find how to do it.
here is my java code:
private ArrayList<Playlist>playlists=new ArrayList<Playlist>();
ArrayAdapter<Playlist> adapter;
lvPlaylists=(ListView)findViewById(R.id.lvPlaylists);
adapter =new ArrayAdapter<Playlist>(Playlists.this, android.R.layout.simple_list_item_1, playlists);
lvPlaylists.setAdapter(adapter);
my function to get the items from the firebase cloud firestore to my arraylist
CollectionReference PlaylistsRef = db.collection("Users").document(Mail).collection("Playlists");
PlaylistsRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()){
for (QueryDocumentSnapshot documentSnapshot : task.getResult())
{
if(!task.getResult().getDocuments().isEmpty())
{
String PlaylistName= (String)documentSnapshot.get("Name");
PlaylistsRef.document(PlaylistName).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot != null){
Playlist playlist = new Playlist((String)documentSnapshot.get("Name"), (String)documentSnapshot.get("Genre"));
playlists.add(playlist);
lvPlaylists.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent=new Intent(Playlists.this,PlaylistView.class);
intent.putExtra("Name", adapter.getItem(position).getName());
intent.putExtra("Genre", adapter.getItem(position).getGenre());
intent.putExtra("PN", PN);
startActivity(intent);
}
});
adapter.notifyDataSetChanged();
}
}
});
}
}
}
}
});`
Playlist:
public class Playlist implements Serializable {
private String name;
private String genre;
private ArrayList<Song> songs;
public Playlist(String name, String genre, ArrayList<Song> songs)
{
this.name=name;
this.genre=genre;
this.songs=songs;
}
public Playlist(String name, String genre)
{
this.name=name;
this.genre=genre;
this.songs=null;
}
public Playlist()
{
this.name=null;
this.genre=null;
this.songs=null;
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return this.name;
}
public void setGenre(String genre)
{
this.genre=genre;
}
public String getGenre()
{
return this.genre;
}
public ArrayList<Song> getSongs ()
{
return this.songs;
}
public void addSong (Song song)
{
songs.add(song);
}
public String ToString()
{
return this.name+" "+this.genre;
}
public void removeSong(Song song)
{
for(int i=0;i<this.songs.size();i++)
{
if(this.songs.get(i).getName()==song.getName())
{
this.songs.remove(i);
}
}
}
right now it shows me this when I run the app:
shows me the item's details and I want text

Related

The Response doesn't Succeed return "0"

There is a problem when receiving the response,
response.body().success
it returns 0 but I expect 1
it shows a toast shows Failed! As the code below which means the response doesn't succeed
mService = Common.getFCMService();
private void sendNotificationOrder(String order_number) {
DatabaseReference tokens = FirebaseDatabase.getInstance().getReference("Tokens");
Query data = tokens.orderByChild("isServerToken").equalTo(true);
data.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapShot:dataSnapshot.getChildren()) {
Token serverToken = postSnapShot.getValue(Token.class);
Notification notification = new Notification("Ziead's Company", "You have New Order" + order_number);
Sender content = new Sender(serverToken.getToken(), notification);
mService.sendNotification(content)
.enqueue(new Callback<MyResponse>() {
#Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
try {
//Here It is Returning "0" not 1 System.out.println(response.body().success);
if (response.code() == 200) {
if (response.body().success == 1) {
System.out.println("Succeedd");
Toast.makeText(Cart.this, "Thank you , Order Place", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(Cart.this, "Failed !!!", Toast.LENGTH_SHORT).show();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<MyResponse> call, Throwable t) {
Log.e("ERROR", t.getMessage());
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
Token.java:
public class Token {
private String token;
private boolean isServerToken;
public Token() {
}
public Token(String token, boolean isServerToken)
{
this.token = token;
this.isServerToken = isServerToken;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public boolean isServerToken() {
return isServerToken;
}
public void setServerToken(boolean serverToken) {
isServerToken = serverToken;
}
}
Notification.java:
public class Notification {
public String body;
public String title;
public Notification(String body, String title) {
this.body = body;
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Sender.java:
public class Sender {
public String to;
public Notification notification;
public Sender(String to, Notification notification) {
this.to = to;
this.notification = notification;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public Notification getNotification() {
return notification;
}
public void setNotification(Notification notification) {
this.notification = notification;
}
}
Common.java:
public class Common {
public static APIService getFCMService(){
return RetrofitClient.getClient(BASE_URL).create(APIService.class);
}
}
APIService Interface:
public interface APIService {
#Headers(
{
"Content-Type:application/json",
"Authorization:key=AAAA0EXeo9E:APA91bGeAWN69zVVIKh9ib_XA6OkMnEA1S0_sZILrJ1civQVF-eelOAF4o3qCOTZpRgSwb9bySoU92ypchs5BqOE2P1Y_FPlvUanIrV2g7RPCY7IpGjYqSK1rlKVxODm6v8R"
}
)
#POST("fcm/send")
Call<MyResponse> sendNotification(#Body Sender body);
}
RetrofitClient.java:
This is all the code related to the main code

How to set an question image to ImageView from Firebase in QuizApp

I am working on a quiz app basically. In my app there are many questions getting datas from Firebase Database with those areas (question, optionA,optionB,optionC,optionD and correctANS) but I want to improve my project. I want to add image questions instead of text questions. For this I added an area(urlImage) to my database on Firebase. Normally I can get data from Firebase except urlImage but I didn't see Image in ImageView in my app. What should i do? Please someone help me?
those are my QuestionsActivity codes:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions);
Toolbar toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
question=findViewById(R.id.question);
urlImage=findViewById(R.id.urlImage);
noIndicator=findViewById(R.id.no_indicator);
bookmarkBtn=findViewById(R.id.bookmark_btn);
optionsContainer=findViewById(R.id.option_container);
shareBtn=findViewById(R.id.share_btn);
nextBtn=findViewById(R.id.next_btn);
preferences=getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
editor=preferences.edit();
gson=new Gson();
getBookmarks();
bookmarkBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (modelMatch()){
bookmarkslist.remove(matchedQuestionPosition);
bookmarkBtn.setImageDrawable(getDrawable(R.drawable.bookmark_border));
}else{
bookmarkslist.add(list.get(position));
bookmarkBtn.setImageDrawable(getDrawable(R.drawable.bookmark));
}
}
});
setId=getIntent().getStringExtra("setId");
loadingDialog=new Dialog(this);
loadingDialog.setContentView(R.layout.loading);
loadingDialog.getWindow().setBackgroundDrawable(getDrawable(R.drawable.rounded_corner2));
loadingDialog.getWindow().setLayout(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
loadingDialog.setCancelable(false);
list=new ArrayList<>();
loadingDialog.show();
myRef.child("SETS").child(setId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
String id=dataSnapshot1.getKey();
String question= dataSnapshot1.child("question").getValue().toString();
String a= dataSnapshot1.child("optionA").getValue().toString();
String b= dataSnapshot1.child("optionB").getValue().toString();
String c= dataSnapshot1.child("optionC").getValue().toString();
String d= dataSnapshot1.child("optionD").getValue().toString();
String correctANS= dataSnapshot1.child("correctANS").getValue().toString();
String urlImage= dataSnapshot1.child("urlImage").getValue().toString();
list.add(new QuestionModel(id,question,a,b,c,d,correctANS,urlImage,setId));
}
if (list.size() > 0){
for (int i=0;i<4;i++){
optionsContainer.getChildAt(i).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkhanswer(((Button)view));
}
});
}
playAnim(question,0,list.get(position).getQuestion());
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
nextBtn.setEnabled(false);
nextBtn.setAlpha(0.7f);
enableOption(true);
position++;
if (position==list.size()){
Intent scoreIntent=new Intent(QuestionsActivity.this,ScoreActivity.class);
scoreIntent.putExtra("score",score);
scoreIntent.putExtra("total",list.size());
startActivity(scoreIntent);
finish();
return;
}
count=0;
playAnim(question,0,list.get(position).getQuestion());
}
});
}else{
finish();
Toast.makeText(QuestionsActivity.this, "There isn't any question.", Toast.LENGTH_SHORT).show();
}
loadingDialog.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(QuestionsActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
loadingDialog.dismiss();
finish();
}
});
// playAnim(question,0,list.get(position).getQuestion());
}
#Override
protected void onPause() {
super.onPause();
storeBookmarks();
}
private void playAnim(final View view, final int value, final String data){
// for (int i=0;i<4;i++){
// optionsContainer.getChildAt(i).setBackgroundTintList(null);
// }
view.animate().alpha(value).scaleX(value).scaleY(value).setDuration(500).setStartDelay(100)
.setInterpolator(new DecelerateInterpolator()).setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animator) {
if (value == 0 && count<4){
String option="";
if (count==0){
option=list.get(position).getA();
}
else if(count==1){
option=list.get(position).getB();
}
else if(count==2){
option=list.get(position).getC();
}
else if(count==3){
option=list.get(position).getD();
}
playAnim(optionsContainer.getChildAt(count),0,option);
count++;
}
}
#Override
public void onAnimationEnd(Animator animator) {
((TextView)view).setText(data);
if (value==0){
try {
((TextView)view).setText(data);
noIndicator.setText(position+1+"/"+list.size());
if (modelMatch()){
bookmarkBtn.setImageDrawable(getDrawable(R.drawable.bookmark));
}else{
bookmarkBtn.setImageDrawable(getDrawable(R.drawable.bookmark_border));
}
}catch (ClassCastException e){
((Button)view).setText(data);
}
view.setTag(data);
playAnim(view,1,data);
// playAnim(urlResim,0,list.get(position).getUrlResim());
}
}
#Override
public void onAnimationCancel(Animator animator) {
}
#Override
public void onAnimationRepeat(Animator animator) {
}
});
}
those are my QuestionModel codes:
public class QuestionModel {
private String id,question,A,B,C,D,answer,set,urlImage;
public QuestionModel(String id, String question, String a, String b, String c, String d, String answer,
String set,String urlImage) {
this.id = id;
this.question = question;
A = a;
B = b;
C = c;
D = d;
this.answer = answer;
this.set = set;
this.urlImage=urlImage;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getA() {
return A;
}
public void setA(String a) {
A = a;
}
public String getB() {
return B;
}
public void setB(String b) {
B = b;
}
public String getC() {
return C;
}
public void setC(String c) {
C = c;
}
public String getD() {
return D;
}
public void setD(String d) {
D = d;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public String getSet() {
return set;
}
public void setSet(String set) {
this.set = set;
}
public String getUrlImage() {
return urlImage;
}
public void setUrlImage(String urlResim) {
this.urlImage = urlImage;
}
}

Cannot called a variable from another class in Java Android Studio

I'm doing a function that will delete a record in a real time Firebase. A person can only delete their own record by knowing the unique ID generated by the .getKey(). However when i want implement the RecordID to delete, I couldn't called the RecordID. Does anyone know what i'm doing wrong here ? Thanks.
Error
My error demo, the variable doesnt recognize in my delete function
My get class
package com.example.sossystem;
public class SosRecords {
String RecordID;
String FullName;
String PhoneNumber;
String EmailAddress;
public SosRecords(){
}
public SosRecords(String recordID, String fullName, String phoneNumber, String emailAddress) {
RecordID = recordID;
FullName = fullName;
PhoneNumber = phoneNumber;
EmailAddress = emailAddress;
}
public String getRecordID() {
return RecordID;
}
public String getFullName() {
return FullName;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public String getEmailAddress() {
return EmailAddress;
}
}
Error
The error is showed on the Stop button
btnStopSOS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onStop();
stopLocationUpdates();
deleteRecords(RecordID);
result.setText("Dashboard");
btnStartSOS.setEnabled(true);
btnStopSOS.setEnabled(false);
}
});
}
private void deleteRecords(String fullName) {
DatabaseReference delRecord = FirebaseDatabase.getInstance().getReference("Records").child(RecordID);
delRecord.removeValue();
Toast.makeText(MainActivity.this, "The SOS Request is Stopped!", Toast.LENGTH_SHORT).show();
}
My Code
btnStartSOS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onStart();
//GET ALL INFORMATION FROM FIRESTORE AND SEND TO REALTIME DATABASE
if(FirebaseAuth.getInstance().getCurrentUser()!= null){
DocumentReference df = FirebaseFirestore.getInstance().collection("Users").document(FirebaseAuth.getInstance().getCurrentUser().getUid());
df.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.getString("FullName")!= null){
String id = reff.push().getKey();
Log.d(TAG, "asdasd"+id);
SosRecords sosRecords = new SosRecords(id,documentSnapshot.getString("FullName"), (documentSnapshot.getString("PhoneNumber")), (documentSnapshot.getString("UserEmail") ));
reff.child(id).setValue(sosRecords);
btnStopSOS.setEnabled(true);
Toast.makeText(MainActivity.this, "You're are now activating SOS request !", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(),Login.class));
finish();
}
});
}
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
checkSettingsAndStartLocationUpdates();
}else{
askLocationPermission();
}
}
});
btnStopSOS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onStop();
stopLocationUpdates();
deleteRecords(RecordID);
result.setText("Dashboard");
btnStartSOS.setEnabled(true);
btnStopSOS.setEnabled(false);
}
});
}
private void deleteRecords(String fullName) {
DatabaseReference delRecord = FirebaseDatabase.getInstance().getReference("Records").child(RecordID);
delRecord.removeValue();
Toast.makeText(MainActivity.this, "The SOS Request is Stopped!", Toast.LENGTH_SHORT).show();
}
SosRecords sosrecords = new SosRecords();
btnStopSOS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onStop();
stopLocationUpdates();
deleteRecords(sosrecords.getRecordID);
result.setText("Dashboard");
btnStartSOS.setEnabled(true);
btnStopSOS.setEnabled(false);
}
});
}
I successfully solved it by set the value of the Id to my RecordID
sosrecords.setRecordID(id);

Display Detail firebase data from listview onitemclick Android Studio

The problem I am facing is that I cannot display the detail of the ListView on which I clicked, any suggestion to display the detail of the Firebase data, I'm done for itemOnClick and change to another activity, but the problem is that it shows only the text of ListView and not the detail, thank you
LISTVIEW JAVA CLASS
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
final String value = dataSnapshot.getValue(Sample.class).toString();
arrayList.add(0,value);
listcase.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), Report.class);
//String sample = String.valueOf(arrayList.get(i));//arrayAdapter.getItem(i);
intent.putExtra("sample", String.valueOf(arrayList.get(i)));
startActivity(intent);
overridePendingTransition(R.anim.slide_right_entering, R.anim.slide_right_exiting);
finish();
}
});
}
});
CONSTRUCTOR
public Sample() {
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
public String getSymthom() {
return symthom;
}
public void setSymthom(String symthom) {
this.symthom = symthom;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getDateDiag() {
return DateDiag;
}
public void setDateDiag(String dateDiag) {
DateDiag = dateDiag;
}
public String toString (){
return "Sample Name : " + Name + "\n"+ "Status : ";
}
DETAIL JAVA CLASS
Intent intent = getIntent();
if (intent.hasExtra("sample"))
{
textView.setText(intent.getStringExtra("sample"));
}
I have no idea how to display detail of my Firebase object to another activity, thank you for helping me
Your ArrayList contains an only String, not a detail object.
final String value = dataSnapshot.getValue(Sample.class).toString();
So when you get by index it returns item value. If you share the value of value JSON structure it would be good to understand better.
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot){
Log.d("data", "onDataChange: "+ dataSnapshot);
Sample Sample = snapshot.getValue(Sample.class);
sampleList.add(Sample);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

Error while passing a model from an activity to another

So I'm following Coding with Mitch's tutorial on Firestore and I'm changing it to fit my personals needs. I'm building a TO-DO App (This is my first ever app/project) Right now, I'm trying to make a second activity in order to view, update and delete the selected task (This activity is ViewTaskActivity). I'm stuck when trying to pass the current task from the MainActivity to the ViewTaskActivity. When I try to call a method on the task variable, it gives me an error.
Here's the code:
Task Model:
package dev.raphdl.firebasepractice.models;
imports ...
#IgnoreExtraProperties
public class Task implements Parcelable {
private String title;
private String content;
private #ServerTimestamp Date timestamp;
private String note_id;
public Task(String title, String content, Date timestamp, String note_id) {
this.title = title;
this.content = content;
this.timestamp = timestamp;
this.note_id = note_id;
}
public Task(){
}
private Task(Parcel in) {
title = in.readString();
content = in.readString();
note_id = in.readString();
}
public static final Creator<Task> CREATOR = new Creator<Task>() {
#Override
public Task createFromParcel(Parcel in) {
return new Task(in);
}
#Override
public Task[] newArray(int size) {
return new Task[size];
}
};
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public String getNote_id() {
return note_id;
}
public void setNote_id(String note_id) {
this.note_id = note_id;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(title);
parcel.writeString(content);
parcel.writeString(note_id);
}
}
MainActivity
package dev.raphdl.firebasepractice;
imports ...
public class MainActivity extends AppCompatActivity implements
View.OnClickListener,
IMainActivity {
#Override
public void updateTask(final Task mTask) {
DocumentReference docRef = db
.collection("users")
.document(mAuth.getCurrentUser().getUid())
.collection("tasks")
.document(mTask.getNote_id());
docRef.update("title", mTask.getTitle(),"content", mTask.getContent()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull com.google.android.gms.tasks.Task<Void> task) {
if(task.isSuccessful()){
makeSnackBarMessage("Updated Task");
mAdapter.updateTask(mTask);
} else {
makeSnackBarMessage("Update Failed, Check logs");
}
}
});
}
#Override
public void deleteTask(final Task mTask){
DocumentReference docRef = db
.collection("users")
.document(mAuth.getCurrentUser().getUid())
.collection("tasks")
.document(mTask.getNote_id());
docRef.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull com.google.android.gms.tasks.Task<Void> task) {
if (task.isSuccessful()){
makeSnackBarMessage("Task Deleted");
mAdapter.deleteTask(mTask);
} else {
makeSnackBarMessage("Failed to Delete, Check Logs");
}
}
});
}
#Override
public void onTaskSelected(Task mTask) {
viewTaskActivity(mTask);
}
private void viewTaskActivity(Task task) {
Intent intent = new Intent(this, ViewTaskActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("Task", task);
intent.putExtras(bundle);
startActivity(intent);
}
}
MainActivityInterface
package dev.raphdl.firebasepractice;
import dev.raphdl.firebasepractice.models.Task;
public interface IMainActivity {
void createNewTask(String title, String content);
void onTaskSelected(Task mTask);
void updateTask (Task mTask);
void deleteTask(Task mTask);
}
ViewTaskActivity
package dev.raphdl.firebasepractice;
imports ...
public class ViewTaskActivity extends AppCompatActivity implements View.OnClickListener {
private IMainActivity mIMainActivity;
private Task mTask;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_task);
Bundle bundle = getIntent().getExtras();
mTask = bundle.getParcelable("Task");
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.save_text_view: {
String title = titleEditText.getText().toString();
String content = contentEditText.getText().toString();
if (mTask != null) {
Toast.makeText(this, "mTask Not NULL", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onClick: mTask Not NULL");
mTask.setTitle(title);
mTask.setContent(content);
//THIS IS THE LINE THAT TRIGGERS THE ERROR
mIMainActivity.updateTask(mTask);
mainActivity();
}else {
Log.d(TAG, "onClick: mTask NULL");
Toast.makeText(this, "mTask NULL", Toast.LENGTH_SHORT).show();
}
break;
}
case R.id.delete_text_view: {
mIMainActivity.deleteTask(mTask);
mainActivity();
break;
}
}
}
private void mainActivity() {
Intent intent = new Intent(this, MainActivity.class);
Toast.makeText(this, "MainActivity", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
}
Finally, the error:
6072-6072/dev.raphdl.firebasepractice E/AndroidRuntime: FATAL EXCEPTION: main
Process: dev.raphdl.firebasepractice, PID: 6072
java.lang.NullPointerException: Attempt to invoke interface method 'void dev.raphdl.firebasepractice.IMainActivity.updateTask(dev.raphdl.firebasepractice.models.Task)' on a null object reference
at dev.raphdl.firebasepractice.ViewTaskActivity.onClick(ViewTaskActivity.java:68)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24697)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Sorry for the big blocks of code.
FYI: the app gives me the same error when trying to delete the task
I'm am still a beginner so this could be me just forgetting something.
Thank you for reading this
First understand the basic concepts of JAVA. You have to create object of the class which is implementing the interface. In your case MainActivity is implementing interface IMainActivity. So you need to initialize mIMainActivity with MainActivity object for ex:
IMainActivity mIMainActivity = new MainActivity();

Categories