MVVM firebase user authentification - java

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.

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. :-)

My Quiz App is crashing when I load Categories from Firebase Firestore but able to recieve users data to firestore from App

When I try to load categories in any activity the quizapp is getting crashed when i load. But when i send users data to firestore, its working.
All the data set in DbQuery.java matches the names entered with Firestore data. But There is something wrong in this that whenever I load this data in login Activity, signup activity or splash activity the app is getting crashed.
Here is my code:
DbQuery.java
package com.nightout.ttsgeneralawareness;
import android.content.Intent;
import android.util.ArrayMap;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.firebase.firestore.WriteBatch;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class DbQuery {
public static FirebaseFirestore g_firestore;
public static List<CategoryModel> g_catList = new ArrayList<>();
public static void createUserData(String email, String name, MyCompleteListener completeListener) {
Map<String, Object> userData = new ArrayMap<>();
userData.put("EMAIL_ID", email);
userData.put("NAME", name);
userData.put("TOTAL_SCORE", 0);
DocumentReference userDoc = g_firestore.collection("USERS")
.document(Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getUid());
WriteBatch batch = g_firestore.batch();
batch.set(userDoc, userData);
DocumentReference countDoc = g_firestore.collection("USERS").document("TOTAL_USERS");
batch.update(countDoc, "COUNT", FieldValue.increment(1));
batch.commit()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
completeListener.onSuccess();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
completeListener.onFailure();
}
});
}
public static void loadCategories(MyCompleteListener completeListener) {
g_catList.clear();
g_firestore.collection("QUIZ").get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
Map<String, QueryDocumentSnapshot> docList = new ArrayMap<>();
for (QueryDocumentSnapshot doc : queryDocumentSnapshots) {
docList.put(doc.getId(), doc);
}
QueryDocumentSnapshot catListDooc = docList.get("Categories");
long catCount = catListDooc.getLong("COUNT");
for (int i = 1; i <= catCount; i++) {
String catID = catListDooc.getString("CAT" + String.valueOf(i) + "_ID");
QueryDocumentSnapshot catDoc = docList.get(catID);
int noOfTest = catDoc.getLong("NO_OF_TESTS").intValue();
String catName = catDoc.getString("NAME");
g_catList.add(new CategoryModel(catID, catName, noOfTest));
}
completeListener.onSuccess();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
completeListener.onFailure();
}
});
}
LoginActivity.java
package com.nightout.ttsgeneralawareness;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import java.util.Locale;
public class LoginActivity extends AppCompatActivity {
private EditText email, password;
private Button loginButton;
private TextView forgotpwd, signup_button;
private FirebaseAuth mAuth;
private Dialog progressDialog;
private TextView dialogText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
email = findViewById(R.id.email);
password = findViewById(R.id.password);
loginButton = findViewById(R.id.login_button);
forgotpwd = findViewById(R.id.forgot_pwd);
signup_button = findViewById(R.id.signup_button);
//google
progressDialog = new Dialog(LoginActivity.this);
progressDialog.setContentView(R.layout.dialog);
progressDialog.setCancelable(false);
progressDialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
dialogText = progressDialog.findViewById(R.id.dialog_text);
dialogText.setText("Signing in...");
mAuth = FirebaseAuth.getInstance();
//google
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (validData())
{
login();
}
}
});
signup_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, SignUpActivity.class);
startActivity(intent);
}
});
}
private boolean validData()
{
if (email.getText().toString().isEmpty())
{
email.setError("Enter E-Mail ID");
return false;
}
if (password.getText().toString().isEmpty())
{
password.setError("Enter Password");
return false;
}
return true;
}
private void login()
{
progressDialog.show();
mAuth.signInWithEmailAndPassword(email.getText().toString().trim(), password.getText().toString().trim())
.addOnCompleteListener(this, task -> {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Toast.makeText(LoginActivity.this,"Login Success",Toast.LENGTH_SHORT).show();
DbQuery.loadCategories(new MyCompleteListener() {
#Override
public void onSuccess() {
progressDialog.dismiss();
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
LoginActivity.this.finish();
}
#Override
public void onFailure() {
progressDialog.dismiss();
Toast.makeText(LoginActivity.this,"Something Went Wrong!",Toast.LENGTH_SHORT).show();
}
});
} else {
progressDialog.dismiss();
// If sign in fails, display a message to the user.
Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
}

Application crash during Item click of recyclerView [duplicate]

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 ?

Android Studio - The (Very) Basics - startActivty doesn't work

im trying to move the info of a user from one activity to the other, but everytime i run the app it crashes at the "startActivity(i)" Line (i checked everything else, it only crashes at that line).
that's the MainActivity Code
package com.example.hw1511;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.hw1511.Model.User;
import org.w3c.dom.Text;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements Serializable {
private EditText Name;
private EditText Age;
private EditText Birth;
private Button AddUser;
private Button Send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Name = findViewById(R.id.Name);
Age = findViewById(R.id.Age);
Birth = findViewById(R.id.Birth);
AddUser = findViewById(R.id.AddUser);
Send = findViewById(R.id.Send);
Intent i = new Intent(MainActivity.this, SecondActivity.class);
List<User> list1 = new LinkedList<>();
AddUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Name.getText().toString().trim().length() > 0 && Age.getText().toString().trim().length() > 0 && Birth.getText().toString().trim().length() > 0) {
User u = new User(Name.getText().toString(), Integer.parseInt(Age.getText().toString()), Birth.getText().toString());
list1.add(u);
Name.setText("");
Age.setText("");
Birth.setText("");
}
else {
Toast.makeText(MainActivity.this, "Fill All", Toast.LENGTH_SHORT).show();
}
}
});
Send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i.putExtra("Users", (Serializable) list1);
startActivity(i);
}
});
}
}
and that's the SecondActivty Code (it's preety much empty)
package com.example.hw1511;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.hw1511.Model.User;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
import java.util.jar.Attributes;
public class SecondActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
}
please if anyone help me understand what is making my app crash everytime i press the send button! it would really help me a lot.
Your User objects need to implement Serializable as well.
Also, since LinkedLists are Serializable you can use putSerializable(String key, Serializable value) instead of putExtra

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

Categories