It is an weird issue of firebase. I am posting data to firebase and sometimes it posted at the same time and some time it is not posting data on firebase. It is really weird and I am unable to understand why this is happening.
When I running app from android studio it posting data at the same time when i posting in app but after some time it behaves weird I am unable to post data.
package com.example.hp.heartful;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
public class NewsPost extends AppCompatActivity {
private ImageButton userImage;
private EditText title,userDesc;
private Button submitbtn;
private DatabaseReference mdatabase;
private Uri imageUri=null;
private ProgressDialog progress;
private StorageReference newsPhotos;
private FirebaseStorage mstorage;
private final static int GALLERY_REQUEST=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_post);
// FirebaseDatabase.getInstance().setPersistenceEnabled(true);
mstorage=FirebaseStorage.getInstance();
mdatabase= FirebaseDatabase.getInstance().getReference().child("News");
newsPhotos=mstorage.getReference().child("NewsImages");
submitbtn=(Button)findViewById(R.id.submit_button);
title=(EditText)findViewById(R.id.title);
userDesc=(EditText)findViewById(R.id.user_des);
progress=new ProgressDialog(this);
userImage=(ImageButton)findViewById(R.id.user_image);
userImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent gallery=new Intent(Intent.ACTION_GET_CONTENT);
gallery.setType("image/jpeg");
gallery.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(gallery, "Complete action using"),GALLERY_REQUEST);
}
});
submitbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progress.setMessage("News Posting, please wait...");
userPost();
}
});
}
private void userPost(){
final String postTitle=title.getText().toString();
final String postDes= userDesc.getText().toString();
if (!TextUtils.isEmpty(postTitle)&&!TextUtils.isEmpty(postDes)&&imageUri!=null){
progress.show();
StorageReference filePath=newsPhotos.child(imageUri.getLastPathSegment());
filePath.putFile(imageUri).addOnSuccessListener(this,new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
#SuppressWarnings("VisibleForTests")
Uri downloadUrl = taskSnapshot.getDownloadUrl();
DatabaseReference newPost=mdatabase.push();
newPost.child("Title").setValue(postTitle);
newPost.child("Description").setValue(postDes);
newPost.child("Image").setValue(downloadUrl.toString());
progress.dismiss();
startActivity(new Intent(NewsPost.this,FragmentTwo.class));
}
});
}
else{
Toast.makeText(NewsPost.this,"Please fill all the blanks",Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==GALLERY_REQUEST&&resultCode==RESULT_OK){
imageUri=data.getData();
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
imageUri=resultUri;
userImage.setImageURI(imageUri);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
Toast.makeText(NewsPost.this, (CharSequence) error,Toast.LENGTH_LONG).show();
}
}
}
}
And this is newpost activity
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context="com.example.hp.heartful.NewsPost">
<ImageButton
android:layout_width="wrap_content"
android:id="#+id/user_image"
android:layout_margin="16dp"
android:layout_height="wrap_content"
android:src="#mipmap/add_btn"/>
<EditText
android:layout_width="match_parent"
android:layout_height="40dp"
android:hint="Title..."
android:inputType="textMultiLine"
android:paddingLeft="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:background="#drawable/text_field_design"
android:id="#+id/title"
android:layout_marginBottom="16dp"
android:layout_below="#+id/user_image"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="8dp"
android:hint="Descriptions..."
android:inputType="textMultiLine"
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp"
android:paddingLeft="16dp"
android:background="#drawable/text_field_design"
android:id="#+id/user_des"
android:layout_below="#+id/editText"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<android.support.v7.widget.AppCompatButton
android:layout_width="match_parent"
android:text="Submit"
android:textColor="#FFF"
android:textSize="24dp"
android:layout_height="wrap_content"
android:background="#drawable/custom_button1"
android:id="#+id/submit_button"
android:layout_marginTop="16dp"
android:layout_centerHorizontal="true" />
</LinearLayout>
</ScrollView>
Related
When I jump from MainActivity to AdminLog it works when adminLog.java contains the code as shown below. I have also searched for solution Like enabling noAction bar but it also doen't work. Not only for login code but it is shows same issue when I try to retrieve data from my firebase database.
package com.example.roc;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class adminLog extends AppCompatActivity {
EditText txtEmail, txtPassword;
ProgressBar progressBar;
Button btnSignin;
private FirebaseAuth mAuth;
private Button mgo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_log);
mgo=(Button)findViewById(R.id.adminLoginBtn);
mgo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(adminLog.this,adminWorking.class));
}
});
}
}
But it stops Working when I add login code in adminLog.java file which is also shown below.
package com.example.roc;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class adminLog extends AppCompatActivity {
EditText txtEmail, txtPassword;
ProgressBar progressBar;
Button btnSignin;
private FirebaseAuth mAuth;
private Button mgo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_log);
mAuth = FirebaseAuth.getInstance();
initializeUI();
btnSignin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginUserAccount();
}
});
}
private void loginUserAccount() {
progressBar.setVisibility(View.VISIBLE);
String email, password;
email = txtEmail.getText().toString();
password = txtPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Please enter email...", Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Please enter password!", Toast.LENGTH_LONG).show();
return;
}
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Login successful!", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
Intent intent = new Intent(adminLog.this, adminWorking.class);
startActivity(intent);
}
else {
Toast.makeText(getApplicationContext(), "Login failed! Please try again later", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
private void initializeUI() {
txtEmail= findViewById(R.id.adminETxt);
txtPassword = findViewById(R.id.adminPTxt);
btnSignin = findViewById(R.id.adminLoginBtn);
progressBar = findViewById(R.id.progressBar);
}
}
adminlog.xml file code is also given below.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".adminLog">
<Button
android:id="#+id/adminLoginBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="132dp"
android:text="Login"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="#+id/adminPTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/customerLoginBtn"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="96dp"
android:hint="Enter your password"
app:layout_constraintBottom_toTopOf="#+id/adminLoginBtn"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="#+id/adminETxt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginTop="332dp"
android:hint="Entere Your E-Mail"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="133dp"
android:layout_height="119dp"
android:layout_marginStart="139dp"
android:layout_marginLeft="139dp"
android:layout_marginTop="164dp"
android:layout_marginEnd="139dp"
android:layout_marginRight="139dp"
android:layout_marginBottom="448dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:visibility="gone"/>
</android.support.constraint.ConstraintLayout>
What should I do to get rid of this problem.
I have created the CreateEvent.java module to upload the data to firebase. But how to retrieve the data and show in the Cardlist? For example show in the xml file below. And also if there was more than 1 data in firebase, how to show in with multiple cardlist that I have created in the xml file?
CreateEvent.java
package com.example.edward.eventmanagementsystem.ManageEvent;
import android.Manifest;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.edward.eventmanagementsystem.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import static android.widget.Toast.LENGTH_SHORT;
public class CreateEvent extends Activity {
private static final String TAG = "activity_create_event";
private Uri filePath;
private TextView mDisplayDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;
private DatabaseReference mDatabaseReference;
private Button mRegisterButton;
EditText mEventNameText, mContactNumText, mEventLocationText;
TextView mEventDate;
RadioGroup mEventType;
FirebaseStorage storage;
StorageReference storageRef,imageRef;
ProgressDialog progressDialog;
UploadTask uploadTask;
Uri uriImage = Uri.parse("com.example.edward.eventmanagementsystem.ManageEvent/"+ R.drawable.ic_launcher_background);
public static final int PICK_IMAGE = 1;
ImageView mimageToUpload;
#Override
protected void onCreate(Bundle savedInstanceState) {
FirebaseDatabase firebaseDatabase;
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("ListEventInformation").push();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_event);
mRegisterButton = (Button)findViewById(R.id.btnRegisterEvent);
storage = FirebaseStorage.getInstance();
storageRef = storage.getReference();
mDisplayDate = (TextView) findViewById(R.id.RegisterEventStartDate);
mDisplayDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(
CreateEvent.this,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
mDateSetListener,
year, month, day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
month = month + 1;
Log.d(TAG, "onDateSet: date: mm/dd/yyyy: " + month + "/" + day + "/" + year);
String date = month + "/" + day + "/" + year;
mDisplayDate.setText(date);
}
};
//perform action upload image
mimageToUpload = (ImageView) findViewById(R.id.imageToUpload);
//insert data to database
mEventNameText = (EditText) findViewById(R.id.RegisterEventName);
mContactNumText = (EditText) findViewById(R.id.RegisterContactNumber);
mEventDate = (TextView) findViewById(R.id.RegisterEventStartDate);
mEventType = (RadioGroup) findViewById(R.id.RegisterEventRadiogroup);
mEventLocationText = (EditText) findViewById(R.id.RegisterEventLocation);
mimageToUpload = (ImageView) findViewById(R.id.imageToUpload);
mRegisterButton = (Button) findViewById(R.id.btnRegisterEvent);
mimageToUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(CreateEvent.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
selectPdf();
}
else {
ActivityCompat.requestPermissions(CreateEvent.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},9);
}
}
});
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedId = mEventType.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton)findViewById(selectedId);
final String name = mEventNameText.getText().toString().trim();
final String contact = mContactNumText.getText().toString().trim();
final String date = mEventDate.getText().toString().trim();
final String type = radioButton.getText().toString().trim();
final String location = mEventLocationText.getText().toString().trim();
if (TextUtils.isEmpty(name)) {
mEventNameText.setError("Enter First Name!");
return;
}
if (TextUtils.isEmpty(date)) {
mEventDate.setError("Enter Date!");
return;
}
if (TextUtils.isEmpty(type)) {
radioButton.setError("Enter Phone Number!");
return;
}
if(isValidPhone(contact)){
Toast.makeText(getApplicationContext(),"Phone number is valid",Toast.LENGTH_SHORT).show();
}else {
mContactNumText.setError("Phone number is not valid");
Toast.makeText(getApplicationContext(),"Phone number is not valid",Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(location)) {
mEventLocationText.setError("Enter Location!");
return;
}
Map userInfo = new HashMap();
userInfo.put("mEventNameText", name);
userInfo.put("mContactNumText", contact);
userInfo.put("mEventDate", date);
userInfo.put("radioButton", type);
userInfo.put("mEventLocationText", location);
mDatabaseReference.updateChildren(userInfo);
final String fileName = System.currentTimeMillis()+"";
if(uriImage != null) {
StorageReference storageReference = storage.getReference();
storageReference.child("profileImageUrl").child(fileName).putFile(uriImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String url = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
mDatabaseReference.child("profileImageUrl").setValue(url).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){ }
else{
Toast.makeText(getApplicationContext(),"File not Successfully Uploaded",LENGTH_SHORT).show(); }
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"File not Successfully Uploaded",LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}else{
}
Toast.makeText(getApplicationContext(),"New event created successfully!",LENGTH_SHORT).show();
Intent ManageEventMenu = new Intent(CreateEvent.this, com.example.edward.eventmanagementsystem.ManageEvent.ManageEventMenu.class);
startActivity(ManageEventMenu);
}
});
}
public boolean isValidPhone(CharSequence phone) {
boolean check=false;
if(!Pattern.matches("[a-zA-Z]+", phone))
{
if(phone.length() < 10 || phone.length() > 11)
{
check = false;
}
else
{
check = true;
}
}
else
{
check=false;
}
return check;
}
private void selectPdf() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
startActivityForResult(intent,86);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 86 && resultCode == RESULT_OK && data != null){
final Uri imageUri = data.getData();
uriImage = imageUri;
mimageToUpload.setImageURI(uriImage);
}
else {
Toast.makeText(getApplicationContext(),"Please select file", LENGTH_SHORT).show();
}
}
}
I would like to show the data in this way.
The sample of xml file I would like to display the data create from Firebase in upload from CreateEvent.java
activity_list_of_event.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/gradientwallpaper">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Events"
android:layout_marginLeft="10dp"
android:textStyle="bold"
android:layout_marginTop="20dp"
android:textSize="24dp"
android:textColor="#color/white"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Total Created Event"
android:layout_marginLeft="10dp"
android:textSize="16dp"
android:textColor="#color/white"
android:layout_marginTop="10dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="10dp"
android:layout_marginBottom="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Upcoming"
android:layout_marginLeft="10dp"
android:textSize="16dp"
android:textColor="#color/white"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Pass"
android:gravity="right"
android:layout_marginRight="10dp"
android:textSize="16dp"
android:textColor="#color/white"/>
</LinearLayout>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:padding="10dp"
android:weightSum="10">
<LinearLayout
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="4"
android:orientation="vertical">
<TextView
android:id="#+id/item_month"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Month" />/ android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
<TextView
android:id="#+id/item_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Date" />/ android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:orientation="vertical">
<TextView
android:id="#+id/item_eventName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Event Name"
android:textStyle="bold" />/android:textScaleX="18sp"
<TextView
android:id="#+id/item_contactNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Contact Number"
android:textStyle="bold" />
<TextView
android:id="#+id/item_type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Type of event"
android:textStyle="bold" />
<TextView
android:id="#+id/itemLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Location"
android:textStyle="bold" />
</LinearLayout>
<ImageView
android:id="#+id/item_image"
android:layout_width="75dp"
android:layout_height="75dp"
android:background="#color/white"
android:scaleType="centerCrop"
android:src="#drawable/pic1" />
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
I wanted to to ask how could i store an image, that will take from gallery and store it to a specific folder.
the location i want to store is Shortcut/Images
i'm posting my code and i want solution after this how to store this image into the location above (The location is not yet created)..
Please keep in mind i want to store image in internal storage so that my app could run in hybrid phone as well
package com.example.mohitgupta.shortcut;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
public class GetImage extends AppCompatActivity {
EditText imageName;
private ImageButton img;
private String name;
private Uri selectedImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_image);
imageName = (EditText) findViewById(R.id.ImageName);
name = imageName.getText().toString().trim();
}
public void GetImageIntent(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
selectedImage = data.getData();
img = (ImageButton) findViewById(R.id.imageSelected);
img.setImageURI(selectedImage);
}
}
public void SaveButtonClicked(View view){
BitmapDrawable drawable = (BitmapDrawable) img.getDrawable();
Bitmap bitmap = drawable.getBitmap();
//Toast.makeText(GetImage.this,"Image Saved",Toast.LENGTH_SHORT).show();
}
}
layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.mohitgupta.shortcut.GetImage">
<ImageButton
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_margin="15dp"
android:layout_gravity="center"
android:id="#+id/imageSelected"
android:onClick="GetImageIntent"
android:scaleType="fitCenter"
android:backgroundTint="#000000"
android:src="#drawable/ic_add_a_photo_white_24dp"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_margin="15dp"
android:hint="Enter Name of Image"
android:id="#+id/ImageName"
android:padding="10dp"
android:background="#drawable/shapes"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="Save"
android:onClick="SaveButtonClicked"/>
</LinearLayout>
So I am creating an events app using Firebase as my database. I am an amateur developer so please bear with me. There are 3 main problems that I have been facing:
1) My main problem is that data is not being written to Firebase. I have changed the rules to 'true' in the database module. I also have an image input by the user which is being uploaded, but the data such as event_title and others is not being uploaded
2) I have used Intent to pass data from one activity to another but it is not passing. I used a textView on the next Activity to setText, but it changes to null. The data is also not shwoing in the Log, as much I know about Log.d
3) I don't for what reason !TextUtils.isEmpty is not working on my CreateEvent2. I need to comment the entire if - condition to go to the CreateEvent3. However it is working in CreateEvent3.java.
I tried a lot of methods but I do not know for what reasons these errors are coming.
Here is my code:
CreateEvent2.java
package com.example.admin.college20;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class CreateEvent2 extends AppCompatActivity {
private EditText mEventTitle, mEventLocation, mEventCategory, mContact;
private Button mNextButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_event2);
mEventTitle = (EditText) findViewById(R.id.event_title);
mEventLocation = (EditText) findViewById(R.id.event_location);
mEventCategory = (EditText) findViewById(R.id.event_category);
mContact = (EditText) findViewById(R.id.contact_info);
mNextButton = (Button) findViewById(R.id.nextButton);
final String event_title = mEventTitle.getText().toString().trim();
final String event_location = mEventLocation.getText().toString().trim();
final String event_category = mEventCategory.getText().toString().trim();
final String contact = mContact.getText().toString().trim();
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/**if (!TextUtils.isEmpty(event_title)
&& !TextUtils.isEmpty(event_location)
&& !TextUtils.isEmpty(event_category)
&& !TextUtils.isEmpty(contact)) {**/
Intent i = new Intent(CreateEvent2.this, CreateEvent3.class);
i.putExtra("title", event_title);
i.putExtra("location", event_location);
i.putExtra("category", event_category);
i.putExtra("contact", contact);
startActivity(i);
}
});
}
}
activity_create_event2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.admin.college20.CreateEvent2"
android:background="#drawable/create_event_1">
<EditText
android:layout_width="300dp"
android:layout_height="50dp"
android:hint="Event Title"
android:layout_marginTop="90dp"
android:id="#+id/event_title"
android:inputType="textMultiLine"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/event_location"
android:layout_alignEnd="#+id/event_location" />
<EditText
android:layout_width="300dp"
android:layout_height="50dp"
android:hint="Event Location"
android:id="#+id/event_location"
android:inputType="textMultiLine"
android:layout_centerVertical="true"
android:layout_alignLeft="#+id/contact_info"
android:layout_alignStart="#+id/contact_info" />
<EditText
android:layout_width="300dp"
android:layout_height="50dp"
android:hint="Event Category"
android:id="#+id/event_category"
android:inputType="textMultiLine"
android:layout_marginTop="32dp"
android:layout_below="#+id/event_location"
android:layout_alignLeft="#+id/contact_info"
android:layout_alignStart="#+id/contact_info" />
<EditText
android:layout_width="300dp"
android:layout_height="50dp"
android:hint="Contact Number"
android:id="#+id/contact_info"
android:inputType="textMultiLine"
android:layout_above="#+id/nextButton"
android:layout_marginBottom="20dp"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="New Button"
android:id="#+id/nextButton"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="27dp" />
</RelativeLayout>
CreateEvent3.java
package com.example.admin.college20;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class CreateEvent3 extends AppCompatActivity {
private EditText mEventDesc, mEventFBUrl, mEventWebLink;
private TextView hello;
private Button upload_image_button, done_button;
private ProgressDialog progressDialog;
private static final int GALLERY_INTENT = 1;
private Uri imageUri = null;
private DatabaseReference mDatabaseReference;
private StorageReference mStorageRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_event3);
mEventDesc = (EditText) findViewById(R.id.event_desc);
mEventFBUrl = (EditText) findViewById(R.id.fb_event_url);
mEventWebLink = (EditText) findViewById(R.id.event_weblink);
upload_image_button = (Button) findViewById(R.id.upload_image_button);
done_button = (Button) findViewById(R.id.done_button);
hello = (TextView) findViewById(R.id.hello);
mDatabaseReference = FirebaseDatabase.
getInstance().
getReference().
child("Event");
mStorageRef = FirebaseStorage.getInstance().getReference();
progressDialog = new ProgressDialog(this);
upload_image_button.setVisibility(View.VISIBLE);
upload_image_button.setBackgroundColor(Color.TRANSPARENT);
upload_image_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
});
done_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startPosting();
Toast.makeText(CreateEvent3.this, "Button Selected", Toast.LENGTH_SHORT).show();
}
});
}
public void startPosting() {
progressDialog.setMessage("Uploading the Data");
Intent in = getIntent();
Bundle bundle = in.getExtras();
final String event_title = getIntent().getStringExtra("title");
final String event_location = getIntent().getStringExtra("location");
final String event_category = getIntent().getStringExtra("category");
final String contact = getIntent().getStringExtra("contact");
final String event_desc = mEventDesc.getText().toString().trim();
final String event_weblink = mEventWebLink.getText().toString().trim();
final String event_fb_url = mEventFBUrl.getText().toString().trim();
Log.d("Event Tile", event_title);
Log.d("Event Location", event_location);
Log.d("Event Category", event_category);
hello.setText(event_title);
if (!TextUtils.isEmpty(event_desc)
&& !TextUtils.isEmpty(event_weblink)
&& !TextUtils.isEmpty(event_fb_url)
&& imageUri != null) {
progressDialog.show();
StorageReference filepath = mStorageRef.child("Images").child(imageUri.getLastPathSegment());
filepath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri uri = taskSnapshot.getDownloadUrl();
DatabaseReference newEvent = mDatabaseReference.push();
newEvent.child("title").setValue(event_title);
newEvent.child("location").setValue(event_location);
newEvent.child("category").setValue(event_category);
newEvent.child("contact").setValue(contact);
newEvent.child("desc").setValue(event_desc);
newEvent.child("web").setValue(event_weblink);
newEvent.child("fb").setValue(event_fb_url);
newEvent.child("imageUrl").setValue(uri.toString());
progressDialog.dismiss();
startActivity(new Intent(CreateEvent3.this, MainPage1.class));
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(CreateEvent3.this, "Upload Failed :(", Toast.LENGTH_SHORT).show();
}
});
}
else{
Toast.makeText(this, "Fill in the details", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
imageUri = data.getData();
}
}
}
activity_create_event3.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.admin.college20.CreateEvent3"
android:background="#drawable/create_event_2">
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/event_desc"
android:layout_marginTop="144dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:inputType="textMultiLine"
android:hint="Enter short description here..."
/>
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/fb_event_url"
android:layout_below="#+id/event_desc"
android:layout_alignLeft="#+id/event_desc"
android:layout_alignStart="#+id/event_desc"
android:layout_marginTop="134dp" />
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/event_weblink"
android:layout_marginTop="49dp"
android:layout_below="#+id/fb_event_url"
android:layout_alignLeft="#+id/fb_event_url"
android:layout_alignStart="#+id/fb_event_url" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="300dp"
android:layout_height="60dp"
android:id="#+id/upload_image_button"
android:layout_marginTop="50dp"
android:layout_below="#+id/event_desc"
android:layout_alignLeft="#+id/event_desc"
android:layout_alignStart="#+id/event_desc" />
<Button
android:layout_width="120dp"
android:layout_height="wrap_content"
android:id="#+id/done_button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="15dp" />
<TextView
android:text="Hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/event_desc"
android:layout_alignEnd="#+id/event_desc"
android:layout_marginRight="49dp"
android:layout_marginEnd="49dp"
android:layout_marginTop="33dp"
android:id="#+id/hello" />
</RelativeLayout>
The problem is that you're getting the text from the EditText on your CreateEvent2's onCreate method. You should get it on your OnClickListener. Like this:
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String event_title = mEventTitle.getText().toString().trim();
final String event_location = mEventLocation.getText().toString().trim();
final String event_category = mEventCategory.getText().toString().trim();
final String contact = mContact.getText().toString().trim();
if (!TextUtils.isEmpty(event_title)
&& !TextUtils.isEmpty(event_location)
&& !TextUtils.isEmpty(event_category)
&& !TextUtils.isEmpty(contact)) {
Intent i = new Intent(CreateEvent2.this, CreateEvent3.class);
i.putExtra("title", event_title);
i.putExtra("location", event_location);
i.putExtra("category", event_category);
i.putExtra("contact", contact);
startActivity(i);
}
}
});
I am trying to add a layout(profile_upload)to my custom AlertDialog which is inside Profile.java
for The first time it works fine. but when i close AlertDialog and again click on the button it crashes sayng
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first
Profile.java
package com.example.accer.sportsgr;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class Profile extends AppCompatActivity implements View.OnClickListener {
ImageButton profile_btn;
AlertDialog.Builder alert;
Bitmap bitmap;
TextView tx_img_name;
Button btn_prfil_upld,btn_pic_choose;
ImageView img_prfl;
View v;
LayoutInflater inflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
profile_btn=(ImageButton)findViewById(R.id.user_profile_photo);
alert=new AlertDialog.Builder(this);
inflater=Profile.this.getLayoutInflater();
if (v == null) {
v = inflater.inflate(R.layout.profile_upload, null, false);
} else {
((ViewGroup) v.getParent()).removeView(v);
}
alert.setView(v);
btn_prfil_upld=(Button)v.findViewById(R.id.btnUpload_profile_pic);
btn_pic_choose=(Button)v.findViewById(R.id.btn_choose_profile_pic);
img_prfl=(ImageView)v.findViewById(R.id.img_profile_upload);
tx_img_name=(TextView)v.findViewById(R.id.tx_img_name);
btn_prfil_upld.setOnClickListener(this);
btn_pic_choose.setOnClickListener(this);
profile_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alert.setTitle("Update Profile Picture");
alert.show();
}
});
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null)
{
Uri filepath=data.getData();
try {
bitmap= MediaStore.Images.Media.getBitmap(getContentResolver(),filepath);
tx_img_name.setText(filepath.toString());
img_prfl.setImageBitmap(bitmap);
} catch (IOException e) {
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onClick(View view) {
int id=view.getId();
switch (id)
{
case R.id.btn_choose_profile_pic :
showFileChooser();
break;
case R.id.btnUpload_profile_pic:
break;
}
}
}
profile_upload.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choose Image"
android:id="#+id/btn_choose_profile_pic" />
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="#+id/img_profile_upload" />
<TextView
android:id="#+id/tx_img_name"
android:textAlignment="center"
android:gravity="center"
android:textSize="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Upload Image"
android:id="#+id/btnUpload_profile_pic" />
</LinearLayout>
activity_profile.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/header_cover_image"
android:layout_width="match_parent"
android:layout_height="75dp"
android:scaleType="centerCrop"
android:src="#drawable/navigation_header_image"/>
<ImageButton
android:id="#+id/user_profile_photo"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_below="#+id/header_cover_image"
android:layout_centerHorizontal="true"
android:layout_marginTop="-60dp"
android:background="#drawable/circular_imageview"
android:elevation="5dp"
android:padding="20dp"
android:scaleType="centerCrop"
android:clickable="true"/>
<!-- android:src="#drawable/profile"-->
<RelativeLayout
android:id="#+id/profile_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/header_cover_image"
android:background="#ebca0707"
android:elevation="4dp"
android:paddingBottom="24dp">
<ImageView
android:id="#+id/add_friend"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="25dp"
android:src="#drawable/ic_action_user_add"
android:layout_toLeftOf="#+id/drop_down_option_menu"/>
<ImageView
android:id="#+id/drop_down_option_menu"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:src="#drawable/ic_action_overflow"/>
<TextView
android:id="#+id/user_profile_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="76dp"
android:text="Name"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="#+id/user_profile_short_bio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/user_profile_name"
android:layout_centerHorizontal="true"
android:layout_marginTop="12dp"
android:text="Email"
android:textColor="#fff"
android:textSize="14sp" />
</RelativeLayout>
</RelativeLayout>
Error Log:
2-17 16:17:47.395 13465-13465/com.example.accer.sportsgr E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.accer.sportsgr, PID: 13465
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:4454)
at android.view.ViewGroup.addView(ViewGroup.java:4295)
at android.view.ViewGroup.addView(ViewGroup.java:4267)
at android.support.v7.app.AlertController.setupCustomContent(AlertController.java:613)
at android.support.v7.app.AlertController.setupView(AlertController.java:452)
at android.support.v7.app.AlertController.installContent(AlertController.java:215)
at android.support.v7.app.AlertDialog.onCreate(AlertDialog.java:258)
at android.app.Dialog.dispatchOnCreate(Dialog.java:389)
at android.app.Dialog.show(Dialog.java:293)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:956)
at com.example.accer.sportsgr.Profile$1.onClick(Profile.java:98)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
}
});
removeall views in this, it will call when u press the navigation back button
Alternatively, you can preserve AlertDialog instance through AlertDialog.Builder.create() instead of AlertDialog.Builder instance.
If you use custom view, dialog will be created and then the custom view will be attached to dialog window every time AlertDialog.Builder.show().
public class Profile extends AppCompatActivity implements View.OnClickListener {
AlertDialog dialog;
ImageButton profile_btn;
TextView tx_img_name;
Button btn_prfil_upld, btn_pic_choose;
ImageView img_prfl;
View v;
LayoutInflater inflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
profile_btn = (ImageButton) findViewById(R.id.user_profile_photo);
profile_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(dialog == null) {
dialog = getBuilder().create();
}
dialog.setTitle("Update Profile Picture");
dialog.show();
}
});
}
#NonNull
private AlertDialog.Builder getBuilder() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
inflater = Profile.this.getLayoutInflater();
if (v == null) {
v = inflater.inflate(R.layout.profile_upload, null, false);
} else {
((ViewGroup) v.getParent()).removeView(v);
}
alert.setView(v);
btn_prfil_upld = (Button) v.findViewById(R.id.btnUpload_profile_pic);
btn_pic_choose = (Button) v.findViewById(R.id.btn_choose_profile_pic);
img_prfl = (ImageView) v.findViewById(R.id.img_profile_upload);
tx_img_name = (TextView) v.findViewById(R.id.tx_img_name);
btn_prfil_upld.setOnClickListener(this);
btn_pic_choose.setOnClickListener(this);
return alert;
}
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.btn_choose_profile_pic:
break;
case R.id.btnUpload_profile_pic:
break;
}
}
}