Home > OS >  how can i make error toast message if data is not inserted into firebase (this is my code)
how can i make error toast message if data is not inserted into firebase (this is my code)

Time:12-04

this is my code qr code scanner

databaseReference.child(id).setValue(data).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            onBackPressed();
            if (task.isSuccessful()) {
                Toast.makeText(getApplicationContext(), "DATA INSERTED", Toast.LENGTH_SHORT).show();
            }
        }
    });
}

the successful task is working

CodePudding user response:

In your code I see you are using wrong onBackPressed();

databaseReference.child(id).setValue(data).addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull Task<Void> task) {
        if (task.isSuccessful()) {
            Toast.makeText(getApplicationContext(), "DATA INSERTED", Toast.LENGTH_SHORT).show();
        } else {
            // Error handling here
            Toast.makeText(getApplicationContext(), "DATA INSERT ERROR", Toast.LENGTH_SHORT).show();
        }
        onBackPressed(); //This will exit the screen, you should consider whether to use it
    }
});

UPDATE: I have updated the code, the best way to display toast for both Fragment and Activity. And I have added Log.d to check where the program runs and if it's working properly

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

public class BaseFragment extends Fragment {
    private static final int MSG_SHOW_TOAST = 1;

    void displayMessage(String message, boolean isLengthLong) {
        requireActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                int longShow = isLengthLong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT;
                Toast.makeText(requireActivity(), message, longShow).show();
            }
        });
    }
}

public class Demo extends BaseFragment {
    private String TAG = getClass().getSimpleName();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        displayMessage("Ahihi", false);
    }

    public void yourMethod() {
        databaseReference.child(id).setValue(data).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                // Put the log here, Check the log outputted from mobile on android studio to make sure this is working
                Log.d(TAG, "yourMethod: onComplete: status task is "   task.isSuccessful());
                if (task.isSuccessful()) {
                    displayMessage("DATA INSERTED", true);
                } else {
                    // Put the log here, Check the log outputted from mobile on android studio to make sure this is working
                    Log.d(TAG, "yourMethod: onComplete: status task is ERROR ");
                    displayMessage("DATA INSERT ERROR", true);
                }
                onBackPressed(); //This will exit the screen, you should consider whether to use it
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

//========================================= below code is for activity

public class BaseActivity extends AppCompatActivity {
    void displayMessage(String message, boolean isLengthLong) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                int longShow = isLengthLong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT;
                Toast.makeText(getApplicationContext(), message, longShow).show();
            }
        });
    }
}

public class Demo extends BaseActivity {
    private String TAG = getClass().getSimpleName();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        displayMessage("Ahihi", false);
    }

    public void yourMethod() {
        databaseReference.child(id).setValue(data).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                // Put the log here, Check the log outputted from mobile on android studio to make sure this is working
                Log.d(TAG, "yourMethod: onComplete: status task is "   task.isSuccessful());
                if (task.isSuccessful()) {
                    displayMessage("DATA INSERTED", true);
                } else {
                    // Put the log here, Check the log outputted from mobile on android studio to make sure this is working
                    Log.d(TAG, "yourMethod: onComplete: status task is ERROR ");
                    displayMessage("DATA INSERT ERROR", true);
                }
                onBackPressed(); //This will exit the screen, you should consider whether to use it
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

CodePudding user response:

This is my whole code

package com.project.healthmonitoring.Util;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.nfc.Tag;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;

import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.zxing.Result;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import com.project.healthmonitoring.Activities.DashBoard;
import com.project.healthmonitoring.Activities.Scanner;
import com.project.healthmonitoring.Model.Data;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import me.dm7.barcodescanner.zxing.ZXingScannerView;

import static com.project.healthmonitoring.Auth.Register.TAG;

public class qrscanner extends AppCompatActivity implements ZXingScannerView.ResultHandler
{
    ZXingScannerView scannerView;
    private DatabaseReference databaseReference;
    private static final int MSG_SHOW_TOAST = 1;


    @Override
    protected void onCreate(android.os.Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        scannerView=new ZXingScannerView(this);
        setContentView(scannerView);
        databaseReference = FirebaseDatabase.getInstance().getReference("data");
        

        Dexter.withContext(getApplicationContext())
                .withPermission(Manifest.permission.CAMERA)
                .withListener(new PermissionListener() {
                    @Override
                    public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
                    scannerView.startCamera();
                    }

                    @Override
                    public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {

                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
                    permissionToken.continuePermissionRequest();
                    }
                }).check();
    }



    @Override
    public void handleResult(Result rawResult) {
        JsonParser jsonParser = new JsonParser();
        JsonObject jsonObject = (JsonObject) jsonParser.parse(rawResult.getText());
        String id = databaseReference.push().getKey();
        String name = jsonObject.get("name").getAsString();
        String phone = jsonObject.get("phone").getAsString();
        String address = jsonObject.get("address").getAsString();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat date = new SimpleDateFormat("MM-dd-yyyy");//dd/MM/yyyy
        SimpleDateFormat minute = new SimpleDateFormat("HH:mm:ss");
        String dates = date.format(calendar.getTime());
        String minutes = minute.format(calendar.getTime());
        Data data = new Data(id, name, phone, address, dates, minutes);




        databaseReference.child(id).setValue(data).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Toast.makeText(getApplicationContext(), "DATA INSERTED", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), "DATA INSERT ERROR", Toast.LENGTH_SHORT).show();
                }
                onBackPressed();
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        scannerView.stopCamera();
    }

    @Override
    protected void onResume() {
        super.onResume();
        scannerView.setResultHandler(this);
        scannerView.startCamera();
    }
}
  • Related