Firebase UI : RecyclerView items are not shown - java

I have been trying to implement Firebase-UI in my app with RecyclerView.
I created a recyclerView users list in a chat app with Realtime database and Firebase-UI, I wanted to retrieve data from ProfileActivity and display them in my AllUsersActivity. The issue is that the RecyclerView items are not displaying and I'm getting this error :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.schoolteacher, PID: 19631
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.ChildEventListener com.google.firebase.database.Query.addChildEventListener(com.google.firebase.database.ChildEventListener)' on a null object reference
at com.firebase.ui.database.FirebaseArray.onCreate(FirebaseArray.java:54)
at com.firebase.ui.common.BaseObservableSnapshotArray.addChangeEventListener(BaseObservableSnapshotArray.java:97)
at com.firebase.ui.database.FirebaseRecyclerAdapter.startListening(FirebaseRecyclerAdapter.java:52)
at com.example.schoolteacher.AllUsersActivity.onStart(AllUsersActivity.java:112)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1419)
at android.app.Activity.performStart(Activity.java:7479)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3454)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
at android.os.Handler.dispatchMessage(Handler.java:112)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
Here is my code :
AllUsersActivity.java
public class AllUsersActivity extends AppCompatActivity {
private DatabaseReference mUsersDatabase;
private LinearLayoutManager linearLayoutManager;
private RecyclerView recyclerView;
private Query query;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_users);
recyclerView = findViewById(R.id.recycler_view);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
query = FirebaseDatabase.getInstance().getReference().child("Users");
}
FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users>()
.setQuery(query, Users.class)
.build();
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull UsersViewHolder holder, int position, #NonNull Users model) {
holder.setName(model.getName());
}
#Override
public UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.message for each item
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_all_users, parent, false);
return new UsersViewHolder(view);
}
};
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name) {
TextView mName = mView.findViewById(R.id.user_single_name);
mName.setText(name);
}
}
ProfileInfoActivity
public class ProfileInfoActivity extends AppCompatActivity {
private DatabaseReference mDatabaseReference;
private FirebaseUser mCurrentUser;
private CircleImageView mDisplayImage;
private TextView mName;
private TextInputEditText mEditName, mEmail;
private TextView mStatus;
private ImageButton mStatusBtn;
private static final int GALLERY_PICK = 1;
private StorageReference mImageStorage;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_info);
mDisplayImage = findViewById(R.id.circle_image);
mName = findViewById(R.id.name);
mEditName = findViewById(R.id.et_name);
mEmail = findViewById(R.id.et_email_address);
mStatus = findViewById(R.id.status);
mStatusBtn = findViewById(R.id.status_btn);
mImageStorage = FirebaseStorage.getInstance().getReference();
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String userID = mCurrentUser.getUid();
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(userID);
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue().toString();
String et_name = dataSnapshot.child("name").getValue().toString();
String et_email_adress = dataSnapshot.child("email").getValue().toString();
String image = dataSnapshot.child("image").getValue().toString();
String status = dataSnapshot.child("status").getValue().toString();
String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();
mName.setText(name);
mEditName.setText(et_name);
mEmail.setText(et_email_adress);
mStatus.setText("Teacher at "+ status);
Picasso.get().load(image).into(mDisplayImage);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mDisplayImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICK);
}
});
mStatusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//send status data to changeSchoolActivity to retrieve it
String status_value = mStatus.getText().toString();
Intent status_intent = new Intent(ProfileInfoActivity.this, ChangeSchoolActivity.class);
status_intent.putExtra("status_value", status_value);
startActivity(status_intent);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_PICK && resultCode == RESULT_OK ) {
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setAspectRatio(1, 1)
.start(this);
//Toast.makeText(ProfileInfoActivity.this, imageUri, Toast.LENGTH_SHORT).show();
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mProgressDialog = new ProgressDialog(ProfileInfoActivity.this);
mProgressDialog.setTitle("Uploading Image...");
mProgressDialog.setMessage("Please wait while we upload and process the image");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
Uri resultUri = result.getUri();
String current_user_id = mCurrentUser.getUid();
final StorageReference filepath = mImageStorage.child("profile_images").child(current_user_id + ".jpg");
filepath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String download_url = uri.toString();
mDatabaseReference.child("image").setValue(download_url).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mProgressDialog.dismiss();
Toast.makeText(ProfileInfoActivity.this,"Success Uploading",Toast.LENGTH_SHORT).show();
}
});
}
});
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}

According to your last comment:
protected void onStart() { super.onStart(); firebaseRecyclerAdapter.startListening(); }
Is the line at which the error occurs. To solve this, please create the firebaseRecyclerAdapter variable as a global variable by adding the following line of code:
private FirebaseRecyclerAdapter firebaseRecyclerAdapter;
Right after:
private Query query;
And remove the type declaration from your code:
//FirebaseRecyclerAdapter does not exist anymore
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(firebaseRecyclerOptions) {
#NonNull
#Override
public UsersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_single_layout, parent, false);
return new UsersViewHolder(mView);
}
#Override
protected void onBindViewHolder(#NonNull UsersViewHolder holder, int position, #NonNull Users model) {
holder.setName(model.getName());
}
};

Related

onbindViewholder include null object

When I run the activity it shows me items that I want plus a null card view(when i delete tostring() from holder.setTitle("product name:"+model.getName().toString()); I'm trying so hard to solve this problem but I didn't find a solution.
this is my class Client_order:
public class Client_order extends AppCompatActivity {
FragmentManager fragmentManager;
Fragment Settingsfrag,Orderfrag,panierfrag;
TextView delorder;
Order model2;
Button submit;
DatabaseReference ref,ref1,ref2;
private Toolbar hometoolbar;
private ImageView settingsbtn, orderIV, imageView7,imageView10;
private RecyclerView orderrv;
private FirebaseAuth mAuth;
private FirebaseUser currentUser;
private DatabaseReference mDatabase;
private String user_id;
Spinner spinnerorder;
private String name;
private String email;
private String phone;
TextView tvName;
Orderviewholder holder1;
private FirebaseRecyclerAdapter<Order, Orderviewholder> orderAdapter;
DatabaseReference dborder,dbpanier;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_order);
tvName = findViewById(R.id.tvName);
hometoolbar = findViewById(R.id.hometoolbarorder);
hometoolbar.setTitle("ordre");
hometoolbar.setTitleTextColor(Color.WHITE);
settingsbtn = findViewById(R.id.settingsbtn);
orderIV = findViewById(R.id.orderIV);
imageView7 = findViewById(R.id.imageView7);
fragmentManager=getSupportFragmentManager();
Orderfrag=fragmentManager.findFragmentById(R.id.orderfrag);
Settingsfrag=fragmentManager.findFragmentById(R.id.settingsfrag);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
mDatabase = FirebaseDatabase.getInstance().getReference();
if (currentUser == null) {
Intent intent=new Intent(Client_order.this,Login.class);
startActivity(intent);
} else {
if (!mAuth.getCurrentUser().isEmailVerified()) {
Toast.makeText(getApplicationContext(), "Please verify your email address", Toast.LENGTH_LONG).show();
Intent startActivity = new Intent(this, Login.class);
startActivity(startActivity);
finish();
} else {
user_id = currentUser.getUid();
}
}
Toast.makeText(getApplicationContext(),user_id, Toast.LENGTH_LONG).show();
panierfrag=fragmentManager.findFragmentById(R.id.panierfrag);
submit=findViewById(R.id.submit);
submit.setVisibility(View.VISIBLE);
fragmentManager.beginTransaction()
.hide(panierfrag)
.show(Orderfrag)
.hide(Settingsfrag)
.commit();
imageView7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(Client_order.this,Client_panier.class);
startActivity(intent);
}
});
settingsbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragmentManager.beginTransaction()
.hide(panierfrag)
.hide(Orderfrag)
.show(Settingsfrag)
.commit();
}
});
orderIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragmentManager.beginTransaction()
.hide(panierfrag)
.show(Orderfrag)
.hide(Settingsfrag)
.commit();
}
});
dborder = FirebaseDatabase.getInstance().getReference().child("order");
dborder.keepSynced(true);
orderrv = (RecyclerView) findViewById(R.id.orderrv);
DatabaseReference personsRef = FirebaseDatabase.getInstance().getReference().child("order").child(user_id.toString());
Query personsQuery = personsRef.orderByKey();
orderrv.hasFixedSize();
orderrv.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions personsOptions = new FirebaseRecyclerOptions.Builder<Order>().setQuery(personsQuery, Order.class).build();
orderAdapter=new FirebaseRecyclerAdapter<Order, Orderviewholder>(personsOptions) {
#Override
protected void onBindViewHolder(#NotNull Orderviewholder holder, int position, #NotNull Order model) {
holder.setTitle("product name:"+model.getName().toString());
holder1=holder;
imageView10=holder.mView.findViewById(R.id.imageVieworder);
Picasso.get().load(model.getImage()).into(imageView10, new Callback() {
#Override
public void onSuccess() {
ProgressBar progressbar3;
progressbar3=holder1.mView.findViewById(R.id.progressBar4);
progressbar3.setVisibility(View.INVISIBLE);
}
#Override
public void onError(Exception e) {
}
});
holder.setdesc(model.getDesc().toString());
holder.setprice(model.getPrice());
holder.setquantity(model.getQuantity());
TextView status;
status=holder.mView.findViewById(R.id.statusorder);
status.setText(model.getStatus());
status.setVisibility(View.VISIBLE);
delorder=holder.mView.findViewById(R.id.orderDelbtn);
delorder.setText("done");
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
delorder.setVisibility(View.VISIBLE);
}
});
model2=model;
delorder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dborder.child(currentUser.getUid()).child(model2.getId()).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NotNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(Client_order.this, "order deleted successfully", Toast.LENGTH_LONG).show();
}
}
});
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ref=FirebaseDatabase.getInstance().getReference().child("order").child(user_id.toString());
ref2=FirebaseDatabase.getInstance().getReference().child("order").child(user_id.toString()).child("submitted");
ref1=FirebaseDatabase.getInstance().getReference().child("order").child("admin");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NotNull DataSnapshot dataSnapshot) {
for (DataSnapshot orderSnapshot: dataSnapshot.getChildren()) {
Order category = orderSnapshot.getValue(Order.class);
//if (category!=null){
ref1.child(category.getId()).setValue(category);
Toast.makeText(Client_order.this,"product successfully submitted", Toast.LENGTH_LONG).show();
ref2.child(category.getId()).setValue(category);
ref.child(category.getId()).removeValue();
// }
}
}
#Override
public void onCancelled(#NotNull DatabaseError databaseError) {
}
});
}
});
}
#NotNull
#Override
public Orderviewholder onCreateViewHolder(#NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.product_list_itemorder, parent, false);
return new Orderviewholder(view);
}
};
orderrv.setAdapter(orderAdapter);
}
#Override
protected void onStart() {
super.onStart();
orderAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
orderAdapter.stopListening();
}
public static class Orderviewholder extends RecyclerView.ViewHolder{
View mView;
public Orderviewholder(View itemView){
super(itemView);
mView = itemView;
}
public void setTitle(String title){
TextView post_title = (TextView)mView.findViewById(R.id.order_name);
post_title.setText(title);
}
public void setdesc(String desc) {
TextView post_title = (TextView) mView.findViewById(R.id.order_description);
post_title.setText(desc);
}
public void setprice(int price) {
TextView post_title = (TextView) mView.findViewById(R.id.order_price);
post_title.setText(Integer.toString(price)+" dhs");
}
public void setquantity(int quantity) {
TextView post_title = (TextView) mView.findViewById(R.id.order_quantity);
post_title.setText(Integer.toString(quantity));
}
}
}
it shows me this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at com.omar.lazywork.Client_order$4.onBindViewHolder(Client_order.java:207)
at com.omar.lazywork.Client_order$4.onBindViewHolder(Client_order.java:204)

How to set ProgressBar value using this code?

I've two values in my document which will help me to set progress bar in the app.
for ex joined and slots. both are numbers.
and below i am fetching the values and setting the progressbar value using the slots and joined number which i fetched from the firestore :
public class Home extends AppCompatActivity {
private FirebaseFirestore mDatabase;
private FirestoreRecyclerAdapter adapter;
RecyclerView recyclerView;
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
mDatabase = FirebaseFirestore.getInstance();
recyclerView = findViewById(R.id.rv);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
if (mUser != null) {
fetch();
} else {
Intent intent = new Intent(Home.this, Login.class);
startActivity(intent);
finish();
}
}
private void fetch() {
Query query = mDatabase.collection("batches");
FirestoreRecyclerOptions<batches> options = new FirestoreRecyclerOptions.Builder<batches>()
.setQuery(query, new SnapshotParser<batches>() {
#NonNull
#Override
public matches parseSnapshot(#NonNull DocumentSnapshot snapshot) {
return new matches(
snapshot.getLong("slots"),
snapshot.getLong("joined")
);
}
}).build();
adapter = new FirestoreRecyclerAdapter<batches,BatchHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull BatchHolder holder, int position, #NonNull batches model) {
holder.progressBar.setProgress(model.getJoined().intValue()/model.getSlots().intValue()*100);
}
#NonNull
#Override
public BatchHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_items,viewGroup,false);
return new BatchHolder(view);
}
};
recyclerView.setAdapter(adapter);
}
public class BatchHolder extends RecyclerView.ViewHolder {
ProgressBar progressBar;
public BatchHolder(#NonNull View itemView) {
super(itemView);
progressBar = itemView.findViewById(R.id.progressBar);
}
}
and in batches.class :
public class batches {
private Long slots, joined;
public matches(Long slots, Long joined) {
this.slots = slots;
this.joined = joined;
}
public Long getSlots() {
return slots;
}
public void setSlots(Long slots) {
this.slots = slots;
}
public Long getJoined() {
return joined;
}
public void setJoined(Long joined) {
this.joined = joined;
}
but when i run the app it says the following error :
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setProgress(int)' on a null object reference
at app.Home$2.onBindViewHolder(Home.java:109)
at app.Home$2.onBindViewHolder(Home.java:100)
at com.firebase.ui.firestore.FirestoreRecyclerAdapter.onBindViewHolder(FirestoreRecyclerAdapter.java:125)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752).... so on

How to delete specific image from recyclerview and also from Firebase storage?

I have created a RecyclerView and there are images and using button I can
delete the image from the RecyclerView but it again appears because it is not deleted from firebase storage and database. I need to delete it from storage and database as well.
I have provided with most of the code so you can look into it.
Thanks!!
//imageAdapter.java Code
public class ImageAdapter extends `enter code
RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context mContext;
private List<Upload> mUploads;
public ImageAdapter(Context context, List<Upload> uploads) {
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item,
parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(final ImageViewHolder holder, final int
position) {
final Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Picasso.get()
.load(uploadCurrent.getImageUrl())
.placeholder(R.mipmap.ic_launcher)
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_view_name);
imageView = itemView.findViewById(R.id.image_view_upload);
}
}
}
//imageActivity.java code
public class ImagesActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
private ProgressBar mProgressCircle;
private FirebaseStorage mStorage;
private DatabaseReference mDatabaseRef;
private List<Upload> mUploads;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_images);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mProgressCircle = findViewById(R.id.progress_circle);
mUploads = new ArrayList<>();
mStorage=FirebaseStorage.getInstance();//image delete
mDatabaseRef =
FirebaseDatabase.getInstance().getReference("uploads");
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUploads.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren())
{
Upload upload = postSnapshot.getValue(Upload.class);
upload.setKey(postSnapshot.getKey());
mUploads.add(upload);
}
mAdapter = new ImageAdapter(ImagesActivity.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
mProgressCircle.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ImagesActivity.this,
databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mProgressCircle.setVisibility(View.INVISIBLE);
}
});
}
}
//Upload.java code
public class Upload {
private String mName;
private String mImageUrl;
private String mKey;
public Upload() {
//empty constructor needed
}
public Upload(String name, String imageUrl) {
if (name.trim().equals("")) {
name = "No Name";
}
mName = name;
mImageUrl = imageUrl;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getImageUrl() {
return mImageUrl;
}
public void setImageUrl(String imageUrl) {
mImageUrl = imageUrl;
}
//image delete
#Exclude
public String getKey(){
return mKey;
}
#Exclude
public void setKey(String key){
mKey=key;
}//end image delete
}
//MainAcitivity.java code
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;
private Button mButtonChooseImage;
private Button mButtonUpload;
private TextView mTextViewShowUploads;
private EditText mEditTextFileName;
private ImageView mImageView;
private ProgressBar mProgressBar;
private Button deleteButton;
private Uri mImageUri;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef;
private StorageTask mUploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButtonChooseImage = findViewById(R.id.button_choose_image);
mButtonUpload = findViewById(R.id.button_upload);
mTextViewShowUploads = findViewById(R.id.text_view_show_uploads);
mEditTextFileName = findViewById(R.id.edit_text_file_name);
mImageView = findViewById(R.id.image_view);
mProgressBar = findViewById(R.id.progress_bar);
deleteButton=findViewById(R.id.del_image);
mStorageRef = FirebaseStorage.getInstance().getReference("uploads");
mDatabaseRef =
FirebaseDatabase.getInstance().getReference("uploads");
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
mButtonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mUploadTask != null && mUploadTask.isInProgress()) {
Toast.makeText(MainActivity.this, "Upload in progress",
Toast.LENGTH_SHORT).show();
} else {
uploadFile();
}
}
});
mTextViewShowUploads.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openImagesActivity();
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
mImageUri = data.getData();
Picasso.get().load(mImageUri).into(mImageView);
}
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void uploadFile() {
if (mImageUri != null) {
StorageReference fileReference =
mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot
taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 500);
Task<Uri> urlTask =
taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
Toast.makeText(MainActivity.this, "Upload
successful", Toast.LENGTH_LONG).show();
Note: Having problem posting further code!!!

Exception when Intent Data to another Activity android.content.Context.getPackageName()

Hello guys iam trying to get Data to putExtra => Intent from an Adapter to another Activity but every time i try to get data from the Adapter to the Activity it Gives me this Exception that
java.lang.String android.content.Context.getPackageName()'
so i tried to Enter the Context class i found it too many Errors cant fix that till now
what makes me really Believe that the problem with the Context is that when i Tried to use TinyDB
it need to define the Object inside the Adapter
tinyDB = new TinyDB(mContext);
the program Crashed and Gives Me this Exception
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
W/System.err: at android.content.ComponentName.<init>(ComponentName.java:128)
at android.content.Intent.<init>(Intent.java:4910)
at com.team.plustegara.Views.Models.Adapters.EventsAdapter$1.onClick(EventsAdapter.java:83)
at android.view.View.performClick(View.java:5647)
at android.view.View$PerformClick.run(View.java:22465)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
W/System.err: at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6238)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
i tried to Fix that but still cant handle the Context problem
Here is my Adapter
public class EventsAdapter extends RecyclerView.Adapter<EventsAdapter.EventsHolder> {
public EventsAdapter(List<EventsModel> list, Context mContext) {
this.list = list;
this.mContext = mContext;
}
private List<EventsModel> list;
private Context mContext;
FirebaseAuth mAuth;
DatabaseReference dbRef;
#NonNull
#Override
public EventsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.events_row_item, parent, false);
EventsHolder holder = new EventsHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull final EventsHolder holder, int position) {
final EventsModel listy = list.get(position);
holder.eventTitle.setText(listy.getTitle());
holder.eventDate.setText(listy.getEventDate());
holder.eventCosts.setText("Event Costs " + listy.getCosts());
Picasso.get()
.load(listy.getEventImage())
.fit()
.centerCrop()
.placeholder(R.drawable.gradients_card)
.into(holder.eventImage);
holder.cardViewEvents.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(mContext, ShowActivityEvents.class);
intent.putExtra("EventImage", listy.getEventImage());
intent.putExtra("EventTitle", listy.getTitle());
intent.putExtra("EventDate", listy.getEventDate());
intent.putExtra("EventCosts", listy.getCosts());
intent.putExtra("EventDescription", listy.getDescription());
intent.putExtra("eventID", listy.getPostID());
mContext.startActivity(intent);
dbRef = FirebaseDatabase.getInstance().getReference("PlusTeam");
mAuth = FirebaseAuth.getInstance();
String userName = mAuth.getCurrentUser().getDisplayName();
String postID = listy.getPostID();
dbRef.child("Events").child(postID).child("Views").push().setValue(userName);
} catch (Exception e) {
e.printStackTrace();
}
}
});
String postID = listy.getPostID();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("PlusTeam");
databaseReference.child("Events").child(postID).child("Views").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
long ViewsCount = dataSnapshot.getChildrenCount();
holder.txtViews.setText(String.valueOf(ViewsCount));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toasty.error(mContext, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class EventsHolder extends RecyclerView.ViewHolder {
#BindView(R.id.EventImageCard)
ImageView eventImage;
#BindView(R.id.txtEventTitle)
TextView eventTitle;
#BindView(R.id.txtEventDate)
TextView eventDate;
#BindView(R.id.txtEventCosts)
TextView eventCosts;
#BindView(R.id.cardView_EventsCard)
CardView cardViewEvents;
#BindView(R.id.txtEventsViews) TextView txtViews;
public EventsHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
here is my Activity which receive the Extras from the Adapter
public class ShowActivityEvents extends AppCompatActivity {
DatabaseReference dbRef;
FirebaseAuth mAuth;
#Override
protected void onStart() {
super.onStart();
checkIfUserAlreadyAccepttheEvent();
}
private void checkIfUserAlreadyAccepttheEvent() {
final String postID = getIntent().getExtras().getString("eventID");
final String UserID = mAuth.getCurrentUser().getUid();
dbRef.child(postID).child("PeopleComing")
.addListenerForSingleValueEvent(new ValueEventListener() {
public static final String TAG = "ShowEvents";
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Log.e(TAG, "onChildAdded: " + dataSnapshot);
String peopleCount = String.valueOf(dataSnapshot.getChildrenCount());
txtPeopleComing.setText( peopleCount + " People Comming");
if (dataSnapshot.child(UserID).exists()) {
btnIamIn.setEnabled(false);
} else {
btnIamIn.setEnabled(true);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toasty.error(ShowActivityEvents.this, "Error code : " + 1, Toast.LENGTH_LONG).show();
}
});
}
#BindView(R.id.btnIamIn)
Button btnIamIn;
#BindView(R.id.txtPeopleComingCount)
TextView txtPeopleComing;
#BindView(R.id.imgEventPost)
ImageView imgEvent;
#BindView(R.id.txtEventTitle) TextView txtEventTitle;
#BindView(R.id.txtEventDescription) TextView txtEventDescription;
#BindView(R.id.txtEventCost) TextView txtEventCost;
#BindView(R.id.txtEventDate) TextView txtEventDate;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_events2);
ButterKnife.bind(this);
dbRef = FirebaseDatabase.getInstance().getReference("PlusTeam");
mAuth = FirebaseAuth.getInstance();
try {
loadDataFromAdapter();
} catch (Exception e) {
e.printStackTrace();
}
}
private void loadDataFromAdapter() {
String Image = getIntent().getExtras().getString("EventImage");
String Title = getIntent().getExtras().getString("EventTitle");
String Date = getIntent().getExtras().getString("EventDate");
String Costs = getIntent().getExtras().getString("EventCosts");
String Description = getIntent().getExtras().getString("EventDescription");
GlideApp.with(this)
.load(Image)
.fitCenter()
.into(imgEvent);
txtEventTitle.setText(Title);
txtEventDescription.setText(Description);
txtEventDate.setText(Date);
txtEventCost.setText(Costs);
}
#OnClick(R.id.btnIamIn) public void addPersonToEvent(){
String UserName = mAuth.getCurrentUser().getDisplayName();
String userID = mAuth.getCurrentUser().getUid();
String postID = getIntent().getExtras().getString("eventID");
dbRef.child(postID)
.child("PeopleComing").setValue(UserName);
btnIamIn.setEnabled(false);
}
}
Finally just wanted to say i searched for this kind of Problem in Google and inside questions in Stack but didn't worked
so any Suggestions
You should pass your context in adapter like in the example below
Activity
adapter = new EventsAdapter(myList,MainActivity.this);
Fragment
adapter = new EventsAdapter(myList,getActivity());
Or another way
#Override
public void onClick(View v) {
v.getContext().startActivity(v.getContext(), ShowActivityEvents.class);
}

Android Firebase java.lang.StackOverflowError: stack size 8MB error when user is uploading an image

Hello I'm trying to create a profile screen where the user can upload their own profile image and change the ImageView into something that they've uploaded. But upon using this Upload profile image for a user Firebase as a reference I encountered an error when I'm starting to upload the images to the database.
My Code
public class userMain extends Fragment {
private TextView userfirstName,usersecondName,userNumber,userGender,userEmail,userDate;
private Button btnChoose, btnUpload;
private ImageView imageView;
private Uri filePath;
private FirebaseStorage storage;
private StorageReference storageReference;
private final int PICK_IMAGE_REQUEST = 71;
public userMain() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_user_main, container, false);
btnUpload = (Button) view.findViewById(R.id.savePhoto);
imageView = (ImageView) view.findViewById(R.id.imageView3);
userfirstName = (TextView) view.findViewById(R.id.firstnametv);
usersecondName = (TextView) view.findViewById(R.id.secondnametv);
userNumber = (TextView) view.findViewById(R.id.numbertv);
userGender = (TextView) view.findViewById(R.id.gendertv);
userEmail = (TextView) view.findViewById(R.id.emailtv);
userDate = (TextView) view.findViewById(R.id.datetv);
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
String useruid=user.getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Accounts").child("Users").child(useruid);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseImage();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadImage();
}
});
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String firstname = dataSnapshot.child("first").getValue(String.class);
String secondname = dataSnapshot.child("second").getValue(String.class);
String number = dataSnapshot.child("number").getValue(String.class);
String gender = dataSnapshot.child("gender").getValue(String.class);
String email = dataSnapshot.child("email").getValue(String.class);
String date = dataSnapshot.child("date").getValue(String.class);
userfirstName.setText(firstname);
usersecondName.setText(secondname);
userNumber.setText(number);
userGender.setText(gender);
userEmail.setText(email);
userDate.setText(date);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return view;
}
private void uploadImage() {
if(filePath != null)
{
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(getContext(), "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getContext(), "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
String useruid=user.getUid();
final DatabaseReference img = FirebaseDatabase.getInstance().getReference().child("Accounts").child("Users").child(useruid);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null )
{
filePath = data.getData();
StorageReference filepath= storageReference.child("Images").child(filePath.getLastPathSegment());
filepath.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
img.child("image").setValue(downloadUrl);
}
});
}
}
}
Change this:
StorageReference filepath= storageReference.child("Images").child(filePath.getLastPathSegment());
filepath.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
img.child("image").setValue(downloadUrl);
}
to this:
StorageReference filepath= storageReference.child("Images").child(filePath.getLastPathSegment());
filepath.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String downloadUrl = taskSnapshot.getDownloadUrl().toString()
img.child("image").setValue(downloadUrl);
}
saving the downloadUrl as string in your firebase database

Categories