package my.anupamroy.smartcanteenapp.activities;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
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.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
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 java.util.HashMap;
import my.anupamroy.smartcanteenapp.Constants;
import my.anupamroy.smartcanteenapp.R;
public class AddProductActivity extends AppCompatActivity {
//ui views
private ImageButton backBtn;
private ImageView productIconTv;
private EditText titleEt,descriptionEt,quantityEt,priceEt;
private TextView categoryTv;
private Button addProductBtn;
//permission Constants
private static final int CAMERA_REQUEST_CODE=200;
private static final int STORAGE_REQUEST_CODE=300;
//image pick constants
private static final int IMAGE_PICK_GALLERY_CODE=400;
private static final int IMAGE_PICK_CAMERA_CODE=500;
//permission arrays
private String[] cameraPermissions;
private String[] storagePermissions;
//image picked uri
private Uri image_uri;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_product);
//init ui views
backBtn=findViewById(R.id.backBtn);
productIconTv=findViewById(R.id.productIconIv);
titleEt=findViewById(R.id.titleEt);
descriptionEt=findViewById(R.id.descriptionEt);
categoryTv=findViewById(R.id.categoryTv);
quantityEt=findViewById(R.id.quantityEt);
priceEt=findViewById(R.id.priceEt);
addProductBtn=findViewById(R.id.addProductBtn);
firebaseAuth=FirebaseAuth.getInstance();
//setup progress dialog
progressDialog=new ProgressDialog(this);
progressDialog.setTitle("Please wait");
progressDialog.setCanceledOnTouchOutside(false);
//init permission arrays
cameraPermissions=new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions=new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
backBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
productIconTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//show dialog to pick image
showImagePickDialog();
}
});
categoryTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//pick category
categoryDialog();
}
});
addProductBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Flow:
//1.Input Data
//2.Validate Data
//3.Add data to db
inputData();
}
});
}
private String productTitle,productDescription,productCategory,productQuantity,originalPrice;
private void inputData() {
//1. input data
productTitle = titleEt.getText().toString().trim();
productDescription = descriptionEt.getText().toString().trim();
productCategory = categoryTv.getText().toString().trim();
productQuantity = quantityEt.getText().toString().trim();
originalPrice = priceEt.getText().toString().trim();
//2.Validate Data
if (TextUtils.isEmpty(productTitle)) {
Toast.makeText(this, "Title is required", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(productCategory)) {
Toast.makeText(this, "Category is required", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(productQuantity)) {
Toast.makeText(this, "Quantity is required", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(originalPrice)) {
Toast.makeText(this, "Price is required", Toast.LENGTH_SHORT).show();
return;
}
addProduct();
}
private void addProduct() {
//3. Add data to db
progressDialog.setMessage("Adding Product...");
progressDialog.show();
final String timestamp=""+System.currentTimeMillis();
if(image_uri==null){
//upload without image
//set data to upload
HashMap<String ,Object>hashMap=new HashMap<>();
hashMap.put("productId",""+timestamp);
hashMap.put("productTitle",""+productTitle);
hashMap.put("productDescription",""+productDescription);
hashMap.put("productCategory",""+productCategory);
hashMap.put("productQuantity",""+productQuantity);
hashMap.put("productIcon","");//no image, set empty
hashMap.put("originalPrice",""+originalPrice);
hashMap.put("timestamp",""+timestamp);
hashMap.put("uid",""+firebaseAuth.getUid());
//add to db
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users");
reference.child(firebaseAuth.getUid()).child("Products").child(timestamp).setValue(hashMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
//db updated
progressDialog.dismiss();
Toast.makeText(AddProductActivity.this, "Product Added...", Toast.LENGTH_SHORT).show();
clearData();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
//failed updating db
progressDialog.dismiss();
Toast.makeText(AddProductActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
else{
//upload with image
//first upload image to storage
//name and path of the image to be uploaded
String filePathAndName="product_images/" + "" +timestamp;
StorageReference storageReference= FirebaseStorage.getInstance().getReference(filePathAndName);
storageReference.putFile(image_uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//get url of uploaded image
Task<Uri> uriTask=taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
Uri downloadImageUri=uriTask.getResult();
if(uriTask.isSuccessful()){
HashMap<String ,Object>hashMap=new HashMap<>();
hashMap.put("productId",""+timestamp);
hashMap.put("productTitle",""+productTitle);
hashMap.put("productDescription",""+productDescription);
hashMap.put("productCategory",""+productCategory);
hashMap.put("productQuantity",""+productQuantity);
hashMap.put("productIcon",""+downloadImageUri);
hashMap.put("originalPrice",""+originalPrice);
hashMap.put("timestamp",""+timestamp);
hashMap.put("uid",""+firebaseAuth.getUid());
//add to db
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users");
reference.child(firebaseAuth.getUid()).child("Products").child(timestamp).setValue(hashMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
//db updated
progressDialog.dismiss();
Toast.makeText(AddProductActivity.this, "Product Added...", Toast.LENGTH_SHORT).show();
clearData();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
//failed updating db
progressDialog.dismiss();
Toast.makeText(AddProductActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(AddProductActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
private void clearData(){
//clear data after uploading product
titleEt.setText("");
descriptionEt.setText("");
categoryTv.setText("");
quantityEt.setText("");
priceEt.setText("");
productIconTv.setImageResource(R.drawable.ic_add_shopping_primary);
image_uri=null;
}
private void categoryDialog() {
//dialog
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Product Category")
.setItems(Constants.productCategories, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
//get picked category
String category=Constants.productCategories[which];
//set picked category
categoryTv.setText(category);
}
})
.show();
}
private void showImagePickDialog() {
//options to display in dialog
String[] options={"Camera","Gallery"};
//dialog
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Pick Image")
.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//handle clicks
if(which==0){
//camera clicked
if(checkCameraPermission()){
//camera permission allowed
pickFromCamera();
}
else{
//not allowed, request
requestCameraPermission();
}
}
else{
//gallery clicked
if(checkStoragePermission()){
//storage Permissions allowed
pickFromGallery();
}
else{
//not allowed request
requestStoragePermission();
}
}
}
})
.show();
}
private void pickFromGallery(){
//intent to pick image from gallery
Intent intent=new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,IMAGE_PICK_GALLERY_CODE);
}
private void pickFromCamera(){
//intent to pick image from camera
//using media store to pick original image
ContentValues contentValues=new ContentValues();
contentValues.put(MediaStore.Images.Media.TITLE,"Temp_Image_Title");
contentValues.put(MediaStore.Images.Media.DESCRIPTION,"Temp_Image_Description");
image_uri=getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues);
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,image_uri);
startActivityForResult(intent,IMAGE_PICK_CAMERA_CODE);
}
private boolean checkStoragePermission(){
boolean result= ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)==
(PackageManager.PERMISSION_GRANTED);
return result;//return true/false
}
private void requestStoragePermission(){
ActivityCompat.requestPermissions(this,storagePermissions,STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermission(){
boolean result=ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA)==
(PackageManager.PERMISSION_GRANTED);
boolean result1=ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)==
(PackageManager.PERMISSION_GRANTED);
return result && result1;
}
private void requestCameraPermission(){
ActivityCompat.requestPermissions(this,cameraPermissions,CAMERA_REQUEST_CODE);
}
//handle permission results
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case CAMERA_REQUEST_CODE:{
if(grantResults.length>0){
boolean cameraAccepted=grantResults[0]==PackageManager.PERMISSION_GRANTED;
boolean storageAccepted=grantResults[1]==PackageManager.PERMISSION_GRANTED;
if(cameraAccepted && storageAccepted){
//permission allowed
pickFromCamera();
}
else{
//permission denied
Toast.makeText(this,"Camera and Storage Permissions are necessary...",Toast.LENGTH_SHORT).show();
}
}
}
break;
case STORAGE_REQUEST_CODE:{
if(grantResults.length>0){
boolean storageAccepted=grantResults[0]==PackageManager.PERMISSION_GRANTED;
if(storageAccepted){
//permission allowed
pickFromGallery();
}
else{
//permission denied
Toast.makeText(this,"Storage Permission is required...",Toast.LENGTH_SHORT).show();
}
}
}
break;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
//handle image pick results
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (resultCode==RESULT_OK){
if (requestCode==IMAGE_PICK_GALLERY_CODE){
//get picked image
image_uri=data.getData();
//set to imageview
productIconTv.setImageURI(image_uri);
}
else if(requestCode==IMAGE_PICK_CAMERA_CODE){
//set to image view
productIconTv.setImageURI(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
LAYOUT FILE:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activities.AddProductActivity">
<!--Toolbar-->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:padding="10dp"
android:background="@drawable/shape_rect01">
<ImageButton
android:id="@+id/backBtn"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="@null"
android:src="@drawable/ic_back_white" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Add Product"
android:textColor="@color/colorWhite"
android:textSize="20sp"
android:textStyle="bold"/>
</RelativeLayout>
<!--Form to input data-->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="60dp">
<com.blogspot.atifsoftwares.circularimageview.CircularImageView
android:id="@+id/productIconIv"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:src="@drawable/ic_add_shopping_primary"
app:c_border="true"
app:c_border_color="@color/colorPrimaryDark"
app:c_border_width="1dp" />
<EditText
android:id="@+id/titleEt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/productIconIv"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="5dp"
android:background="@drawable/shape_rect02"
android:drawableStart="@drawable/ic_title_gray"
android:drawablePadding="10dp"
android:hint="Title"
android:inputType="textPersonName|textCapWords"
android:padding="10dp" />
<EditText
android:id="@+id/descriptionEt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/titleEt"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="5dp"
android:background="@drawable/shape_rect02"
android:drawableStart="@drawable/ic_title_gray"
android:drawablePadding="10dp"
android:hint="Description"
android:inputType="textPersonName|textCapWords"
android:padding="10dp" />
<TextView
android:id="@+id/categoryTv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/descriptionEt"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="5dp"
android:background="@drawable/shape_rect02"
android:drawableStart="@drawable/ic_baseline_apps_gray"
android:drawableEnd="@drawable/ic_down_gray"
android:drawablePadding="10dp"
android:hint="Category"
android:inputType="textPersonName|textCapWords"
android:padding="10dp" />
<EditText
android:id="@+id/quantityEt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/categoryTv"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="5dp"
android:background="@drawable/shape_rect02"
android:drawableStart="@drawable/ic_cart_gray"
android:drawablePadding="10dp"
android:hint="Quantity"
android:inputType="text"
android:padding="10dp" />
<EditText
android:id="@+id/PriceEt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/quantityEt"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="5dp"
android:background="@drawable/shape_rect02"
android:drawableStart="@drawable/ic_baseline_currency_rupee_24"
android:drawablePadding="10dp"
android:hint="Price"
android:inputType="numberDecimal"
android:padding="10dp" />
<Button
android:id="@+id/addProductBtn"
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/PriceEt"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:minWidth="150dp"
android:text="Add Product"
android:textStyle="bold" />
</RelativeLayout>
</RelativeLayout>
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
In LOGCAT I AM getting the following errors in line number 132,43,119
java.lang.NullPointerException: Attempt to invoke virtual method ‘android.text.Editable android.widget.EditText.getText()’ on a null object reference
java.lang.NullPointerException: Attempt to invoke virtual method ‘android.text.Editable android.widget.EditText.getText()’ on a null object reference
java.lang.NullPointerException: Attempt to invoke virtual method ‘android.text.Editable android.widget.EditText.getText()’ on a null object reference
**my.anupamroy.smartcanteenapp.activities.AddProductActivity.inputData(AddProductActivity.java:132)** at my.anupamroy.smartcanteenapp.activities.AddProductActivity.access$200(AddProductActivity.java:43) *at my.anupamroy.smartcanteenapp.activities.AddProductActivity$4.onClick(AddProductActivity.java:119)**
Please Help me out of this error
from many days i am struggling with this error
2
Answers
Check your
EditText
in XML showing PriceEt andin Activity its initialized as
Change that from XML file either in Activity and try once.
You have given
PriceEt
id to theEditText
in the XML but you initialized it withpriceEt
which is causing an error, ReplacepriceEt
withPriceEt
to resolve the error.Old code
New code