Every time the application is destroyed and opened again, by another mean every time the method "onStart" is called, every new item added two times.
And when I close it and open it again, every new item will be repeated three times , and so on...
Here is the code of the activity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
IntializeControllers();
if (getIntent().getExtras() != null && getIntent().getStringExtra("userID" ) != null&& getIntent().getStringExtra("userName") != null&& getIntent().getStringExtra("userImage") != null){
messageReceiverID = getIntent().getExtras().get("userID").toString();
if (messageReceiverID.equals(auth.getCurrentUser().getUid())){
Toast.makeText(this, "يرجى التأكد من إعدادات تسجيل الدخول", Toast.LENGTH_SHORT).show();
finish();
}
messageReceiverName = getIntent().getExtras().get("userName").toString();
messageReceiverImage = getIntent().getExtras().get("userImage").toString();
}
else {
Toast.makeText(this, "لا يوجد بيانات", Toast.LENGTH_SHORT).show();
finish();
}
DisplayLastSeen();
userName.setText(messageReceiverName);
Picasso.get().load(messageReceiverImage).placeholder(R.drawable.profile_image).into(userImage);
SendMessageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
MessageInputText.setText("");
}
});
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mCurrentPage++;
itemPos =0;
LoadMoreMessages();
}
});
sendFileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence options[] = new CharSequence[]
{
"Images",
"PDF Files",
"Ms Word Files"
};
AlertDialog.Builder builder = new AlertDialog.Builder(ChatActivity.this);
builder.setTitle("Select the File");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
if (i == 0){
checker ="image";
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Image"),438);
}if (i == 1){
checker ="pdf";
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select PDF File"),438);
}if (i == 2){
checker ="docx";
Intent intent = new Intent();
intent.setType("application/msword");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Ms Word File"),438);
}
}
});
builder.show();
}
});
seenListener =null;
}
#Override
protected void onStart() {
super.onStart();
LoadMessages();
callImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sheckSelfPermissionsAndCallUser();
}
});
Toast.makeText(this, "onStart", Toast.LENGTH_SHORT).show();
}
private void IntializeControllers() {
toolbar = findViewById(R.id.group_chat_toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE);
View actionBarView = layoutInflater.inflate(R.layout.custom_chat_bar, null);
actionBar.setCustomView(actionBarView);
}
auth = FirebaseAuth.getInstance();
messageSenderID = auth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
callImage = findViewById(R.id.custom_user_call);
userImage = findViewById(R.id.custom_profile_image);
userName = findViewById(R.id.custom_profile_name);
userLastSeen = findViewById(R.id.custom_user_last_seen);
SendMessageButton = findViewById(R.id.send_message_btn);
MessageInputText = findViewById(R.id.input_message);
recyclerView = findViewById(R.id.private_messages_list_of_users);
swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
sendFileButton = findViewById(R.id.send_files_btn);
progressDialog = new ProgressDialog(ChatActivity.this);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
Calendar calendar = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");
saveCurrentDate =currentDate.format(calendar.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("hh:mm a");
saveCurrentTime =currentTime.format(calendar.getTime());
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
sinchClient = Sinch.getSinchClientBuilder()
.context(this)
.applicationKey("b3ecda78-59b0-400e-91bb-53f14fc1efc1")
.applicationSecret("pi0eQwXOzEGP7Crsk8Zepw==")
.environmentHost("clientapi.sinch.com")
.userId(firebaseUser.getUid())
.build();
sinchClient.setSupportCalling(true);
sinchClient.startListeningOnActiveConnection();
sinchClient.start();
callImage.setVisibility(View.VISIBLE);
userLastSeen.setVisibility(View.VISIBLE);
sinchClient.getCallClient().addCallClientListener(new CallClientListener() {
#Override
public void onIncomingCall(CallClient callClient, final com.sinch.android.rtc.calling.Call calli) {
alertDialog = new AlertDialog.Builder(ChatActivity.this).create();
alertDialog.setTitle("وردتك مكالمة من قبل " + messageReceiverName);
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "رفض", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
call.hangup();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "قبول", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
call = calli;
call.answer();
call.addCallListener(new sinchCallListenr());
Toast.makeText(ChatActivity.this, "Calling is Start", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
}
});
apiService = Client.getClient("https://fcm.googleapis.com/").create(APIService.class);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 438 && resultCode == RESULT_OK && data != null && data.getData() != null){
progressDialog.setTitle("Sending File");
progressDialog.setMessage("please wait, we are sending that file...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
fileUri = data.getData();
if (!checker.equals("image")){
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Document Files");
final String messageSenderRef = "Messages/" + messageSenderID +"/" + messageReceiverID;
final String messageReceiverRef = "Messages/" + messageReceiverID + "/" +messageSenderID;
DatabaseReference userMessageKeyRef = RootRef.child("Messages")
.child(messageSenderID).child(messageReceiverID).push();
final String messagePushID =userMessageKeyRef.getKey();
final StorageReference filePath =storageReference.child(messagePushID +"."+checker);
filePath.putFile(fileUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
myUrl = downloadUrl;
notify = true;
Map messageTextBody = new HashMap();
messageTextBody.put("message",myUrl);
messageTextBody.put("name", Objects.requireNonNull(fileUri.getLastPathSegment()));
messageTextBody.put("type",checker);
messageTextBody.put("from",messageSenderID);
messageTextBody.put("to",messageReceiverID);
messageTextBody.put("seenMessage",false);
messageTextBody.put("messageID",messagePushID);
messageTextBody.put("time",saveCurrentTime);
messageTextBody.put("date",saveCurrentDate);
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(messageSenderRef
+"/" +messagePushID, messageTextBody);
messageBodyDetails.put(messageReceiverRef +"/" +messagePushID,
messageTextBody); RootRef.updateChildren(messageBodyDetails);
progressDialog.dismiss();
if (notify) {
//
sendNotification(messageReceiverID, GetNameUser(), myUrl, checker);
}
notify = false;
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(ChatActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double p = (100.0*taskSnapshot.getBytesTransferred())/taskSnapshot.getTotalByteCount();
progressDialog.setMessage((int) p +" % Uploading....");
}
});
}else if (checker.equals("image")){
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Image Files");
final String messageSenderRef = "Messages/" + messageSenderID +"/" + messageReceiverID;
final String messageReceiverRef = "Messages/" + messageReceiverID + "/" +messageSenderID;
DatabaseReference userMessageKeyRef = RootRef.child("Messages")
.child(messageSenderID).child(messageReceiverID).push();
final String messagePushID =userMessageKeyRef.getKey();
final StorageReference filePath =storageReference.child(messagePushID +".jpg");
uploadTask = filePath.putFile(fileUri);
uploadTask.continueWithTask(new Continuation() {
#Override
public Object then(#NonNull Task task){
if (!task.isSuccessful()){
Toast.makeText(ChatActivity.this, ""+task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>(){
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()){
Uri downloadUri = task.getResult();
myUrl = downloadUri.toString();
Map messageTextBody = new HashMap();
messageTextBody.put("message",myUrl);
messageTextBody.put("name",fileUri.getLastPathSegment());
messageTextBody.put("type",checker);
messageTextBody.put("from",messageSenderID);
messageTextBody.put("to",messageReceiverID);
messageTextBody.put("seenMessage",false);
messageTextBody.put("messageID",messagePushID);
messageTextBody.put("time",saveCurrentTime);
messageTextBody.put("date",saveCurrentDate);
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(messageSenderRef +"/" +messagePushID, messageTextBody);
messageBodyDetails.put(messageReceiverRef +"/" +messagePushID, messageTextBody);
RootRef.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
notify=true;
//messageAdapter.notifyDataSetChanged();
progressDialog.dismiss();
Toast.makeText(ChatActivity.this, "Message Sent Successfully", Toast.LENGTH_SHORT).show();
if (notify) {
sendNotification(messageReceiverID, GetNameUser(), myUrl, checker);
}
notify = false;
}else {
progressDialog.dismiss();
Toast.makeText(ChatActivity.this, "Error : "+task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}else {
Toast.makeText(this, "Nothing Selected, Error.", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
}
#Override
protected void onResume() {
Log.d("tester","onResume");
super.onResume();
//move recycler from here
messageAdapter =new MessageAdapter(messagesList,ChatActivity.this,messageReceiverImage);
recyclerView.setAdapter(messageAdapter);
ItemTouchHelper itemTouchHelper = new
ItemTouchHelper(new SwipeToDeleteCallback(messageAdapter));
itemTouchHelper.attachToRecyclerView(recyclerView);
recyclerView.smoothScrollToPosition(recyclerView.getAdapter().getItemCount());
seenMessage();
UpdateUserStatus("online");
DisplayLastSeen();
messageAdapter.notifyDataSetChanged();
// messagesListAdapter = new MessagesListAdapter(messagesList,messageReceiverImage);
// recyclerView.setAdapter(messagesListAdapter);
}
}
#Override
protected void onStop() {
super.onStop();
Log.d("tester","onStop");
FirebaseUser firebaseUser = auth.getCurrentUser();
if (firebaseUser != null){
UpdateUserStatus("offline");
RootRef.removeEventListener(seenListener);
RootRef.removeEventListener(listener);
}
}
#Override
protected void onDestroy() {
Log.d("tester","onDestroy");
super.onDestroy();
FirebaseUser firebaseUser = auth.getCurrentUser();
if (firebaseUser != null){
UpdateUserStatus("offline");
if (seenListener != null) {
RootRef.removeEventListener(seenListener);
}
}
}
}
I appreciate your help as I can't figure out the problem. Please note that a lot of functions have been removed for readability.
To resolve your issue, clear adap zter while loading new data, so duplicacy can be removed and update new data. This issue occur due to multiple call on Android Lifecycle method in various state like
onResume - Called multiple times. So avoid initalization in here
onStart - is called whenever application is come from background to foreground or visible state
// When adding new data
adapter.addAll(data);
adapter.notifyDataSetChanged();
// when updating data again in onResume or onStart
adapter.clear();// clear old data from list
adapter.addAll(data);
adapter.notifyDataSetChanged();
//Inside adapter
//Adding item
void addAll(List<Data> data){
list.addAll(data);
}
//For clearing list
void clear(){
list.clear();
// To update list automatically add below line
//notifyDataSetChanged();
}
Related
I made a simple app that has a button and an ImageView. When I click on the button, an image (from drawable) gets displayed on the ImageView. I have also written the code for uploading the image on Firebase, but the exception message of onAddFailureListener gives the message User does not have permission to access this object. What should I do?
This answer does not help me.
User does not have permission to access this object . Firebase storage android
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 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);
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);
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_LONG).show();
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
/*
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);
*/
Objects.requireNonNull(taskSnapshot.getMetadata()).getReference().getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
assert uploadId != null;
mDatabaseRef.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, 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());
mProgressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
}
}
private void openImagesActivity() {
Intent intent = new Intent(this, ImagesActivity.class);
startActivity(intent);
}
}
Realtime Database
{
"rules": {
".read": true,
".write": true
}
}
Storage
rules_version = '2';
service firebase.storage {
match /b/savephoto-a1cc3.appspot.com/o {
match /{allPaths=**} {
// Allow access by all users
allow read, write;
}
}
}
Since I have seen a comment in your code that sounds like this "Allow access by all users", then I recommend you use the following rules:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
For testing purposes, it will work but I encourage you to change them when you'll launch the application.
My code above is to insert user registration data into the firebase database. but when I build the app and try to insert some demo data into the database to perform a user registration none of them is being inserted to the firebase. can anyone check my code and find out anything that I have done wrong?
public class CreateProfile extends AppCompatActivity {
EditText etName,etBio,etProfession,etEmail,etWeb;
Button button;
ImageView imageView;
ProgressBar progressBar;
Uri imageUri;
UploadTask uploadTask;
StorageReference storageReference;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference databaseReference;
FirebaseFirestore db = FirebaseFirestore.getInstance() ;
DocumentReference documentReference;
private static final int PICK_IMAGE=1;
All_User_Member member;
String currentUserId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_profile);
member = new All_User_Member();
imageView = findViewById(R.id.iv_cp);
etBio = findViewById(R.id.et_bio_cp);
etEmail = findViewById(R.id.et_email_cp);
etName = findViewById(R.id.et_name_cp);
etProfession = findViewById(R.id.et_profession_cp);
etWeb = findViewById(R.id.et_web_cp);
button = findViewById(R.id.btn_cp);
progressBar = findViewById(R.id.progressbar_cp);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
currentUserId = user.getUid();
//reference
documentReference = db.collection("user").document(currentUserId);
storageReference = FirebaseStorage.getInstance().getReference("Profile images");
databaseReference = database.getReference("All users");
//button click
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadData();
}
});
//ProfileImageSelect
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"select image"),PICK_IMAGE);
}
});
}
//LoadingProfileImage
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode==PICK_IMAGE || resultCode== RESULT_OK || data != null || data.getData() !=null){
imageUri = data.getData();
Picasso.get().load(imageUri).into(imageView);
}
}catch (Exception e){
Toast.makeText(this, "Error"+e, Toast.LENGTH_SHORT).show();
}
}
private String getFileExt(Uri uri){
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType((contentResolver.getType(uri)));
}
private void uploadData() {
String name = etName.getText().toString();
String bio = etBio.getText().toString();
String web = etWeb.getText().toString();
String prof = etProfession.getText().toString();
String mail = etEmail.getText().toString();
if(TextUtils.isEmpty(name) || TextUtils.isEmpty(bio) || TextUtils.isEmpty(web) || TextUtils.isEmpty(prof) ||
TextUtils.isEmpty(mail) || imageUri != null){
progressBar.setVisibility(View.VISIBLE);
final StorageReference reference = storageReference.child(System.currentTimeMillis()+ "."+getFileExt(imageUri));
uploadTask = reference.putFile(imageUri);
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()){
throw task.getException();
}
return reference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()){
Uri downloadUri = task.getResult();
Map<String, String> profile = new HashMap<>();
profile.put("name", name);
profile.put("prof", prof);
profile.put("url", downloadUri.toString());
profile.put("bio", bio);
profile.put("mail", mail);
profile.put("web", web);
profile.put("privacy", "Public");
member.setName(name);
member.setProf(prof);
member.setUid(currentUserId);
member.setUrl(downloadUri.toString());
databaseReference.child(currentUserId).setValue(member);
documentReference.set(profile).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(CreateProfile.this, "Profile Created", Toast.LENGTH_SHORT).show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(CreateProfile.this,Fragment1.class);
startActivity(intent);
}
},2000);
}
});
}
}
});
}else {
Toast.makeText(this, "Please fill all fields", Toast.LENGTH_SHORT).show();
}
}
}
These are the errors getting in the android studio:
After I save my profile image it says image updated but when I open settings again it does not show any image; instead, a white screen. It shows the status though.
Here is my code:
private Button UpdateAccountSettings;
private EditText userName, userStatus;
private CircleImageView userProfileImage;
private String currentUserID;
private FirebaseAuth mAuth;
private DatabaseReference Rootref;
private static final int GalleryPick = 1;
private StorageReference UserProfileImagesRef;
private ProgressDialog loadingBar;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
Rootref = FirebaseDatabase.getInstance().getReference();
UserProfileImagesRef= FirebaseStorage.getInstance().getReference().child("Profile Images");
InitializeFields();
userName.setVisibility(View.INVISIBLE);
UpdateAccountSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
UpdateSettings();
}
});
RetrieveUserInfo();
userProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,GalleryPick);
}
});
}
private void InitializeFields() {
UpdateAccountSettings = (Button) findViewById(R.id.update_settings_button);
userName = (EditText) findViewById(R.id.set_user_name);
userStatus = (EditText) findViewById(R.id.set_profile_status );
userProfileImage= (CircleImageView) findViewById(R.id.set_profile_image );
loadingBar = new ProgressDialog(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode== GalleryPick && resultCode== RESULT_OK && data!= null)
{
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK)
{
loadingBar.setTitle("set Profile Image");
loadingBar.setMessage("Please wait, your profile image is updating...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImagesRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful())
{
Toast.makeText(SettingsActivity.this," Profile Image Uploded succesfully...", Toast.LENGTH_SHORT).show();
final String downloadedUrl = task.getResult().getStorage().getDownloadUrl().toString();
Rootref.child("Users").child(currentUserID).child("image")
.setValue(downloadedUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
Toast.makeText(SettingsActivity.this,"Image saved in database Successfully...", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else
{
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this,"", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
else
{
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this,"Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
}
private void UpdateSettings() {
String setUserName = userName.getText().toString();
String setStatus = userStatus.getText().toString();
if(TextUtils.isEmpty(setUserName)){
Toast.makeText(this,"Please write your username first..", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(setStatus)){
Toast.makeText(this,"Please write your Status first..", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, String> profileMap = new HashMap<>();
profileMap.put("uid", currentUserID);
profileMap.put("name", setUserName);
profileMap.put("Status", setStatus);
Rootref.child("Users").child(currentUserID).setValue( profileMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(SettingsActivity.this, "Profile Updated Succesfully...", Toast.LENGTH_SHORT).show();
}
else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void RetrieveUserInfo()
{
Rootref.child("Users").child(currentUserID)
.addValueEventListener(new ValueEventListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") ) &&(dataSnapshot.hasChild("image")))
{
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrievesStatus = dataSnapshot.child("Status").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrievesStatus);
Picasso.get().load(retrieveProfileImage).into(userProfileImage);
}
else if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name")))
{
String retrieveUserName = Objects.requireNonNull(dataSnapshot.child("name").getValue()).toString();
String retrievesStatus = Objects.requireNonNull(dataSnapshot.child("Status").getValue()).toString();
userName.setText(retrieveUserName);
userStatus.setText(retrievesStatus);
}
else{
userName.setVisibility(View.VISIBLE);
Toast.makeText(SettingsActivity.this, "Please set & update your profile information...", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(SettingsActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
My logcat does not show any error, please help me.
I am trying to take inputs from one user and send the same data to another user. I am not sure what to put as an argument in child so that it refers to the same data and I can retrieve and show the data to another user for approval. I am able to send the image but for the data fields like visitor,mobile and flat not sure what to do.
My code is as follows.
Data entry File Code
public class Main4Activity extends AppCompatActivity {
private static final int PERMISSION_CODE = 1000;
private static final int IMAGE_CAPTURE_CODE = 1001;
Button btn;
ImageView imageView;
static Uri image_uri;
ImageView mImageView;
TextView mCaptureBtn;
Button uploadbtn;
static String downloadurl;
public static String Dvisitor;
public static String Dmobile;
static DatabaseReference reff;
//for upload
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 71;
FirebaseStorage storage;
StorageReference storageReference;
//for upload
static String URL;
//Data store of Visitor
static EditText visitor;
static EditText mbnumber;
EditText bnmbr;
static EditText fnmbr;
EditText emal;
EditText pswrd;
HashMap<String,Object> map = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
//for upload
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
//for upload
mImageView = (ImageView) findViewById(R.id.imageView2);
mCaptureBtn = (TextView) findViewById(R.id.textView4);
//Data for Visitor
visitor = (EditText) findViewById(R.id.vname);
mbnumber = (EditText) findViewById(R.id.mnumber);
bnmbr = (EditText) findViewById(R.id.blknmbr);
fnmbr = (EditText) findViewById(R.id.fltnmbr);
emal = (EditText) findViewById(R.id.emailId);
pswrd = (EditText) findViewById(R.id.passwordfield2);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
upload();
FirebaseDatabase.getInstance().getReference().child("Image").push().setValue(map)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
map.put("visitor",visitor.getText().toString());
map.put("mobile",mbnumber.getText().toString());
map.put("block",bnmbr.getText().toString());
map.put("flat",fnmbr.getText().toString());
map.put("email",emal.getText().toString());
map.put("password",pswrd.getText().toString());
Toast.makeText(Main4Activity.this, "Successful data registration", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Main4Activity.this, "Failed data registration", Toast.LENGTH_SHORT).show();
}
});
}
});
//Camera functionality click and upload starts
mCaptureBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
String[] permission = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permission, PERMISSION_CODE);
} else {
openCamera();
}
} else {
openCamera();
}
}
});
imageView = (ImageView) findViewById(R.id.imageView);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main4Activity.this, MainActivity.class);
startActivity(intent);
}
});
}
private void openCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera");
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE);
{
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_CODE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
mImageView.setImageURI(image_uri);
}
}
private void upload(){
if(image_uri != null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
final StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(image_uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Main4Activity.this, "Uploaded", Toast.LENGTH_SHORT).show();
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
DatabaseReference imagestore = FirebaseDatabase.getInstance().getReference().child("Image").push();
//HashMap<String, String> hasmap = new HashMap<>();
URL = uri.toString();
map.put("imgurl",URL);
//map.put("imageurl", String.valueOf(uri));
imagestore.setValue(map).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Intent intent= new Intent(Main4Activity.this,Main5Activity.class);
startActivity(intent);
}
});
//This is your image url do whatever you want with it.
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Main4Activity.this, "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 + "%");
}
});
}
}
}
//Camera functionality click and upload starts
Code for another user to Approve
public class Main5Activity extends AppCompatActivity {
Button btnAllow, btnProhibit;
private String Dvisitor;
private String Dmobile;
private String Dflat;
DatabaseReference reff;
ImageView img;
private DatabaseReference Post;
static TextView textView;
String roadies;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
btnAllow = (Button) findViewById(R.id.button);
btnProhibit = (Button) findViewById(R.id.button2);
textView = (TextView) findViewById(R.id.textView5);
img = (ImageView) findViewById(R.id.imageView3);
imageshow();
init();
readonetime();
}
private void readonetime() {
Query query = Post.orderByKey().limitToLast(1);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot child: dataSnapshot.getChildren()) {
String post = dataSnapshot.child("visitor").getValue(String.class);
String post1 = dataSnapshot.child("mobile").getValue(String.class);
String post2 = dataSnapshot.child("flat").getValue(String.class);
textView.setText("Mr. "+post+"with mobile number: " + post1+"wants to visit your flat: " + post2);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void init() {
Post = FirebaseDatabase.getInstance().getReference().child("Image");
}
private void imageshow() {
reff = FirebaseDatabase.getInstance().getReference().child("Image");
reff.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Picasso.get().load(Main4Activity.URL).fit().into(img);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Main5Activity.this, "OoooooLalalala", Toast.LENGTH_SHORT).show();
}
});
btnAllow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main5Activity.this, Main8Activity.class);
startActivity(intent);
}
});
btnProhibit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main5Activity.this, Main9Activity.class);
startActivity(intent);
}
});
}
}
In your Main5Activity, I think:
This:
for(DataSnapshot child: dataSnapshot.getChildren()) {
String post = dataSnapshot.child("visitor").getValue(String.class);
String post1 = dataSnapshot.child("mobile").getValue(String.class);
String post2 = dataSnapshot.child("flat").getValue(String.class);
textView.setText("Mr. "+post+"with mobile number: " + post1+"wants to visit your flat: " + post2);
}
Must be like this:
for(DataSnapshot ds: dataSnapshot.getChildren()) {
String post = ds.child("visitor").getValue(String.class);
String post1 = ds.child("mobile").getValue(String.class);
String post2 = ds.child("flat").getValue(String.class);
textView.setText("Mr. "+post+"with mobile number: " + post1+"wants to visit your flat: " + post2);
}
I'm trying to pass an intent from adapter and get it in my activity.
Whenever I did this it went to the else condition.
It doesn't get the value and I don't no why. When I try the same code in any other activity it worked perfectly, but in this activity it always gives a null value in intent.
I know there are so many answers to how to get and pass intent, but in my case it doesn't work in one activity and I don't know why.
My Adapter class:
holder.getSurvey.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,AuthorMainScreen.class);
intent.putExtra("work", "getting");
context.startActivity(intent);
}
My AuthorMainScreen Activity:
public class AuthorMainScreen extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
Button newSurveyBtn, surveyWithRef, surveyResult;
ArrayList<JSONObject> jsonObjects = new ArrayList<JSONObject>();
public static TextView textView;
DatabaseReference databaseReference, surveyReference;
String referenceNo, loggedInUserId;
AlertDialog dialog;
ProgressDialog progressDialog;
DrawerLayout drawerLayout;
NavigationView navigationView;
LinearLayout linearLayout;
FirebaseAuth firebaseAuth;
TextView headerEmailView, rateOk;
Button headerLogout;
EditText reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_author_navigation);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Processing your request...");
viewDeclaration();
clickFunctionalities();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
//drawerLayout.addDrawerListener(actionBarDrawerToggle);
navigationView.setNavigationItemSelectedListener(this);
}
private void clickFunctionalities() {
newSurveyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
surveyTitleDialog();
}
});
surveyWithRef.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
referenceDialog();
rateOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
referenceNo = reference.getText().toString().trim();
if (!referenceNo.isEmpty()) {
progressDialog.show();
getSurvey();
dialog.dismiss();
} else {
progressDialog.dismiss();
reference.setError("Reference # is required");
}
}
});
}
});
surveyResult.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
referenceDialog();
rateOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
referenceNo = reference.getText().toString().trim();
if (!referenceNo.isEmpty()) {
progressDialog.show();
getSurveyResultFile();
dialog.dismiss();
} else {
progressDialog.dismiss();
reference.setError("Reference # is required");
}
}
});
}
});
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
drawerLayout.openDrawer(GravityCompat.START);
}
}
});
headerLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(AuthorMainScreen.this, LoginSignupActivity.class);
startActivity(intent);
finish();
}
});
}
private void surveyTitleDialog() {
final AlertDialog.Builder textBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View view = inflater.inflate(R.layout.survey_name_dialog, null);
final EditText surveyName = view.findViewById(R.id.edt_set_survey_name);
TextView ok = view.findViewById(R.id.survey_name_btn);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String surveyTitleName = surveyName.getText().toString().trim();
if (!surveyTitleName.equals("")) {
dialog.dismiss();
Intent intent = new Intent(AuthorMainScreen.this, MakeSurvey.class);
intent.putExtra("surveyname", surveyTitleName);
Toast.makeText(AuthorMainScreen.this, surveyTitleName, Toast.LENGTH_SHORT).show();
startActivity(intent);
} else {
surveyName.setError("Title is Required");
}
}
});
TextView cancelBtn = view.findViewById(R.id.dismiss_dialog);
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
textBuilder.setView(view);
dialog = textBuilder.create();
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
Window window = dialog.getWindow();
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(false);
}
private void getSurvey() {
surveyReference = FirebaseDatabase.getInstance().getReference().child(Constants.content).child(Constants.survey).child(referenceNo);
surveyReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
System.out.println(dataSnapshot);
if (dataSnapshot.hasChildren()) {
progressDialog.dismiss();
Intent intent = new Intent(getApplicationContext(), GetSurveys.class);
intent.putExtra(Constants.ref_no, referenceNo);
startActivity(intent);
} else {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Reference number is not valid !!!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Something went wrong!!!", Toast.LENGTH_SHORT).show();
}
});
}
public void getSurveyResultFile() {
databaseReference = FirebaseDatabase.getInstance().getReference().child(Constants.content).child(Constants.Answers).child(loggedInUserId).child(referenceNo);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
progressDialog.dismiss();
JSONArray dataSnapshotArray = new JSONArray();
JSONArray dataSnapshotChildrenArray;
JSONObject dataSnapshotChildrenAnswer;
JSONArray dataSnapshotChildrenAnswerValues;
for (DataSnapshot ds : dataSnapshot.getChildren()) {
System.out.println("sdsd" + ds);
dataSnapshotChildrenArray = new JSONArray();
ArrayList<Object> list = (ArrayList<Object>) ds.getValue();
for (int i = 0; i < list.size(); i++) {
HashMap<String, Object> map = (HashMap<String, Object>) list.get(i);
Iterator<Map.Entry<String, Object>> finalIterator = map.entrySet().iterator();
dataSnapshotChildrenAnswer = new JSONObject();
while (finalIterator.hasNext()) {
Map.Entry<String, Object> entry = finalIterator.next();
Object value = entry.getValue();
String key = entry.getKey();
try {
dataSnapshotChildrenAnswer.put(key, value);
if (value instanceof ArrayList) {
dataSnapshotChildrenAnswerValues = new JSONArray();
ArrayList<String> answers = (ArrayList<String>) value;
for (int j = 0; j < answers.size(); j++) {
dataSnapshotChildrenAnswerValues.put(answers.get(j));
}
dataSnapshotChildrenAnswer.put(key, dataSnapshotChildrenAnswerValues);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
dataSnapshotChildrenArray.put(dataSnapshotChildrenAnswer);
}
dataSnapshotArray.put(dataSnapshotChildrenArray);
System.out.println("jso " + dataSnapshotArray);
}
try {
saveCsv(dataSnapshotArray);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(AuthorMainScreen.this, "Sorry!!user or survey not found.", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void saveCsv(JSONArray outerArray) throws IOException, JSONException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
String fileName = referenceNo + " Result";
String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/test/";
File dir = new File(rootPath);
if (!dir.exists()) {
dir.mkdir();
}
File file = null;
file = new File(rootPath, fileName);
if (!file.exists()) {
progressDialog.dismiss();
file.createNewFile();
}
if (file.exists()) {
progressDialog.dismiss();
CSVWriter writer = new CSVWriter(new FileWriter(file), ',');
for (int i = 0; i < outerArray.length(); i++) {
JSONArray innerJsonArray = (JSONArray) outerArray.getJSONArray(i);
for (int k = 0; k < innerJsonArray.length(); k++) {
String[][] arrayOfArrays = new String[innerJsonArray.length()][];
JSONObject innerJsonObject = (JSONObject) innerJsonArray.getJSONObject(k);
String[] stringArray1 = new String[innerJsonObject.length()];
//stringArray1[0]= (String) innerJsonObject.getString("type");
stringArray1[1] = "Questions";
stringArray1[2] = "Answers";
stringArray1[1] = (String) innerJsonObject.getString("title");
stringArray1[2] = "";
JSONArray jsonArray = (JSONArray) innerJsonObject.getJSONArray("answer");
for (int j = 0; j < jsonArray.length(); j++) {
stringArray1[2] += jsonArray.get(j).toString();
stringArray1[2] += ",";
}
arrayOfArrays[k] = stringArray1;
writer.writeNext(arrayOfArrays[k]);
System.out.println("aa " + Arrays.toString(arrayOfArrays[k]));
}
}
writer.close();
Toast.makeText(this, fileName + " is been saved at " + rootPath, Toast.LENGTH_LONG).show();
}
}
public void referenceDialog() {
final AlertDialog.Builder rateBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View view = inflater.inflate(R.layout.survey_refno_dialog, null);
reference = view.findViewById(R.id.edt_survey_ref_no);
rateOk = view.findViewById(R.id.ref_btnOk);
TextView rateCancel = view.findViewById(R.id.ref_btnCancel);
rateBuilder.setView(view);
rateCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog = rateBuilder.create();
dialog.show();
Window rateWindow = dialog.getWindow();
rateWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(false);
}
private void viewDeclaration() {
newSurveyBtn = findViewById(R.id.new_surveys_button);
surveyWithRef = findViewById(R.id.get_survey_button);
surveyResult = findViewById(R.id.analyze_survey);
linearLayout = findViewById(R.id.hamburg_icon_layout);
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.navigation_view);
View view = navigationView.getHeaderView(0);
headerEmailView = view.findViewById(R.id.header_email);
headerLogout = findViewById(R.id.nav_logout);
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser() != null) {
String userEmail = firebaseAuth.getCurrentUser().getEmail();
headerEmailView.setText(userEmail);
}
if (firebaseAuth.getCurrentUser() != null && firebaseAuth.getCurrentUser().getUid() != null) {
loggedInUserId = firebaseAuth.getCurrentUser().getUid();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.menu_share:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "DataPro");
intent.putExtra(Intent.EXTRA_TEXT, Constants.shareMessage);
startActivity(Intent.createChooser(intent, "Share Via"));
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.menu_survey_count:
startActivity(new Intent(getApplicationContext(), UserAllSurveys.class));
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.menu_new_instruments:
startActivity(new Intent(getApplicationContext(), CreateInstrument.class));
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.menu_about_us:
Toast.makeText(getApplicationContext(), "About us", Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawer(GravityCompat.START);
break;
}
return true;
}
#Override
protected void onStart() {
super.onStart();
Intent intent = getIntent();
/* if (intent.hasExtra("work") ) {
String k = getIntent().getStringExtra("work");
Toast.makeText(this, k, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "eroor", Toast.LENGTH_SHORT).show();
} */
Bundle bundle = getIntent().getExtras();
if (bundle != null ) {
String k = bundle.getString("work");
Toast.makeText(this, k, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
Try like this
Bundle bundle = getIntent().getExtras();
if (bundle != null ) {
String k = bundle.getString("work");
Toast.makeText(this, k, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "error" , Toast.LENGTH_SHORT).show();
}
Do you have another class with the same class name, but different package name?
Because it seems like there is no extra parameter present in your receiver activity (AuthorMainScreen). Sometimes mistakes like this can take more time than any other logical mistake. Or you can try to call it onCreate() by commenting the rest of the code. Just check this.