onSupportNavigateUp() function not working? - android

All my pages use onSupportNavigateUp() function with the same method and it's working. However when I tried to implement in my LessonActivity.java it's not working. Any ideas? It's it because of WebView?
My current working codes for LessonActivity.java:
package com.activity.lesson;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatRatingBar;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
import com.google.firebase.database.ValueEventListener;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.material.components.R;
import com.material.components.activity.pastyears.PastYears;
import com.material.components.activity.practice.Practice;
import com.material.components.adapter.AdapterQuestionToTeacher;
import com.material.components.model.Lessons;
import com.material.components.model.QuestionsToTeacher;
import com.material.components.model.SubChapter;
import com.material.components.utils.Tools;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class LessonActivity extends AppCompatActivity{
public WebView contentWebView;
public ProgressBar progressBar;
public String chapterTitle;
private SharedPreferences analysisSharedPreferences;
private SharedPreferences.Editor editorAnalysisPreferences;
private BottomSheetBehavior mBehavior;
private BottomSheetDialog mBottomSheetDialog;
private View bottom_sheet;
private BottomNavigationView navigation;
public ArrayList<QuestionsToTeacher> questionsToTeacherList = new ArrayList<>();
private AdapterQuestionToTeacher adapterQuestionToTeacher;
private RecyclerView questionListRecyclerView;
private String subjectId;
private String chapterId;
private String subchapterId;
private TextView question_content;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lesson);
contentWebView = findViewById(R.id.contentWebView);
progressBar = findViewById(R.id.progressBarContent);
question_content = findViewById(R.id.question_content);
Tools.setSystemBarColor(this,R.color.black);
String qContent = question_content.getText().toString().trim();
if(qContent.isEmpty())
{
question_content.setVisibility(View.GONE);
}else
{
question_content.setVisibility(View.VISIBLE);
}
initToolbar();
String subChapterId = getIntent().getStringExtra("subchapter_id");
getLessonData(subChapterId);
analysisSharedPreferences = getApplicationContext().getSharedPreferences("AnalysisSharedPreferences",MODE_PRIVATE);
editorAnalysisPreferences = analysisSharedPreferences.edit();
subjectId = analysisSharedPreferences.getString("subjectId","");
chapterId = analysisSharedPreferences.getString("chapterId","");
subchapterId = analysisSharedPreferences.getString("subchapterId","");
bottom_sheet = findViewById(R.id.bottom_sheet);
mBehavior = BottomSheetBehavior.from(bottom_sheet);
navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_question_list:
showQuestionList();
return true;
}
return false;
}
});
}
private void getQuestionList() {
GsonBuilder builder = new GsonBuilder();
final Gson gson = builder.create();
questionsToTeacherList.clear();
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = firebaseDatabase.getReference();
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
databaseReference.child("ask_teachers/students/"+firebaseAuth.getUid()+"/subjects/"+subjectId+"/chapters/"+chapterId+"/subchapters/"+subchapterId+"/questions").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot: dataSnapshot.getChildren())
{
String dataReceived = gson.toJson(snapshot.getValue());
System.out.println(snapshot.getValue());
QuestionsToTeacher questionsToTeacher = gson.fromJson(dataReceived,QuestionsToTeacher.class);
questionsToTeacherList.add(questionsToTeacher);
}
adapterQuestionToTeacher.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showQuestionList() {
if (mBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
mBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
final View view = getLayoutInflater().inflate(R.layout.sheet_question_list, null);
adapterQuestionToTeacher = new AdapterQuestionToTeacher(questionsToTeacherList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(LessonActivity.this);
questionListRecyclerView = view.findViewById(R.id.questionListRecyclerView);
questionListRecyclerView.setItemAnimator(new DefaultItemAnimator());
questionListRecyclerView.setNestedScrollingEnabled(false);
questionListRecyclerView.setHasFixedSize(true);
questionListRecyclerView.setLayoutManager(layoutManager);
questionListRecyclerView.setAdapter(adapterQuestionToTeacher);
adapterQuestionToTeacher.setOnClickListener(new AdapterQuestionToTeacher.OnClickListener() {
#Override
public void onItemClick(View view, QuestionsToTeacher obj, int pos) {
question_content.setVisibility(View.VISIBLE);
question_content.setText(obj.messages);
mBottomSheetDialog.dismiss();
}
});
(view.findViewById(R.id.bt_close)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mBottomSheetDialog.dismiss();
}
});
mBottomSheetDialog = new BottomSheetDialog(this);
mBottomSheetDialog.setContentView(view);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBottomSheetDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
mBottomSheetDialog.show();
mBottomSheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
mBottomSheetDialog = null;
}
});
getQuestionList();
}
private void getLessonData(String subChapterId)
{
FirebaseDatabase.getInstance().getReference().child("lessons/"+subChapterId+"/lessons_data")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String lessonDisplay = "";
for(DataSnapshot snapshot: dataSnapshot.getChildren())
{
System.out.println("lesson_inner_content");
System.out.println(snapshot.getValue());
lessonDisplay += snapshot.getValue();
}
contentWebView.getSettings().setJavaScriptEnabled(true);
contentWebView.setWebViewClient(new AppWebViewClients(progressBar));
contentWebView.loadData(String.valueOf(lessonDisplay),"text/html", "UTF-8");
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public class AppWebViewClients extends WebViewClient {
private ProgressBar progressBar;
public AppWebViewClients(ProgressBar progressBar) {
this.progressBar=progressBar;
progressBar.setVisibility(View.VISIBLE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
private void initToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
chapterTitle = getIntent().getStringExtra("subChapterTitle");
setTitle(chapterTitle);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
public void openSubMenu(View v)
{
PopupMenu popup = new PopupMenu(v.getContext(), v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_lesson_more, popup.getMenu());
popup.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_lesson,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.askTeacher)
{
showQuestionEntryDialog();
}
if(id == R.id.practice)
{
Intent gotoPractice = new Intent(LessonActivity.this, Practice.class);
startActivity(gotoPractice);
}
if(id == R.id.pastYears)
{
Intent gotoPastYears = new Intent(LessonActivity.this, PastYears.class);
startActivity(gotoPastYears);
}
return true;
}
private void showQuestionEntryDialog() {
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // before
dialog.setContentView(R.layout.dialog_ask_teacher_question_entry);
dialog.setCancelable(true);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
final EditText et_post = dialog.findViewById(R.id.et_post);
dialog.findViewById(R.id.bt_cancel).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.findViewById(R.id.bt_submit).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String review = et_post.getText().toString().trim();
if (review.isEmpty()) {
Toast.makeText(getApplicationContext(), "Please fill review text", Toast.LENGTH_SHORT).show();
}else
{
submitQuestion(review, dialog);
}
}
});
dialog.show();
dialog.getWindow().setAttributes(lp);
}
private void submitQuestion(String message, final Dialog dialog)
{
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String uuid = currentFirebaseUser.getUid();
DatabaseReference databaseReference = firebaseDatabase.getReference();
HashMap<Object,Object> messagesData = new HashMap<>();
messagesData.put("subject_id",subjectId);
messagesData.put("chapter_id",chapterId);
messagesData.put("subchapter_id",subchapterId);
messagesData.put("messages",message);
messagesData.put("status","pending");
messagesData.put("dt_added", ServerValue.TIMESTAMP);
databaseReference.child("ask_teachers/students/"+uuid+"/subjects/"+subjectId+"/chapters/"+chapterId+"/subchapters/"+subchapterId+"/questions/").push().setValue(messagesData, new DatabaseReference.CompletionListener(){
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
Toast.makeText(LessonActivity.this, "Successfully added to Ask Teacher list", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
}
}

onSupportNavigateUp() is not working because you're also overriding onOptionsItemSelected(). Since you return true; from onOptionsItemSelected(), you basically tell Android that you handle all item clicks by yourself and it doesn't need to do something.
You have two options now. Either call super.onOptionsItemSelected() like:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.askTeacher) {
showQuestionEntryDialog();
return true; // don't forget to return true after your action
}
// ... handle all your other items
return super.onOptionsItemSelected(item);
}
Or you handle the back button click by yourself:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// navigate up on back button click
if (id == android.R.id.home) {
NavUtils.navigateUpFromSameTask(this);
return true;
}
// ... handle all your other items
return true;
}
By the way, I think overriding onSupportNavigateUp() is not needed at all. Up navigation works "out of the box" (at least for me), as long as I don't override onOptionsItemSelected() or call super.onOptionsItemSelected(item); from within it.

Related

Firebase error after published to play store [duplicate]

This question already has answers here:
Firebase No properties to serialize found on class
(12 answers)
Firebase release apk not loading data
(3 answers)
Firebase AndroidChat release build error
(3 answers)
Closed 2 years ago.
On my android studio debug theres nothing problem, but when i publish the app to playstore my app was close after splashscreen. my apps using firebase, and i have to added SHA-1 from playstore to my firebase project. but still cant crash :
this error i got from play console :
com.google.firebase.database.DatabaseException:
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.<init> (CustomClassMapper.java:11)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.loadOrCreateBeanMapperForClass (CustomClassMapper.java)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean (CustomClassMapper.java:4)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass (CustomClassMapper.java:4)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass (CustomClassMapper.java:8)
at com.google.firebase.database.DataSnapshot.getValue (DataSnapshot.java:8)
at com.kepulcorporation.kepul.HomeFragment$10.onDataChange (HomeFragment.java:8)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent (ValueEventRegistration.java:2)
at com.google.firebase.database.core.view.DataEvent.fire (DataEvent.java)
at com.google.firebase.database.core.view.EventRaiser$1.run (EventRaiser.java:6)
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:6121)
at java.lang.reflect.Method.invoke (Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:779)
this is my main activity :
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Registry;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.module.AppGlideModule;
import com.firebase.ui.storage.images.FirebaseImageLoader;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.storage.StorageReference;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private ActionBar actionBar;
private NestedScrollView nested_scroll_view;
private BottomSheetBehavior mBehavior;
private BottomSheetDialog mBottomSheetDialog;
private View bottom_sheet;
private HorizontalScrollView horizontalScrollView;
private Fragment fragment;
private Fragment fragmenthome;
private SessionManager sessionManager;
RelativeLayout toolbar;
LinearLayout content;
NestedScrollView scrolllayout;
ImageView home_icon, transaksi_icon, bantuan_icon, akun_icon;
TextView home_text, transaksi_text, bantuan_text, akun_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
content = findViewById(R.id.list_category_item_dashboard);
scrolllayout = findViewById(R.id.nested_scroll_view);
//Set Theme
Tools.setSystemBarColor(this, R.color.colorPrimary);
sessionManager = new SessionManager(this);
sessionManager.checkLogin(this);
home_icon = findViewById(R.id.home_icon);
transaksi_icon = findViewById(R.id.transaksi_icon);
bantuan_icon = findViewById(R.id.bantuan_icon);
akun_icon = findViewById(R.id.akun_icon);
home_text = findViewById(R.id.home_text);
transaksi_text = findViewById(R.id.transaksi_text);
bantuan_text = findViewById(R.id.bantuan_text);
akun_text = findViewById(R.id.akun_text);
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
#Override
public void onComplete(#NonNull Task<String> task) {
if (!task.isSuccessful()) {
// Toast.makeText(MainActivity.this, "Fetching FCM registration token failed", Toast.LENGTH_SHORT).show();
return;
}
// Get new FCM registration token
String token = task.getResult();
if(sessionManager.isLoggin())
{
save_fcm(token);
}
}
});
initComponent();
}
public void save_fcm(String token){
HashMap<String, String> user;
sessionManager = new SessionManager(MainActivity.this);
user = sessionManager.getUserDetail();
String email = user.get("EMAIL");
String convertemail = email.replaceAll("\\.", "_");
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference tableuser = database.getReference("Users");
tableuser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String email = user.get("EMAIL");
String convertemail = email.replaceAll("\\.", "_");
Users users = snapshot.child(convertemail).getValue(Users.class);
Map<String, Object> updates = new HashMap<String,Object>();
updates.put("address", users.getAddress());
updates.put("email", email);
updates.put("name", users.getName());
updates.put("password", users.getPassword());
updates.put("phone", users.getPhone());
updates.put("photo_profile_path", users.getPhoto_profile_path());
updates.put("role_id", users.getRole_id());
updates.put("point", users.getPoint());
updates.put("token", token);
updates.put("promosipush", users.getPromosipush());
updates.put("promosiemail", users.getPromosiemail());
updates.put("statuspush", users.getStatuspush());
updates.put("statusemail", users.getStatusemail());
tableuser.child(convertemail).setValue(updates);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void initComponent() {
nested_scroll_view = (NestedScrollView) findViewById(R.id.nested_scroll_view);
fragment = new HomeFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
home_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
} else {
Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
public void toHome(View view) {
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
fragment = new HomeFragment();
}
else {
fragment = new HomeFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
home_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
transaksi_text.setTextColor(this.getResources().getColor(R.color.text));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
bantuan_text.setTextColor(this.getResources().getColor(R.color.text));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
akun_text.setTextColor(this.getResources().getColor(R.color.text));
}
public void toTransaksi(View view) {
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
fragment = new TransaksiloginFragment();
}
else {
fragment = new TransaksiFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
home_text.setTextColor(this.getResources().getColor(R.color.text));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
transaksi_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
bantuan_text.setTextColor(this.getResources().getColor(R.color.text));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
akun_text.setTextColor(this.getResources().getColor(R.color.text));
}
public void toBantuan(View view){
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
fragment = new BantuanFragment();
}
else {
fragment = new BantuanFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
home_text.setTextColor(this.getResources().getColor(R.color.text));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
transaksi_text.setTextColor(this.getResources().getColor(R.color.text));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
bantuan_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
akun_text.setTextColor(this.getResources().getColor(R.color.text));
}
public void toAkun(View view){
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
fragment = new AkunLoginFragment();
}
else {
fragment = new AkunFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
home_text.setTextColor(this.getResources().getColor(R.color.text));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
transaksi_text.setTextColor(this.getResources().getColor(R.color.text));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
bantuan_text.setTextColor(this.getResources().getColor(R.color.text));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
akun_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
}
public void toSell(View view) {
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
startActivity(new Intent(MainActivity.this, JualsampahActivity.class));
}
else {
fragment = new JualFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
home_text.setTextColor(this.getResources().getColor(R.color.text));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
transaksi_text.setTextColor(this.getResources().getColor(R.color.text));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
bantuan_text.setTextColor(this.getResources().getColor(R.color.text));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
akun_text.setTextColor(this.getResources().getColor(R.color.text));
}
}
and this my HomeFragment :
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.github.islamkhsh.CardSliderViewPager;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import org.w3c.dom.Text;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
import ru.tinkoff.scrollingpagerindicator.ScrollingPagerIndicator;
public class HomeFragment extends Fragment {
CardSliderViewPager cardSliderViewPager;
private List<Category>listData;
private List<Produk>listData1;
private List<SliderData>sliderData;
private RecyclerView rv;
private CategoryAdapter adapter;
private ProdukAdapter adapter1;
private SliderAdapter sliderAdapter;
private RecyclerView recyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View root = inflater.inflate(R.layout.fragment_home, container, false);
cardSliderViewPager = root.findViewById(R.id.viewPager);
recyclerView = root.findViewById(R.id.product_recyclerview);
rv = root.findViewById(R.id.category_recyclerview);
rv.setHasFixedSize(true);
rv.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
listData=new ArrayList<>();
listData1 = new ArrayList<>();
sliderData = new ArrayList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference table = database.getReference("Category");
table.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(isAdded())
{
listData.clear();
for (DataSnapshot npsnapshot : snapshot.getChildren()){
Category l = npsnapshot.getValue(Category.class);
listData.add(l);
}
adapter=new CategoryAdapter(listData);
rv.setAdapter(adapter);
ScrollingPagerIndicator recyclerIndicator = root.findViewById(R.id.indicator2);
recyclerIndicator.attachToRecyclerView(rv);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
final SessionManager sessionManager = new SessionManager(getActivity());
HashMap<String, String> user = sessionManager.getUserDetail();
String email = user.get("EMAIL");
if(!sessionManager.isLoggin())
{
LinearLayout not_login = root.findViewById(R.id.not_login);
LinearLayout login = root.findViewById(R.id.login);
not_login.setVisibility(View.VISIBLE);
login.setVisibility(View.GONE);
}
else {
LinearLayout not_login = root.findViewById(R.id.not_login);
LinearLayout login = root.findViewById(R.id.login);
not_login.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
FirebaseDatabase databaseuser = FirebaseDatabase.getInstance();
DatabaseReference tableuseruser = databaseuser.getReference("Users");
tableuseruser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(isAdded())
{
String convertemail = email.toString().replaceAll("\\.", "_").toString();
Users users = snapshot.child(convertemail).getValue(Users.class);
TextView point = root.findViewById(R.id.profile_point);
TextView name = root.findViewById(R.id.profile_name);
CircleImageView circleImageView = root.findViewById(R.id.profile_image);
name.setText(user.get("NAME"));
point.setText(users.getPoint().toString() + " Point");
if (user.get("PHOTO_PROFILE_PATH").equals(""))
{
Glide.with(getContext()).load("https://cdn.business2community.com/wp-content/uploads/2017/08/blank-profile-picture-973460_640.png").into(circleImageView);
}
else {
Glide.with(getContext()).load(user.get("PHOTO_PROFILE_PATH")).into(circleImageView);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
getbanner();
FirebaseDatabase databasepro = FirebaseDatabase.getInstance();
DatabaseReference tablepro = databasepro.getReference("Product");
tablepro.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(isAdded())
{
listData1.clear();
for (DataSnapshot npsnapshot : snapshot.getChildren()){
Produk l = npsnapshot.getValue(Produk.class);
listData1.add(l);
}
adapter1 = new ProdukAdapter((ArrayList<Produk>) listData1);
recyclerView.setAdapter(adapter1);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
LinearLayout jual = root.findViewById(R.id.btn_jual);
LinearLayout sedekah = root.findViewById(R.id.btn_sedekah);
LinearLayout baitullah = root.findViewById(R.id.btn_baitullah);
ImageView notif = root.findViewById(R.id.notif);
ReddotNotif reddotNotif = new ReddotNotif(getContext());
if(reddotNotif.isRedDot())
{
notif.setImageResource(R.drawable.ic_notify);
}
else {
notif.setImageResource(R.drawable.ic_notif);
}
notif.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
reddotNotif.logout();
startActivity(new Intent(getActivity(), HistorynotificationActivity.class));
}
});
baitullah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(sessionManager.isLoggin())
{
startActivity(new Intent(getActivity(), MenujubaitullahActivity.class));
}
else {
Intent intent = new Intent(getActivity(), MustloginActivity.class);
intent.putExtra("type", "baitullah");
startActivity(intent);
}
}
});
jual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sessionManager.isLoggin())
{
startActivity(new Intent(getActivity(), JualsampahActivity.class));
}
else {
Intent intent = new Intent(getActivity(), MustloginActivity.class);
intent.putExtra("type", "jual");
startActivity(intent);
}
}
});
sedekah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Boolean login = false;
if(sessionManager.isLoggin())
{
startActivity(new Intent(getActivity(), SedekahsampahActivity.class));
}
else {
Intent intent = new Intent(getActivity(), MustloginActivity.class);
intent.putExtra("type", "sedekah");
startActivity(intent);
}
}
});
Button login = root.findViewById(R.id.login_button);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), LoginActivity.class));
}
});
TextView FAQ = root.findViewById(R.id.faq);
String FAQTEXT = "Untuk informasi lebih lanjut, kunjungi halaman FAQ. <font color=#0098FF>di sini </font> ";
FAQ.setText(Html.fromHtml(FAQTEXT));
FAQ.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), FaqActivity.class));
}
});
return root;
}
private void getbanner() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference table = database.getReference("Banner");
table.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(isAdded())
{
sliderData.clear();
for (DataSnapshot npsnapshot : snapshot.getChildren()){
SliderData l = npsnapshot.getValue(SliderData.class);
sliderData.add(l);
}
sliderAdapter = new SliderAdapter((ArrayList<SliderData>) sliderData);
cardSliderViewPager.setAdapter(sliderAdapter);
cardSliderViewPager.setSmallScaleFactor(0.9f);
cardSliderViewPager.setSmallAlphaFactor(0.5f);
cardSliderViewPager.setAutoSlideTime(5);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
this my Category class :
public class Category {
private String id;
private String name;
private String picture_path;
public Category(){
}
public Category(String id, String name, String picture_path) {
this.id = id;
this.name = name;
this.picture_path = picture_path;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPicture_path() {
return picture_path;
}
public void setPicture_path(String picture_path) {
this.picture_path = picture_path;
}
}
and this category at database :
category database
can you help me please, I've been looking for a week where it went wrong, but still can't find it.

Get Acknowledge in Fragment from MainActivity, when my menu filter (sorting in MainActivity) is clicked

I have menu item in MainActivity it is filter(sort), I want that if user click on filter menu like A-z or z-a, in my MainActivity's onclick it is clicked but i want to get acknowledge in fragments as well
[nhewuhfduehiuhuewhucuewcueucueuncneincineincinencneincineinciniencineicnnecnnecneicniencnnecncncncnicnincincncnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnncncicieicieicicnicnncncicn]
code:
MainActivity:
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.TextAppearanceSpan;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.tabs.TabLayout;
import com.tekitsolutions.remindme.Adapter.ReminderListAdapter;
import com.tekitsolutions.remindme.Adapter.ViewPagerAdapter;
import com.tekitsolutions.remindme.Fragment.HomeFragment;
import com.tekitsolutions.remindme.Fragment.OfficeFragment;
import com.tekitsolutions.remindme.Fragment.OtherFragment;
import com.tekitsolutions.remindme.Interface.AdapterInterface;
import com.tekitsolutions.remindme.Interface.HamburgerMenuInterface;
import com.tekitsolutions.remindme.Interface.MenuItemListener;
import com.tekitsolutions.remindme.Interface.SearchListener;
import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.ParticularPayment;
import com.tekitsolutions.remindme.Model.Profile;
import com.tekitsolutions.remindme.Model.Reminder;
import com.tekitsolutions.remindme.R;
import com.tekitsolutions.remindme.RestApi.ApiClient;
import com.tekitsolutions.remindme.RestApi.ApiInterface;
import com.tekitsolutions.remindme.Sql.DatabaseAdapter;
import com.tekitsolutions.remindme.Utils.RemindMe;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.tekitsolutions.remindme.Utils.CommonUtils.CREATE_PASSCODE_ACTIVITY;
import static com.tekitsolutions.remindme.Utils.CommonUtils.GET_PROFILE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.IMAGE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PHONE_NUMBER;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PICK_SEARCH;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PROFILE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.USERNAME;
public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener, AdapterInterface, HamburgerMenuInterface, SearchListener, MenuItemListener {
private static final String TAG = MainActivity.class.getSimpleName();
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.recycler_view)
RecyclerView listView;
private String phoneNum = null, getImage = null, getUsername = null;
private int first = 0, position = 0;
private ActionBar actionBar;
private DatabaseAdapter dbAdapter;
private ReminderListAdapter listAdapter;
private List<Reminder> listItems = new ArrayList<>();
private TabLayout tabLayout;
private ViewPager viewPager;
private MenuItemListener searchListener;
private DrawerLayout drawer;
private SharedPreferences profilePreference;
private TextView navUsername, navMobile;
private ImageView navImage;
private View headerView;
private NavigationView navigationView;
private SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
CREATE_PASSCODE_ACTIVITY = 0;
setThemeAndLoadLocale(MainActivity.this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
ButterKnife.bind(this);
setToolbar(toolbar, getString(R.string.app_name));
profilePreference = getSharedPreferences(PROFILE, MODE_PRIVATE);
getDataPhoneNumber();
tabLayout = findViewById(R.id.tab_layout);
viewPager = findViewById(R.id.view_pager);
drawer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
headerView = navigationView.getHeaderView(0);
navUsername = headerView.findViewById(R.id.profile_name);
navMobile = headerView.findViewById(R.id.mobile_number);
navImage = headerView.findViewById(R.id.profile_image);
if (!phoneNum.isEmpty()) {
first = 1;
getProfileData();
}
Menu menu = navigationView.getMenu();
MenuItem tools = menu.findItem(R.id.nav_general_setting);
SpannableString s = new SpannableString(tools.getTitle());
s.setSpan(new TextAppearanceSpan(this, R.style.nav_header_color), 0, s.length(), 0);
tools.setTitle(s);
Menu menu2 = navigationView.getMenu();
MenuItem tools2 = menu2.findItem(R.id.nav_communicate);
SpannableString s2 = new SpannableString(tools2.getTitle());
s2.setSpan(new TextAppearanceSpan(this, R.style.nav_header_color), 0, s2.length(), 0);
tools2.setTitle(s2);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.AddFragment(new HomeFragment(), getResources().getString(R.string.fragment_home));
adapter.AddFragment(new OfficeFragment(), getResources().getString(R.string.fragment_office));
adapter.AddFragment(new OtherFragment(), getResources().getString(R.string.fragment_other));
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
listAdapter = new ReminderListAdapter(this, listItems, MainActivity.this, this, this);
listView.setHasFixedSize(true);
final LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(this);
listView.setLayoutManager(mLayoutManager);
listView.setItemAnimator(new DefaultItemAnimator());
try {
listView.setAdapter(listAdapter);
} catch (Exception exp) {
exp.printStackTrace();
}
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, AddReminderActivity.class));
}
});
dbAdapter = new DatabaseAdapter(this);
HomeFragment homeFragment = new HomeFragment();
homeFragment.setListener(this);
}
#Override
public void onClickFavoriteById(int isFavorite, long id) {
}
private void setData() {
if (getUsername != null && !getUsername.isEmpty()) {
navUsername.setText(getUsername.trim());
}
if (phoneNum != null && !phoneNum.isEmpty()) {
navMobile.setVisibility(View.VISIBLE);
navMobile.setText(phoneNum);
}
if (getImage != null && !getImage.isEmpty()) {
Bitmap bitmap = convertBase64ToBitMap(getImage);
navImage.setImageBitmap(bitmap);
} else {
navImage.setImageResource(R.drawable.user_image);
}
}
private void storeInSharedPreference() {
editor = getSharedPreferences(PROFILE, MODE_PRIVATE).edit();
editor.putString(USERNAME, getUsername);
editor.putString(IMAGE, getImage);
editor.apply();
}
private void getProfileData() {
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<List<Profile>> profileDetails = apiInterface.getProfileDetails(phoneNum);
profileDetails.enqueue(new Callback<List<Profile>>() {
#Override
public void onResponse(Call<List<Profile>> call, Response<List<Profile>> response) {
int statusCode = response.code();
if (statusCode == 200) {
List<Profile> responseList = response.body();
Profile profile = responseList.get(0);
showLog("username: " + profile.getProfileName());
getUsername = profile.getProfileName();
if (getUsername == null) {
showLog("Null");
} else {
showLog("Not null");
}
getImage = profile.getImage();
phoneNum = profile.getProfileNo();
setData();
storeInSharedPreference();
}
}
#Override
public void onFailure(Call<List<Profile>> call, Throwable t) {
showLog("Failed: " + t.getMessage());
}
});
}
private void getDataFromSharedPref() {
phoneNum = profilePreference.getString(PHONE_NUMBER, "");
getUsername = profilePreference.getString(USERNAME, "");
getImage = profilePreference.getString(IMAGE, "");
}
private void getDataPhoneNumber() {
phoneNum = profilePreference.getString(PHONE_NUMBER, "");
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Intent intent = null;
switch (item.getItemId()) {
case R.id.nav_profile:
intent = new Intent(this, ProfileActivity.class);
intent.putExtra(GET_PROFILE, true);
intent.putExtra(IMAGE, getImage);
intent.putExtra(USERNAME, getUsername);
startActivity(intent);
break;
case R.id.nav_favorite:
intent = new Intent(MainActivity.this, AddFavoriteReminder.class);
startActivity(intent);
break;
case R.id.nav_setting:
intent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent);
break;
case R.id.nav_passcode:
intent = new Intent(this, PasscodeActivity.class);
startActivity(intent);
break;
case R.id.nav_share:
String link = "https://drive.google.com/drive/folders/1sDS_hGb5s5SjyDIK3me3oY8cS1Oo1I4F?usp=sharing";
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
SpannableString ss = new SpannableString("Android is a Software stack");
String shareBodyText = link;
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBodyText);
startActivity(Intent.createChooser(sharingIntent, "Sharing Option"));
return true;
case R.id.nav_help:
intent = new Intent(MainActivity.this, HelpActivity.class);
startActivity(intent);
break;
case R.id.nav_feedback:
intent = new Intent(Intent.ACTION_SENDTO);
intent.setType("message/rfc822");
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"jimmytrivedi#outlook.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Remind Me Feedback");
intent.putExtra(Intent.EXTRA_TEXT, "Developer Team,");
try {
startActivity(Intent.createChooser(intent, "Send Email"));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public void onClickReminderList(int position) {
}
private Bitmap convertBase64ToBitMap(String profileImage) {
try {
byte[] encodeByte = Base64.decode(profileImage, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch (Exception e) {
showLog("" + e.getMessage());
return null;
}
}
#Override
protected void onResume() {
super.onResume();
CREATE_PASSCODE_ACTIVITY = 0;
if (RemindMe.isChanged()) {
RemindMe.setChanged(false);
recreate();
}
getDataFromSharedPref();
setData();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.search:
Intent intent = new Intent(MainActivity.this, SearchActivity.class);
startActivityForResult(intent, PICK_SEARCH);
break;
case R.id.filter:
break;
case R.id.ascending:
position = 1;
break;
case R.id.descending:
position = 2;
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_fragment_search, menu);
getMenuInflater().inflate(R.menu.menu_filter, menu);
return true;
}
#Override
public void onClickHamburger(long id) {
}
#Override
public void onClickListItem(int position) {
}
#Override
public void setToolbar(Toolbar toolBar, String title) {
super.setToolbar(toolBar, title);
}
private void showLog(String msg) {
Log.d(TAG, msg);
}
#Override
public void onSelectedProviderSearchItem(General general) {
}
#Override
public void onSelectedParticularPaymentSearchItem(ParticularPayment particularPayment) {
}
#Override
public void onSelectedReminderSearchItem(Reminder reminder) {
}
#Override
public void unused(int position) {
}
#Override
public void onFilterItem(int position) {
}
}
Interface
MenuItemListener
import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.ParticularPayment;
import com.tekitsolutions.remindme.Model.Reminder;
public interface MenuItemListener {
void onFilterItem(int position);
}
HomeFragment:
package com.tekitsolutions.remindme.Fragment;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.tekitsolutions.remindme.Activity.AddReminderActivity;
import com.tekitsolutions.remindme.Activity.MainActivity;
import com.tekitsolutions.remindme.Activity.ReminderDetailActivity;
import com.tekitsolutions.remindme.Adapter.ReminderListAdapter;
import com.tekitsolutions.remindme.Interface.AdapterInterface;
import com.tekitsolutions.remindme.Interface.HamburgerMenuInterface;
import com.tekitsolutions.remindme.Interface.MenuItemListener;
import com.tekitsolutions.remindme.Interface.SearchListener;
import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.ParticularPayment;
import com.tekitsolutions.remindme.Model.Reminder;
import com.tekitsolutions.remindme.R;
import com.tekitsolutions.remindme.Receiver.AlarmReceiver;
import com.tekitsolutions.remindme.RestApi.ApiClient;
import com.tekitsolutions.remindme.RestApi.ApiInterface;
import com.tekitsolutions.remindme.Sql.DatabaseAdapter;
import com.tekitsolutions.remindme.Utils.RecyclerViewClickListener;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_FAVORITE;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_ID;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_TYPE_ID;
import static com.tekitsolutions.remindme.Utils.CommonUtils.HOME;
import static com.tekitsolutions.remindme.Utils.CommonUtils.IS_EDIT;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PICK_HOME;
public class HomeFragment extends Fragment implements AdapterInterface, HamburgerMenuInterface, Callback<String>, SearchListener, MenuItemListener {
private static final String TAG = HomeFragment.class.getSimpleName();
public MainActivity activity;
public Context context;
View view;
private DatabaseAdapter dbAdapter;
private List<Reminder> listItems = new ArrayList<>();
private ReminderListAdapter listAdapter;
private MenuItemListener menuItemListener;
private RecyclerView listView;
private TextView tvNoData;
private AdapterInterface listener;
private HamburgerMenuInterface menuInterface;
private AlertDialog.Builder builder;
private Reminder reminder;
private long reminderId = 0;
private int getFavorite = 0;
public HomeFragment() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.home_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView = view.findViewById(R.id.recycler_view);
tvNoData = view.findViewById(R.id.tv_no_data);
dbAdapter = new DatabaseAdapter(getContext());
listAdapter = new ReminderListAdapter(getActivity(), listItems, HomeFragment.this, this, this);
listView.setHasFixedSize(false);
final LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(getActivity());
listView.setLayoutManager(mLayoutManager);
listView.setItemAnimator(new DefaultItemAnimator());
try {
listView.setAdapter(listAdapter);
} catch (Exception exp) {
exp.printStackTrace();
}
listView.addOnItemTouchListener(new RecyclerViewClickListener.RecyclerTouchListener(getContext(),
listView, new RecyclerViewClickListener.ClickListener() {
#Override
public void onClick(View view, int position) {
}
#Override
public void onLongClick(View view, int position) {
}
}
));
loadAllReminders();
}
#Override
public void onStart() {
super.onStart();
loadAllReminders();
}
private void loadAllReminders() {
listItems.clear();
List<Reminder> list = dbAdapter.getReminderById(REMINDER_TYPE_ID, HOME);
if (list.size() > 0) {
tvNoData.setVisibility(View.GONE);
listItems.addAll(list);
listAdapter.notifyDataSetChanged();
} else {
tvNoData.setVisibility(View.VISIBLE);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.menuItemListener = (MenuItemListener) getActivity();
}
private void showLog(String msg) {
Log.d(TAG, msg);
}
#Override
public void onFilterItem(int position) {
showLog("test: " + position);
}
public void setListener(MenuItemListener listener) {
this.menuItemListener = listener;
}
}
You can do this with EventBus or Interface. You can follow these steps for EventBus.
Implement EventBus
implementation 'org.greenrobot:eventbus:3.1.1'
EventBustDataEvents.class
public class EventBusDataEvents{
public static class isClick {
boolean isClick;
public isClick(boolean isClick) {
this.isClick = isClick;
}
public boolean getIsClick() {
return isClick;
}
public void setIsClick(boolean isClick) {
this.isClick = isClick;
}
}
}
MainActivity.class
EventBus.getDefault().postSticky(new EventBusDataEvents.isClick(true));
Fragment.class
#Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void isClick(EventBusDataEvents.isClick click) {
if (click.isClick()) {
}
}
#Override
public void onStart() {
super.onStart();
try {
EventBus.getDefault().register(this);
} catch (Exception e) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
try {
EventBus.getDefault().unregister(this);
} catch (Exception e) {
}
}
Or Interface
IMainActivity.class // interface class
public interface IMainActivity {
void onClick();}
MainActivity.class
private IMainActivity listener; //This will be described above as a field.
public void setOnEventListener(IMainActivity listener) {
IMainActivity = listener;
}
//buttonClickEvent
listener.OnClick();
Fragment.class
//onCreateView
setOnEventListener(new IMainActivity() {
#Override
public void onClick() {
}
});

Why is findViewById returning null when trying to get user info?

I have some code whose function is to show the name and age of a user in a RecyclerView but that same RecyclerView is always returning null no matter where I put it.
I tried to put getUserInfo() in onStart() and it didn't work.
I've already looked in other posts in StackOverflow and it still hasn't worked.
My MainActivity.java
package com.pap.diogo.pilltrack;
import android.accounts.Account;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
private RelativeLayout pills_layout, appoint_layout, add_pills_layout, add_appoints_layout, account_layout, add_button;
private View pills, appointments, add_pills, add_appoints, account;
private TextView AccountName0, AccountAge0;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
Home();
return true;
case R.id.navigation_pills:
Pills();
return true;
case R.id.navigation_appointment:
Appointment();
return true;
case R.id.navigation_account:
Account();
return true;
}
return false;
}
};
public MainActivity() {
}
private void Account(){
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) add_button.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.account);
pills_layout.removeView(pills);
appoint_layout.removeView(appointments);
add_pills_layout.removeView(add_pills);
add_appoints_layout.removeView(add_appoints);
//account_layout.removeAllViews();
//account_layout.addView(account);
add_button.setVisibility(View.VISIBLE);
getUserInfo();
}
private void Appointment() {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) add_button.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.add_appoints);
pills_layout.removeView(pills);
appoint_layout.removeView(appointments);
add_pills_layout.removeView(add_pills);
//account_layout.removeView(account);
add_appoints_layout.removeAllViews();
add_appoints_layout.addView(add_appoints);
add_button.setVisibility(View.VISIBLE);
}
private void Pills() {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) add_button.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.add_pills);
pills_layout.removeView(pills);
appoint_layout.removeView(appointments);
add_appoints_layout.removeView(add_appoints);
//account_layout.removeView(account);
add_pills_layout.removeAllViews();
add_pills_layout.addView(add_pills);
add_button.setVisibility(View.VISIBLE);
}
private void Home() {
add_appoints_layout.removeView(add_appoints);
add_pills_layout.removeView(add_pills);
//account_layout.removeView(account);
pills_layout.removeAllViews();
pills_layout.addView(pills);
appoint_layout.removeAllViews();
appoint_layout.addView(appointments);
add_button.setVisibility(View.GONE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pills_layout = findViewById(R.id.pills_layout);
appoint_layout = findViewById(R.id.appoint_layout);
add_pills_layout = findViewById(R.id.add_pills);
add_appoints_layout = findViewById(R.id.add_appoints);
//account_layout = findViewById(R.id.account);
add_button = findViewById(R.id.add);
AccountName0 = findViewById(R.id.AccountName0);
AccountAge0 = findViewById(R.id.AccountAge0);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
pills = inflater.inflate(R.layout.pills, null);
appointments = inflater.inflate(R.layout.appointments, null);
add_pills = inflater.inflate(R.layout.add_pills, null);
add_appoints = inflater.inflate(R.layout.add_appoint, null);
account = inflater.inflate(R.layout.account, null);
pills_layout.addView(pills);
appoint_layout.addView(appointments);
add_button.setVisibility(View.GONE);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
public void getUserInfo(){
RecyclerView accountUsers;
if ((accountUsers = account.findViewById(R.id.AccountList)) != null)
{
accountUsers.setHasFixedSize(true);
accountUsers.setLayoutManager(new LinearLayoutManager(getBaseContext()));
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final String userid = user.getUid();
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
FirebaseRecyclerOptions<AccountLayout> AccountQ = new FirebaseRecyclerOptions.Builder<AccountLayout>().setQuery(ref, AccountLayout.class).setLifecycleOwner(this).build();
FirebaseRecyclerAdapter<AccountLayout, AccountInfo> AccountAdapter = new FirebaseRecyclerAdapter<AccountLayout, AccountInfo>(AccountQ){
#NonNull
#Override
public AccountInfo onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
return new AccountInfo(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.account_layout, viewGroup, false));
}
#Override
protected void onBindViewHolder(#NonNull final AccountInfo holder, int position, #NonNull final AccountLayout model) {
ref.child(userid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
final String name = dataSnapshot.child("name").getValue().toString();
final String age = dataSnapshot.child("idade").getValue().toString();
holder.setName(name);
holder.setAge(age);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
};
accountUsers.setAdapter(AccountAdapter);
}
}
public static class AccountInfo extends RecyclerView.ViewHolder{
View AccountL;
public AccountInfo(#NonNull View itemView) {
super(itemView);
AccountL = itemView;
}
public void setName(String name){
TextView AccountName = AccountL.findViewById(R.id.AccountName0);
AccountName.setText(name);
}
public void setAge(String age){
TextView AccountAge = AccountL.findViewById(R.id.AccountAge0);
AccountAge.setText(age);
}
}
}
My AccountLayout.java
package com.pap.diogo.pilltrack;
public class AccountLayout {
private String name, idade;
public AccountLayout() {
}
public AccountLayout(String name, String idade) {
this.name = name;
this.idade = idade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdade() {
return idade;
}
public void setIdade(String idade) {
this.idade = idade;
}
}
My account.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/AccountList"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Modify your code as below:
public void getUserInfo(){
RecyclerView accountUsers = (RecyclerView) account.findViewById(R.id.AccountList);
if (accountUsers != null)
{
...

Why do i get argument might be null error?

package e.starf.project;
import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.module.AppGlideModule;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private RecyclerView postList;
private Toolbar toolbar;
private ImageButton AddNewPostButton;
private FirebaseAuth firebaseAuth;
private DatabaseReference UsersRef, PostsRef, LikesRef;
private StorageReference mStorageRef;
String currentUserID;
Boolean LikeChecker = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
LikesRef = FirebaseDatabase.getInstance().getReference().child("Likes");
UsersRef.keepSynced(true);
PostsRef.keepSynced(true);
LikesRef.keepSynced(true);
mStorageRef = FirebaseStorage.getInstance().getReference();
toolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home");
AddNewPostButton = (ImageButton) findViewById(R.id.add_new_post);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout,
R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
postList = (RecyclerView) findViewById(R.id.all_users_post_list);
postList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
postList.setLayoutManager(linearLayoutManager);
View navView = navigationView.inflateHeaderView(R.layout.navigration_header);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
AddNewPostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SendUserToPostActivity();
}
});
DisplayAllUsersPosts();
}
private void DisplayAllUsersPosts() {
final FirebaseRecyclerOptions < Posts options = new FirebaseRecyclerOptions.Builder < Posts().setQuery(PostsRef,
Posts.class).build();
FirebaseRecyclerAdapter < Posts, PostsViewHolder firebaseRecyclerAdapter = new FirebaseRecyclerAdapter < Posts,
PostsViewHolder(options) {
#NonNull
#Override
public PostsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.all_posts_layout,
viewGroup, false);
return new PostsViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull final PostsViewHolder holder, int position, #NonNull final Posts model) {
final String PostKey = getRef(position).getKey();
holder.setName(model.getName());
holder.setTime(model.getTime());
holder.setDate(model.getDate());
holder.setDescription(model.getDescription());
holder.setPostimage(getApplicationContext(), model.getPostimage());
holder.setLikeButtonStatus(PostKey);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent clickPostIntent = new Intent(MainActivity.this, ClickPostActivity.class);
clickPostIntent.putExtra("PostKey", PostKey);
startActivity(clickPostIntent);
}
});
holder.CommentPostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent clickPostIntent = new Intent(MainActivity.this, CommentsActivity.class);
clickPostIntent.putExtra("PostKey", PostKey);
startActivity(clickPostIntent);
}
});
holder.LikePostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LikeChecker = true;
if (LikeChecker) {
LikesRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (LikeChecker.equals(true)) {
if (dataSnapshot.child(PostKey).hasChild(currentUserID)) {
LikesRef.child(PostKey).child(currentUserID).removeValue();
LikeChecker = false;
} else {
LikesRef.child(PostKey).child(currentUserID).setValue(true);
LikeChecker = false;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
});
}
};
postList.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
public static class PostsViewHolder extends RecyclerView.ViewHolder {
View mView;
ImageButton LikePostButton, CommentPostButton;
TextView DisplayNoOfLikes;
int countLikes;
String currentUserID;
DatabaseReference LikesRef;
public PostsViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
LikePostButton = (ImageButton) mView.findViewById(R.id.like_button);
CommentPostButton = (ImageButton) mView.findViewById(R.id.comment_button);
DisplayNoOfLikes = (TextView) mView.findViewById(R.id.display_no_of_likes);
LikesRef = FirebaseDatabase.getInstance().getReference().child("Likes");
currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
}
public void setLikeButtonStatus(final String PostKey) {
LikesRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(PostKey).hasChild(currentUserID)) {
countLikes = (int) dataSnapshot.child(PostKey).getChildrenCount();
LikePostButton.setImageResource(R.drawable.like);
DisplayNoOfLikes.setText(Integer.toString(countLikes) + (" Likes"));
} else {
countLikes = (int) dataSnapshot.child(PostKey).getChildrenCount();
LikePostButton.setImageResource(R.drawable.dislike);
DisplayNoOfLikes.setText(Integer.toString(countLikes) + (" Likes"));
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void setName(String name) {
TextView username = (TextView) mView.findViewById(R.id.post_user_name);
username.setText(name);
}
public void setTime(String time) {
TextView PostTime = (TextView) mView.findViewById(R.id.post_time);
PostTime.setText(" " + time);
}
public void setDate(String date) {
TextView PostDate = (TextView) mView.findViewById(R.id.post_date);
PostDate.setText(" " + date);
}
public void setDescription(String description) {
TextView PostDescription = (TextView) mView.findViewById(R.id.post_question);
PostDescription.setText(description);
}
public void setPostimage(Context ctx, String postimage) {
ImageView PostImage = (ImageView) mView.findViewById(R.id.post_image);
Picasso.get().load(postimage).into(PostImage);
// Glide.with(ctx).load(postimage).into(PostImage);
}
}
private void SendUserToPostActivity() {
Intent addNewPostIntent = new Intent(MainActivity.this, PostActivity.class);
startActivity(addNewPostIntent);
}
protected void onStart() {
super.onStart();
FirebaseUser currentUser = firebaseAuth.getCurrentUser();
if (currentUser == null) {
SendUserToLoginActivity();
} else {
CheckUserExistence();
}
}
private void CheckUserExistence() {
final String current_user_id = firebaseAuth.getCurrentUser().getUid();
UsersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(current_user_id)) {
SendUserToSetupActivity();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToSetupActivity() {
Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void SendUserToLoginActivity() {
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
private void SendUserToProfileActivity() {
Intent profileIntent = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(profileIntent);
}
private void SendUserToAboutUsActivity() {
Intent AboutUsIntent = new Intent(MainActivity.this, AboutUs.class);
startActivity(AboutUsIntent);
}
private void SendUserToContactUsActivity() {
Intent AboutUsIntent = new Intent(MainActivity.this, ContactUs.class);
startActivity(AboutUsIntent);
}
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void UserMenuSelector(MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_post:
SendUserToPostActivity();
break;
case R.id.nav_menu1:
Toast.makeText(this, "Home", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_menu2:
Toast.makeText(this, "Discussion FOrum", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_menu3:
SendUserToProfileActivity();
break;
case R.id.nav_menu4:
SendUserToAboutUsActivity();
break;
case R.id.nav_menu5:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "PICT Placement.\n Forum to create awareness...\nLink:
https: //github.com/pragyagupta1898");
sendIntent.setType("text/plain"); startActivity(sendIntent); Toast.makeText(this, "Share", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_contact:
SendUserToContactUsActivity();
break;
case R.id.nav_logout:
firebaseAuth.signOut(); SendUserToLoginActivity();
break;
}
}
}
The error is here:
if(dataSnapshot.child(PostKey).hasChild(currentUserID))
It says:
Argument 'PostKey' might be null less... (Ctrl+F1)
This inspection analyzes method control and data flow to report possible conditions that are always true or false, expressions whose value is statically proven to be constant, and situations that can lead to nullability contract violations.
Variables, method parameters and return values marked as #Nullable or #NotNull are treated as nullable (or not-null, respectively) and used during the analysis to check nullability contracts, e.g. report NullPointerException (NPE) errors that might be produced.
More complex contracts can be defined using #Contract annotation, for example:
#Contract(", null - null") — method returns null if its second argument is null #Contract(", null - null; _, !null - !null") — method returns null if its second argument is null and not-null otherwise #Contract("true - fail") — a typical assertFalse method which throws an exception if true is passed to it
The inspection can be configured to use custom #Nullable
#NotNull annotations (by default the ones from annotations.jar will be used)
How to resolve it?
That's not an error, it's a warning.
Since it doesn't seem that you read the warning you quoted, I'll paraphrase:
The DataSnapshot.child() method has a #Nullable flag, meaning it's possible that it will return null. Since you are calling something directly on the result of that method, Android Studio is simply telling you that, since child() can be null, running hasChild() on it might lead to a NullPointerException.
Either check the null state or ignore it.
try something like this.
if((PostKey != null) && dataSnapshot.child(PostKey).hasChild(currentUserID))
You can also write it so that you handle the null case
if (PostKey == null) //do somthing
else if (dataSnapshot.child(PostKey).hasChild(currentUserID)) //do something
else //do something
If you debug your app at this warning you will found that the mUserID = null,
so you just need to inti it:
mUserID = mAuth.getCurrentUser().getUid();

ListView displays data twice

I am working on a small application to save the data of the book (such as the name of the book, the type of the book, the author of the book and the year of publication) in a database, but when the data is returned from the databases using CursorLoader It's shown twice in ListView
This is a code of AddBook activity.
package training.android.com.librarycard;
import android.app.AlertDialog;
import android.app.LoaderManager;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import training.android.com.librarycard.Database.Database;
import training.android.com.librarycard.Database.LibraryCardContract;
public class AddBook extends AppCompatActivity
implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int EXISTING_BOOK_LOADER = 0;
Spinner mBookType;
EditText mBookTitle, mBookAuthor, mBookPublishYear;
String bookType;
int position;
private boolean bookHasChanged = false;
private Uri currentBookUri;
private View.OnTouchListener touchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
bookHasChanged = true;
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_book);
Intent intent = getIntent();
if (intent != null) {
currentBookUri = intent.getData();
if (currentBookUri == null) {
setTitle("Add a book");
invalidateOptionsMenu();
} else {
setTitle("Edit a book");
getLoaderManager().initLoader(EXISTING_BOOK_LOADER, null, this);
}
}
mBookType = findViewById(R.id.spinner);
mBookTitle = findViewById(R.id.book_title);
mBookAuthor = findViewById(R.id.book_author);
mBookPublishYear = findViewById(R.id.publish_year);
mBookType.setOnTouchListener(touchListener);
mBookAuthor.setOnTouchListener(touchListener);
mBookTitle.setOnTouchListener(touchListener);
mBookPublishYear.setOnTouchListener(touchListener);
setupBookTypeSpinner();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (currentBookUri == null) {
MenuItem menuItem = menu.findItem(R.id.action_delete);
menuItem.setVisible(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_save:
setBook();
finish();
return true;
case R.id.action_delete:
showDeleteConfirmationDialog();
return true;
case android.R.id.home:
if (!bookHasChanged) {
NavUtils.navigateUpFromSameTask(AddBook.this);
return true;
}
DialogInterface.OnClickListener discardButtonClickListener
= new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
NavUtils.navigateUpFromSameTask(AddBook.this);
}
};
showUnsavedChangeDialog(discardButtonClickListener);
return true;
}
return super.onOptionsItemSelected(item);
}
private void showUnsavedChangeDialog(DialogInterface.OnClickListener discardButtonClickListener) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Discard your changes and quit editing?");
builder.setPositiveButton("Discard", discardButtonClickListener);
builder.setNegativeButton("Keep editing", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog != null)
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void showDeleteConfirmationDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Delete this book ?");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
deleteBook();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog != null)
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void deleteBook() {
if (currentBookUri != null) {
int rowDeleted = getContentResolver().delete(currentBookUri, null, null);
if (rowDeleted == 0)
Toast.makeText(this, "Delete book failed", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "Delete book successful", Toast.LENGTH_SHORT).show();
}
finish();
}
public void setupBookTypeSpinner() {
final ArrayAdapter<CharSequence> bookTypeAdapter = ArrayAdapter.createFromResource(
this, R.array.books_type, R.layout.support_simple_spinner_dropdown_item);
bookTypeAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
mBookType.setAdapter(bookTypeAdapter);
mBookType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
bookType = parent.getSelectedItem().toString();
position = parent.getSelectedItemPosition();
Log.i("BookTypeSelection", bookType+"");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void setBook() {
String bookTitle = mBookTitle.getText().toString().trim();
String bookAuthor = mBookAuthor.getText().toString().trim();
String publishYear = mBookPublishYear.getText().toString().trim();
if (currentBookUri == null && TextUtils.isEmpty(bookTitle) && TextUtils.isEmpty(bookAuthor)
&& TextUtils.isEmpty(publishYear))
return;
Database database = new Database(this);
SQLiteDatabase db = database.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE, bookTitle);
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR, bookAuthor);
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR, publishYear);
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE, bookType);
if (currentBookUri == null) {
Uri uri = getContentResolver().insert(LibraryCardContract.LibraryCard.CONTENT_URI, values);
if (uri == null) {
Toast.makeText(this, "Error with saving book", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Book saved", Toast.LENGTH_SHORT).show();
}
} else {
int rowAffected = getContentResolver().update(currentBookUri, values, null, null);
if (rowAffected == 0) {
Toast.makeText(this, "Error with saving book", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Book saved", Toast.LENGTH_SHORT).show();
}
}
db.insert(LibraryCardContract.LibraryCard.TABLE_NAME, null, values);
Toast.makeText(this, "Insert new book", Toast.LENGTH_SHORT).show();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String [] projection = {
LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR,
LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR };
return new CursorLoader(this,currentBookUri,projection,
null,null,null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if(data.moveToFirst()){
String title = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE));
String type = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE));
String publishYear = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR));
String author = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR));
mBookTitle.setText(title);
mBookAuthor.setText(author);
mBookType.setSelection(position);
mBookPublishYear.setText(publishYear);
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mBookTitle.setText("");
mBookType.setSelection(position);
mBookAuthor.setText("");
mBookPublishYear.setText("");
}
#Override
public void onBackPressed() {
if(!bookHasChanged){
super.onBackPressed();
return;
}
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
};
showUnsavedChangeDialog(discardButtonClickListener);
}
}
And this is a code of Home activity that contains a listView to
display the data.
package training.android.com.librarycard;
import android.app.LoaderManager;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import training.android.com.librarycard.Database.Database;
import training.android.com.librarycard.Database.LibraryCardContract;
import training.android.com.librarycard.Models.BookCursorAdapter;
import training.android.com.librarycard.Models.BookDetail;
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, LoaderManager.LoaderCallbacks<Cursor> {
private static final int BOOK_LOADER = 0;
private ListView mBookList;
private BookCursorAdapter cursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mBookList = findViewById(R.id.books_rv);
cursorAdapter = new BookCursorAdapter(this, null);
mBookList.setAdapter(cursorAdapter);
mBookList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Home.this, AddBook.class);
Uri currentPetUri = ContentUris.withAppendedId(LibraryCardContract.LibraryCard.CONTENT_URI, id);
intent.setData(currentPetUri);
startActivity(intent);
}
});
getLoaderManager().initLoader(BOOK_LOADER, null, this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getBaseContext(), AddBook.class);
startActivity(intent);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case R.id.delete_all_books:
deleteAllBooks();
return true;
}
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
private void deleteAllBooks() {
int rowDeleted = getContentResolver().delete(LibraryCardContract.LibraryCard.CONTENT_URI,
null, null);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = {
LibraryCardContract.LibraryCard._ID,
LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR,
LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR};
return new CursorLoader(this, LibraryCardContract.LibraryCard.CONTENT_URI,
projection,
null,
null,
null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
cursorAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
cursorAdapter.swapCursor(null);
}
}
> This is a code of **BookCursorAdapter** class.
package training.android.com.librarycard.Models;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
import training.android.com.librarycard.Database.LibraryCardContract;
import training.android.com.librarycard.R;
/**
* Created by Hassan on 4/9/2018.
*/
public class BookCursorAdapter extends CursorAdapter {
public BookCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context)
.inflate(R.layout.book_list,parent,false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView bookTitle = view.findViewById(R.id.book_name_tv);
TextView bookAuthor = view.findViewById(R.id.author_tv);
TextView bookType = view.findViewById(R.id.book_type_tv);
TextView publishYear = view.findViewById(R.id.publish_year_tv);
String title = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE));
String type = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE));
String year = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR));
String author = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR));
bookAuthor.setText(author);
bookTitle.setText(title);
bookType.setText(type);
publishYear.setText(year);
}
#Override
public int getCount() {
return super.getCount();
}
}
Screenshot of the application
enter image description here

Categories

Resources