How can I solve Singelton is NULL problem [duplicate] - java

This question already has answers here:
Wait Firebase async retrieve data in Android
(2 answers)
How to wait for Firebase Task to complete to get result as an await function
(2 answers)
Firebase (android) not returning the reference for an Object
(1 answer)
getContactsFromFirebase() method return an empty list
(1 answer)
Closed 1 year ago.
I'm trying to make a student registration system and I keep these students in firestore. I don't want it to add student with same number when adding student and for this, I created a singleton class. This singleton class has a flag value. I used this flag to provide control if there is a student with the same number in the firestore.
but it always returns null. I don't understand.
I'm just sharing the necessary codes.
My add student class
private ActivityOgrenciEkleBinding binding;
private FirebaseFirestore mFirestore = FirebaseFirestore.getInstance();
private LinkedHashMap<String,String> linkedHashMap;
private OgrenciyiKontrolEt ogrenciyiKontrolEt;
Singleton singleton;
public void init(){
linkedHashMap = new LinkedHashMap<>();
singleton = Singleton.getInstance();
btn_Ogrenci_EKLE();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityOgrenciEkleBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
init();
}
public void btn_Ogrenci_EKLE(){
binding.btnEkleOgrenci.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
String email_ogr = binding.emailOgrenci.getText().toString();
String ad_ogr = binding.isimOgrenci.getText().toString();
String soyisim_ogr = binding.soyisimOgrenci.getText().toString();
String no_ogr = binding.numaraOgrenci.getText().toString();
String parola_ogr = binding.sifreOgrenci.getText().toString();
ogrenciyiKontrolEt = new
OgrenciyiKontrolEt(no_ogr,OgrenciEkleActivity.this);// I
//created object from
//control class to check students
if(email_ogr.equals("") || ad_ogr.equals("") || soyisim_ogr.equals("") || no_ogr.equals("") || parola_ogr.equals("")){
AlertDialog.Builder builder = new AlertDialog.Builder(OgrenciEkleActivity.this);
builder.setTitle("UYARI !");
builder.setMessage("Boş alan bırakmayınız !");
builder.setIcon(R.drawable.warningicon);
builder.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.show();
}
else{
ogrenciyiKontrolEt.OGR_KONTROL();
System.out.println("singleton get flag"+singleton.getflag()); //singleton returns null here and and it never
//goes into the if loop
if("100".equals(singleton.getflag())){
AlertDialog.Builder builder = new AlertDialog.Builder(OgrenciEkleActivity.this);
builder.setIcon(R.drawable.warningicon);
builder.setMessage(no_ogr+" numaralı öğrenci zaten kayıtlı lütfen farklı bir numara giriniz.");
builder.setTitle("UYARI");
builder.setPositiveButton("TAMAM", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.show();
}
else{
linkedHashMap.put("name",ad_ogr);
linkedHashMap.put("lastname",soyisim_ogr);
linkedHashMap.put("number",no_ogr);
linkedHashMap.put("email",email_ogr);
linkedHashMap.put("password",parola_ogr);
mFirestore.collection("Students").add(linkedHashMap).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(#NonNull DocumentReference documentReference) {
Toast toast = Toast.makeText(OgrenciEkleActivity.this,"Öğrenci başaralı bir şekilde eklendi.",Toast.LENGTH_LONG);
toast.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast toast = Toast.makeText(OgrenciEkleActivity.this,"Öğrenci eklerken bir hata ile karşılaşıldı.",Toast.LENGTH_LONG);
toast.show();
}
});
}
}
}
});
}
Control class that I created to control students
public class OgrenciyiKontrolEt {
protected String ogrenci_no;
protected String firestore_ogr_no;
protected FirebaseFirestore firebaseFirestoreDb = FirebaseFirestore.getInstance();
public Context context;
Singleton singleton = Singleton.getInstance();
public OgrenciyiKontrolEt(String ogr_no,Context context){
this.ogrenci_no = ogr_no;
this.context = context;
}
public void OGR_KONTROL(){
firebaseFirestoreDb.collection("Students")
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(#NonNull QuerySnapshot queryDocumentSnapshots) {
List<DocumentSnapshot> snapshotList = queryDocumentSnapshots.getDocuments();
for(DocumentSnapshot snapshot: snapshotList ) {
firestore_ogr_no = snapshot.getString("number");
if(firestore_ogr_no.equals(ogrenci_no)) {
singleton.setflag("100"); //If there is a student with the same
number, I set the flag in the singleton to 100.
}
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast toast = Toast.makeText(context,"Bir hata ile karşılaşıldı.",Toast.LENGTH_LONG);
toast.show();
}
});
}
}
My singleton class
public class Singleton {
**EDIT**
private String flag="1";
**EDIT**
private static Singleton singleton;
private Singleton() {
}
public String getflag() {
return flag;
}
public void setflag(String flag) {
this.flag = flag;
}
public static Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}

Your flag is not initialized when you call it, Either set something as default value or initialize in constructor like
private Singleton() {
this.flag = "";
}
or call your setFlag before first occurrence of getFalg

Related

First and last switch button getting triggred in recycler view

Hi I have switch button (switchTaskFinished) on my recycler view,when I am clicking any button, the last button is getting selected. Also when I press button it updates the data to firebase. And changes the button status accordingly. But even though buttons value is true it only updates last button status not others.
public class MyAdaptorUser extends RecyclerView.Adapter<MyAdaptorUser.myViewHolder> {
private Context context;
private ArrayList<TaskModel> taskLists;
private Switch switchTaskFinished;
private OnTaskClickListner mTaskListner;
private AlertDialog dialog;
private AlertDialog.Builder builder;
private TaskConfirmationSender taskConfirmationSender;
public MyAdaptorUser(Context c, ArrayList<TaskModel> t, OnTaskClickListner onTaskClickListner) {
context = c;
taskLists = t;
this.mTaskListner = onTaskClickListner;
}
#NonNull
#Override
public MyAdaptorUser.myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
builder = new AlertDialog.Builder(parent.getContext());
builder.setTitle("Please Wait").setView(R.layout.my_progress_view).setCancelable(false);
dialog = builder.create();
return new MyAdaptorUser.myViewHolder(LayoutInflater.from(context).inflate(R.layout.task_preview, parent, false), mTaskListner);
}
#Override
public void onBindViewHolder(#NonNull MyAdaptorUser.myViewHolder holder, final int position) {
//Set title and description to task preview textviews
holder.title.setText(taskLists.get(position).getTaskTitle());
holder.dueDate.setText(taskLists.get(position).getDueDate());
holder.description.setText(taskLists.get(position).getTaskDescription());
//Sets the path of database to taskAwatingConfirmation/task_title/UserEmail
final DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
try {
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
email = removeSpecialCharacter(email);
final DatabaseReference taskConfirmationRef = dbRef
.child("taskAwatingConfirmation")
.child(taskLists.get(position).getTaskTitle())
.child(email);
taskConfirmationRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//Fetching switchButton Status (Task finished) from database
switchTaskFinished.setChecked(false);
String buttonStatus = (String) dataSnapshot.child("buttonStatus").getValue();
if (buttonStatus != null) {
Log.d("taskerror", buttonStatus);
if (buttonStatus.equals("true")) {
switchTaskFinished.setChecked(true);
} else if (buttonStatus.equals("false")) {
switchTaskFinished.setChecked(false);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
switchTaskFinished.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
//dialog = builder.show();
taskConfirmationSender = new TaskConfirmationSender();
//When Task Finished button is clicked send data to database
sendConfirmationToAdmin(new FirebaseCallBack() {
#Override
public void Callback(TaskConfirmationSender taskConfirmationSender) {
taskConfirmationSender.setButtonStatus(String.valueOf(buttonView.isChecked()));
taskConfirmationSender.setTaskDueDate(taskLists.get(position).getDueDate());
if (buttonView.isChecked()) {
taskConfirmationRef.setValue(taskConfirmationSender).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
});
}else{
taskConfirmationRef.setValue(taskConfirmationSender).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
});
}
}
});
}
});
} catch (NullPointerException ignored) {
dialog.dismiss();
}
}
private String removeSpecialCharacter(String email) {
StringBuffer sbf = new StringBuffer(email);
email = String.valueOf(sbf.reverse());
int length = email.length();
email = email.substring(4, length);
StringBuffer stringBuffer = new StringBuffer(email);
email = String.valueOf(stringBuffer.reverse());
return email.replace("#", "_");
}
private void sendConfirmationToAdmin(final FirebaseCallBack firebaseCallBack) {
DatabaseReference volunteerRef = FirebaseDatabase.getInstance().getReference()
.child("Volunteer").child("Member")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
taskConfirmationSender = new TaskConfirmationSender();
try {
//Fetching details of users (full name, email) from database and setting their value to taskConfirmation Object
volunteerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child("fullName").getValue().toString();
String userEmail = dataSnapshot.child("email").getValue().toString();
String userId = dataSnapshot.getKey();
//TODO: Fetch UID of user and set it to taskConfirmation OBject
taskConfirmationSender.setUserEmail(userEmail);
taskConfirmationSender.setUserName(userName);
taskConfirmationSender.setId(userId);
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
String submissionDate = day + "/" + month + "/" + year;
taskConfirmationSender.setSubmissionDate(submissionDate);
firebaseCallBack.Callback(taskConfirmationSender);
/**/
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} catch (NullPointerException ee) {
}
}
private interface FirebaseCallBack {
void Callback(TaskConfirmationSender taskConfirmationSender);
}
#Override
public int getItemCount() {
return taskLists.size();
}
class myViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title, dueDate, description;
OnTaskClickListner onTaskClickListner;
public myViewHolder(#NonNull View itemView, OnTaskClickListner onTaskClickListner) {
super(itemView);
title = itemView.findViewById(R.id.taskTitle);
dueDate = itemView.findViewById(R.id.taskDueDate);
description = itemView.findViewById(R.id.taskDescription);
switchTaskFinished = itemView.findViewById(R.id.switchTaskFinished);
this.onTaskClickListner = onTaskClickListner;
ConstraintLayout taskBar = itemView.findViewById(R.id.linearLayoutTaskBar);
itemView.setOnClickListener(this);
//hides delete task button
taskBar.setVisibility(View.GONE);
}
#Override
public void onClick(View v) {
onTaskClickListner.onTaskClick(getAdapterPosition());
}
}
public interface OnTaskClickListner {
void onTaskClick(int position);
}
}
Maybe its because of the valueEventListener that stays attached:
Instead of this:
taskConfirmationRef.addValueEventListener(new ValueEventListener() {.........
Do this:
taskConfirmationRef.addListenerForSingleValueEvent(new ValueEventListener() {......
And set the switch to checked or unchecked when you turn on or off:
if (buttonView.isChecked()) {
//here
switchTaskFinished.setChecked(true);
taskConfirmationRef.setValue(taskConfirmationSender).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
});
}else{
//here
switchTaskFinished.setChecked(false);
...................

Android Java: AlertDialog method called from another class causes null pointer exception

I'm trying to call a method from another class which then calls an AlertDialog method, and I've tried many things but it always causes a null pointer exception. The calling class is running a web server, and I have a RecyclerView list on the activity class containing the method being called. here's some code from the activity class with AlertDialog:
public class ListClass extends AppCompatActivity {
private WebSvr server;
private static final int PORT = 8080;
private androidx.appcompat.widget.Toolbar toolbar;
private ListView lv;
private CustomAdapter customAdapter;
public ArrayList<EditModel> editModelArrayList;
public static String[] newList = new String[20];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server_screen);
toolbar = (androidx.appcompat.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
startWebServer();
customAdapter = new CustomAdapter(this, editModelArrayList);
lv.setAdapter(customAdapter);
}
public static boolean listUpdated;
public void updateList() {
listUpdated = false;
Runnable r = new Runnable() {
#Override
public void run() {
for (int i = 0; i < 20; i++) {
if (CustomAdapter.editModelArrayList.get(i).getEditTextValue() != "") {
newList[i] = CustomAdapter.editModelArrayList.get(i).getEditTextValue();
} else {
if (!showNotification) {
runOnUiThread(new Runnable() {
#Override
public void run() {
showNullFieldNotification(); // <------------- CALLING THIS
}
});
showNotification = true;
}
}
}
listUpdated = true;
}
};
Thread thread = new Thread(r);
thread.start();
}
boolean showNotification = false;
public void showNullFieldNotification() {
new AlertDialog.Builder(ListClass.this)
.setTitle("Warning, some fields are empty")
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
showNotification = false;
}
}).show();
}
public static boolean returnListUpdated() {
return listUpdated;
}
...
}
And here's the code from my web server class:
public class WebSvr extends NanoHTTPD {
public ListClass ListClass = new ListClass();
public WebSvr(int port){
super(port);
}
#Override
public Response serve(String uri, Method method,
Map<String, String> header,
Map<String, String> parameters,
Map<String, String> files) {
ListClass.updateList(); // <--------------- THE METHOD CALLED
while (!ListClass.returnListUpdated()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String strResponse = Arrays.toString(ListClass.returnString());
return newFixedLengthResponse(strResponse);
}
}
It always causes null pointer exception on this line:
new AlertDialog.Builder(ListClass.this)
and where the method is called in ListClass:
showNullFieldNotification();
Error message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.espressif.iot_esptouch_demo, PID: 18217
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:152)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:224)
at android.app.AlertDialog$Builder.<init>(AlertDialog.java:454)
at com.myProject.ListClass.showNullFieldNotification(ListClass.java:177)
at com.myProject.ListClass$4.run(ListClass.java:193)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6665)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:772)
If I call showNullFieldNotification() in ListClass onCreate() or from the options menu it works no problem, but when called from the WebSvr class it always causes the exception.
For context on the AlertDialog I've tried ListClass.this, getApplicationContext(), getBaseContext()... I've tried to save a context in onCreate as getApplicationContext() and use that.
I've tried to use the solution from this question to get context but that didn't work either. Would really appreciate any help.
EDIT: Forgot to mention that I had also tried to build the alert in this way:
public void showNullFieldNotification2() {
AlertDialog.Builder alert = new AlertDialog.Builder(ListClass.this);
alert.setTitle("Warning, some fields detected as being empty or having \"0\" as value");
alert.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
showNotification = false;
}
});
AlertDialog dialog = alert.create();
dialog.show();
}
you forgot create Alert Dialog so it null, not the context
Android simple alert dialog
Got the solution from here in answer from Dan Bray. Needed to use a static context.
Since you are calling from outside of an activity, you'll need to save the context in activity class:
public static Context context;
And inside onCreate:
context = this;
To show notification:
new Handler(Looper.getMainLooper()).post(new Runnable(){
#Override
public void run(){
new AlertDialog.Builder(context)
.setTitle("Warning, some fields are empty")
.setNegativeButton("OK",new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface,int i){
dialogInterface.cancel();
showNotification=false;
}
}).show();
}
});
The methods called in the activity class must also be public static.

Convert Activity to Fragment which use Database and Adapter class

I'm loading json file from online and saving it on Sqlite such that when app is offline...Then still user will be able to see the data.
It works fine in MainActivity.
But when I try to covert it into fragment, I'm getting errors of Fragment cannot be cast in to FlowerAdapter$FlowerClickListener
Here is the error file
My Fragment name is nepali.
Here is the Mainactivity
public class MainActivity extends AppCompatActivity implements FlowerAdapter.FlowerClickListener, FlowerFetchListener {
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView mRecyclerView;
private RestManager mManager;
private FlowerAdapter mFlowerAdapter;
private FlowerDatabase mDatabase;
private Button mReload;
private ProgressDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
configViews();
mManager = new RestManager();
mDatabase = new FlowerDatabase(this);
loadFlowerFeed();
mReload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadFlowerFeed();
}
});
}
private void loadFlowerFeed() {
mDialog = new ProgressDialog(MainActivity.this);
mDialog.setMessage("Loading Flower Data...");
mDialog.setCancelable(true);
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setIndeterminate(true);
mFlowerAdapter.reset();
mDialog.show();
if (getNetworkAvailability()) {
getFeed();
} else {
getFeedFromDatabase();
}
}
private void getFeedFromDatabase() {
mDatabase.fetchFlowers(this);
}
private void configViews() {
mReload = (Button) findViewById(R.id.reload);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
mFlowerAdapter = new FlowerAdapter(this);
mRecyclerView.setAdapter(mFlowerAdapter);
}
#Override
public void onClick(int position) {
}
public void getFeed() {
Call<List<Flower>> listCall = mManager.getFlowerService().getAllFlowers();
listCall.enqueue(new Callback<List<Flower>>() {
#Override
public void onResponse(Call<List<Flower>> call, Response<List<Flower>> response) {
if (response.isSuccessful()) {
List<Flower> flowerList = response.body();
for (int i = 0; i < flowerList.size(); i++) {
Flower flower = flowerList.get(i);
SaveIntoDatabase task = new SaveIntoDatabase();
task.execute(flower);
mFlowerAdapter.addFlower(flower);
}
} else {
int sc = response.code();
switch (sc) {
case 400:
Log.e("Error 400", "Bad Request");
break;
case 404:
Log.e("Error 404", "Not Found");
break;
default:
Log.e("Error", "Generic Error");
}
}
mDialog.dismiss();
}
#Override
public void onFailure(Call<List<Flower>> call, Throwable t) {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public boolean getNetworkAvailability() {
return Utils.isNetworkAvailable(getApplicationContext());
}
#Override
public void onDeliverAllFlowers(List<Flower> flowers) {
}
#Override
public void onDeliverFlower(Flower flower) {
mFlowerAdapter.addFlower(flower);
}
#Override
public void onHideDialog() {
mDialog.dismiss();
}
public class SaveIntoDatabase extends AsyncTask<Flower, Void, Void> {
private final String TAG = SaveIntoDatabase.class.getSimpleName();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Flower... params) {
Flower flower = params[0];
try {
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
return null;
}
}
}
and FlowerDatabase class is
public class FlowerDatabase extends SQLiteOpenHelper {
private static final String TAG = FlowerDatabase.class.getSimpleName();
public FlowerDatabase(Context context) {
super(context, Constants.DATABASE.DB_NAME, null, Constants.DATABASE.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(Constants.DATABASE.CREATE_TABLE_QUERY);
} catch (SQLException ex) {
Log.d(TAG, ex.getMessage());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(Constants.DATABASE.DROP_QUERY);
this.onCreate(db);
}
public void addFlower(Flower flower) {
Log.d(TAG, "Values Got " + flower.getName());
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Constants.DATABASE.PRODUCT_ID, flower.getProductId());
values.put(Constants.DATABASE.CATEGORY, flower.getCategory());
values.put(Constants.DATABASE.PRICE, Double.toString(flower.getPrice()));
values.put(Constants.DATABASE.INSTRUCTIONS, flower.getInstructions());
values.put(Constants.DATABASE.NAME, flower.getName());
try {
db.insert(Constants.DATABASE.TABLE_NAME, null, values);
} catch (Exception e) {
}
db.close();
}
public void fetchFlowers(FlowerFetchListener listener) {
FlowerFetcher fetcher = new FlowerFetcher(listener, this.getWritableDatabase());
fetcher.start();
}
public class FlowerFetcher extends Thread {
private final FlowerFetchListener mListener;
private final SQLiteDatabase mDb;
public FlowerFetcher(FlowerFetchListener listener, SQLiteDatabase db) {
mListener = listener;
mDb = db;
}
#Override
public void run() {
Cursor cursor = mDb.rawQuery(Constants.DATABASE.GET_FLOWERS_QUERY, null);
final List<Flower> flowerList = new ArrayList<>();
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
Flower flower = new Flower();
flower.setFromDatabase(true);
flower.setName(cursor.getString(cursor.getColumnIndex(Constants.DATABASE.NAME)));
flower.setPrice(Double.parseDouble(cursor.getString(cursor.getColumnIndex(Constants.DATABASE.PRICE))));
flower.setInstructions(cursor.getString(cursor.getColumnIndex(Constants.DATABASE.INSTRUCTIONS)));
flower.setCategory(cursor.getString(cursor.getColumnIndex(Constants.DATABASE.CATEGORY)));
flower.setProductId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Constants.DATABASE.PRODUCT_ID))));
flowerList.add(flower);
publishFlower(flower);
} while (cursor.moveToNext());
}
}
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
mListener.onDeliverAllFlowers(flowerList);
mListener.onHideDialog();
}
});
}
public void publishFlower(final Flower flower) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
mListener.onDeliverFlower(flower);
}
});
}
}
}
and FlowerAdapter Class is
public class FlowerAdapter extends RecyclerView.Adapter<FlowerAdapter.Holder> {
private static final String TAG = FlowerAdapter.class.getSimpleName();
private final FlowerClickListener mListener;
private List<Flower> mFlowers;
public FlowerAdapter(FlowerClickListener listener) {
mFlowers = new ArrayList<>();
mListener = listener;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item, null, false);
return new Holder(row);
}
#Override
public void onBindViewHolder(Holder holder, int position) {
Flower currFlower = mFlowers.get(position);
holder.mName.setText(currFlower.getName());
holder.minstruction.setText(currFlower.getInstructions());
}
#Override
public int getItemCount() {
return mFlowers.size();
}
public void addFlower(Flower flower) {
mFlowers.add(flower);
notifyDataSetChanged();
}
/**
* #param position
* #return
*/
public Flower getSelectedFlower(int position) {
return mFlowers.get(position);
}
public void reset() {
mFlowers.clear();
notifyDataSetChanged();
}
public class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView mName, minstruction;
public Holder(View itemView) {
super(itemView);
mName = (TextView) itemView.findViewById(R.id.flowerName);
minstruction = (TextView) itemView.findViewById(R.id.flowerPrice);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
mListener.onClick(getLayoutPosition());
}
}
public interface FlowerClickListener {
void onClick(int position);
}
}
My fragment class is that I try to convert above Mainactivity code into Frament class is
public class nepali extends Fragment {
private static final String TAG = nepali.class.getSimpleName();
private RecyclerView mRecyclerView;
private RestManager mManager;
private FlowerAdapter mFlowerAdapter;
private FlowerDatabase mDatabase;
private Button mReload;
private ProgressDialog mDialog;
View view;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_data, container, false);
configViews();
mManager = new RestManager();
mDatabase = new FlowerDatabase(getActivity());
loadFlowerFeed();
mReload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadFlowerFeed();
}
});
return view;
}
private void loadFlowerFeed() {
mDialog = new ProgressDialog(getActivity());
mDialog.setMessage("Loading Flower Data...");
mDialog.setCancelable(true);
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setIndeterminate(true);
mFlowerAdapter.reset();
mDialog.show();
if (getNetworkAvailability()) {
getFeed();
} else {
getFeedFromDatabase();
}
}
private void getFeedFromDatabase() {
mDatabase.fetchFlowers(this);
}
private void configViews() {
mReload = (Button) view.findViewById(R.id.reload);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
mFlowerAdapter = new FlowerAdapter((FlowerAdapter.FlowerClickListener) this);;
mRecyclerView.setAdapter(mFlowerAdapter);
}
public void getFeed() {
Call<List<Flower>> listCall = mManager.getFlowerService().getAllFlowers();
listCall.enqueue(new Callback<List<Flower>>() {
#Override
public void onResponse(Call<List<Flower>> call, Response<List<Flower>> response) {
if (response.isSuccessful()) {
List<Flower> flowerList = response.body();
for (int i = 0; i < flowerList.size(); i++) {
Flower flower = flowerList.get(i);
SaveIntoDatabase task = new SaveIntoDatabase();
task.execute(flower);
mFlowerAdapter.addFlower(flower);
}
} else {
int sc = response.code();
switch (sc) {
case 400:
Log.e("Error 400", "Bad Request");
break;
case 404:
Log.e("Error 404", "Not Found");
break;
default:
Log.e("Error", "Generic Error");
}
}
mDialog.dismiss();
}
#Override
public void onFailure(Call<List<Flower>> call, Throwable t) {
mDialog.dismiss();
Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public boolean getNetworkAvailability() {
return Utils.isNetworkAvailable(getActivity());
}
public void onDeliverFlower(Flower flower) {
mFlowerAdapter.addFlower(flower);
}
public void onHideDialog() {
mDialog.dismiss();
}
public class SaveIntoDatabase extends AsyncTask<Flower, Void, Void> {
private final String TAG = SaveIntoDatabase.class.getSimpleName();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Flower... params) {
Flower flower = params[0];
try {
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
return null;
}
}
}
Lastly the FlowerService class is
public interface FlowerService {
#GET("/routine/first.json")
Call<List<Flower>> getAllFlowers();
}
and FlowerFetchListener Class is
public interface FlowerFetchListener {
void onDeliverAllFlowers(List<Flower> flowers);
void onDeliverFlower(Flower flower);
void onHideDialog();
}
Please Help....and Thanks in advance.
You should not call db and network from activity or fragment. Try to learn MVVM architecture and use ViewModel to store the data from db or network. You may put a lot of effort making your app work but it will still lead to crashes (especially after you introduce fragment and call db and API from there). You will need to handle your data state during configuration changes. Listen to this talk and start writing clean code https://m.youtube.com/watch?v=5qlIPTDE274
The error you get is because you pass wrong parameter into adapter constructor ‘new FlowerAdapter((FlowerAdapter.FlowerClickListener) this)’. If you want to pass a listener to the adapter you need to pass the class which implements the listener: either activity - then pass getActivity(), or fragment ‘this’ - then make fragment implement implements FlowerAdapter.FlowerClickListener.Be aware that it can be null when fragment is not attached to activity, eg configuration change.

Fingerprint AuthenticationCallback in LoginActivity

How can I call the method "loginprep" of the LoginActivityClass from the FingerPrintClass?
See in the code...I wrote in where I want to call the loginprep with: "//Here I need the method loginprep() from the LoginActivity class"
FingerprintHandler.java
public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {
private Context context;
// Constructor
public FingerprintHandler(Context mContext) {
context = mContext;
}
public void startAuth(FingerprintManager manager, FingerprintManager.CryptoObject cryptoObject) {
CancellationSignal cancellationSignal = new CancellationSignal();
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
return;
}
manager.authenticate(cryptoObject, cancellationSignal, 0, this, null);
}
#Override
public void onAuthenticationError(int errMsgId, CharSequence errString) {
Toast.makeText((Activity)context, "Fingerprint Authentication error.", Toast.LENGTH_LONG).show();
}
#Override
public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
Toast.makeText((Activity)context, "Fingerprint Authentication help.", Toast.LENGTH_LONG).show();
}
#Override
public void onAuthenticationFailed() {
Toast.makeText((Activity)context, "Fingerprint Authentication failed.", Toast.LENGTH_LONG).show();
}
#Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
//Here I need the method loginprep() from the LoginActivity class
}
}
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
public void loginprep() {
SharedPreferences sharedPreferencesF = getSharedPreferences("loginDatasFinger", Context.MODE_PRIVATE);
String urn = sharedPreferencesF.getString("username", "");
String pwd = sharedPreferencesF.getString("password", "");
loginUser(urn, pwd);
}
private void launchHomeScreen() {
Intent homeActivity = new Intent (LoginActivity.this,HomeActivity.class);
LoginActivity.this.startActivity(homeActivity);
finish();
}
public void loginUser(final String urn, final String pwd){
pd = ProgressDialog.show(LoginActivity.this, "", "Loading...");
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
System.out.println("JSON RESPONSE: " + jsonResponse.toString());
boolean success = jsonResponse.getBoolean("success");
if (success) {
launchHomeScreen();
pd.dismiss();
Toast.makeText(LoginActivity.this,"Welcome back " + urn,Toast.LENGTH_LONG).show();
SharedPreferences sharedPref = getSharedPreferences("loginDatas", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("username", urn);
editor.putString("password", pwd);
editor.apply();
}
else {
loginButton.setBackgroundColor(0x73000000);
Toast.makeText(LoginActivity.this,"Wrong Username or Password!",Toast.LENGTH_LONG).show();
pd.dismiss();
}
}
catch (JSONException e) {
loginButton.setBackgroundColor(0x73000000);
e.printStackTrace();
pd.dismiss();
Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loginButton.setBackgroundColor(0x73000000);
pd.dismiss();
System.out.println("Error: " + error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<>();
params.put(KEY_USERNAME,urn);
params.put(KEY_PASSWORD,pwd);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Following:
MainActivity mActivity = new MainActivity();
this is not the way Android is expecting you to create new instances of an activity, normally you wait the onCreate callback as described in the activity lifeCycle...
no following that approach you will need another way to communicate 2 different activities, what way must be taken depends on the specific arch of your application... the most commonly implemented could be using self defined interfaces and implement you custom callbacks...
You're writing a FingerPrint callback class, which means there is some onAuthenticationSucceeded method that is called when the "authentication succeeds."
How about you implement your own callback to pass back into the LoginActivity?
In other words, you'd
1) Write an interface
public interface LoginListener {
void onLoginSuccess();
void onLoginFailed();
}
2) Have the Activity implements LoginListener and have the Activity method of onLogin do your non-static stuff with the SharedPreferences,
public class LoginActivity extends AppCompatActivity
implements LoginListener {
public static final String KEY_USERNAME = "username";
public static final String KEY_PASS = "password";
private FingerprintHandler fingerprintHandler;
#Override
public void onLoginFailed() { }
#Override
public void onLoginSuccess() {
SharedPreferences sharedPrefs = getSharedPreferences("loginDatasFinger", Context.MODE_PRIVATE);
String urn = sharedPrefs.getString(KEY_USERNAME, "");
String pwd = sharedPrefs.getString(KEY_PASS, "");
loginUser(urn, pwd);
}
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_login);
fingerprintHandler = new FingerprintHandler(this);
}
// public void loginUser(final String urn, final String pwd){ }
}
3) Expect to pass in a LoginListener as a parameter to that separate class.
public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {
private final Context mContext;
private LoginListener mListener;
// Constructor
public FingerprintHandler(Context context) {
mContext = context;
if (context instanceof LoginListener) {
this.mListener = (LoginListener) context;
} else {
throw new ClassCastException("FingerprintHandler: context must implement LoginListener!");
}
}
4) And you do then can use your callback from the other callback.
#Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
if (mListener != null) {
mListener.onLoginSuccess();
}
}

Pass a method through/as a parameter - ANDROID

I have 2 classes:
TelaCadastroRestaurante (extends Activity) and Metodos (doesn't extends Activity).
On my first class i have this: http://i.imgur.com/N0jrjc1.png
On my second class i have this: http://i.imgur.com/PimEoxr.png
So, What do i want to? In my method caixaCerteza(), i want pass the method mandarNuvem() through/as PARAMETER 3.
public class TelaCadastroRestaurante extends Activity {
private EditText nomeRestaurante, emailRestaurante, telefoneRestaurante;
private Button buttonProximo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tela_cadastro_restaurante);
incializarComponentes();
acaoBotoes();
}
public void incializarComponentes() {
nomeRestaurante = (EditText) findViewById(R.id.editTextNomeRestauranteTelaCadastroRestaurante);
emailRestaurante = (EditText) findViewById(R.id.editTextEmailRestauranteTelaCadastroRestaurante);
telefoneRestaurante = (EditText) findViewById(R.id.editTextTelefoneRestauranteTelaCadastroRestaurante);
buttonProximo = (Button) findViewById(R.id.buttonProximoTelaCadastroRestaurante);
}
public void acaoBotoes() {
buttonProximo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pegarValores();
callMandarNuvem();
}
});
}
public void pegarValores(){
final Restaurante rest = new Restaurante();
rest.setNomeRest(nomeRestaurante.getText().toString());
rest.setEmailRest(emailRestaurante.getText().toString());
rest.setTelefoneRest(Integer.parseInt(telefoneRestaurante.getText().toString()));
}
public void callMandarNuvem(){
Metodos.caixaCerteza(TelaCadastroRestaurante.this,
"Você tem certeza que deseja cadastrar o restaurante " + nomeRestaurante.getText().toString() + "?",
Metodos.mandarNuvem(TelaCadastroRestaurante.this));
}
}
public class Metodos {
private static ProgressDialog dialog;
// Metodo que mostra o Aguarde a verificação
public static void taskInProgres(boolean mostrar, Context context) {
if (dialog == null) {
dialog = new ProgressDialog(context);
dialog = ProgressDialog.show(context, "","Espere um momento...", true);
}
if (mostrar) {
dialog.show();
} else {
dialog.dismiss();
}
}
// Metodo que mostra a caixa de certeza
public static void caixaCerteza(final Context context, final String texto, final Metodos metodo) {
AlertDialog.Builder builderaction = new AlertDialog.Builder(context);
builderaction.setTitle("Atenção!");
builderaction.setMessage(texto);
builderaction.setPositiveButton("Sim",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builderaction.setNegativeButton("Não",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builderaction.create();
alert.setIcon(R.drawable.ic_stop);
alert.show();
}
public static void mandarNuvem(final Context context){
Metodos.taskInProgres(true, context);
Restaurante rest = new Restaurante();
ParseObject restauranteParse = new ParseObject("Restaurante");
restauranteParse.put("nomeRestaurante", rest.getNomeRest());
restauranteParse.put("emailRestaurante", rest.getEmailRest());
restauranteParse.put("telefoneRestaurante", rest.getTelefoneRest());
restauranteParse.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(context,"Salvo com sucesso!", Toast.LENGTH_SHORT).show();
Metodos.taskInProgres(false, context);
} else {
Toast.makeText(context, e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
}
You can't pass a method, but an object containing a method. This means maybe slightly more code. Call caixaCerteza with something like
caixaCerteza(..., ..., new Callable() {
#Override
public void call() {
mandarNuvem();
}
});
In method caixaCerteza(..., ..., Callable callable), execute the method with
callable.call();
EDIT:
This can even be simplified if the method mandarNuvem can be put in a class that implements some interface/extends a superclass (for example, Callable) that can then serve as a third parameter of caixaCerteza directly (instead of wrapping it in an anonymous Callable object).

Categories

Resources