I am trying to read data from Firebase Database and using the database fields to initialize an object but it is returning null.
Model class.
public class Event {
private String Nome;
private String data;
private String descrizione;
private String luogo;
private String mese;
private String ora_fine;
private String ora_inizio;
private String type;
private String programma;
private String img ;
public Event()
{
}
public Event(String nome, String data, String descrizione, String luogo, String mese, String ora_fine, String ora_inizio, String type, String mprogramma, String mimg) {
Nome = nome;
this.data = data;
this.descrizione = descrizione;
this.luogo = luogo;
this.mese = mese;
this.ora_fine = ora_fine;
this.ora_inizio = ora_inizio;
this.type = type;
this.programma=mprogramma;
this.img=mimg;
}
public String getNome() {
return Nome;
}
public String getData() {
return data;
}
public String getDescrizione() {
return descrizione;
}
public String getLuogo() {
return luogo;
}
public String getMese() {
return mese;
}
public String getOra_fine() {
return ora_fine;
}
public String getOra_inizio() {
return ora_inizio;
}
public String getType() {
return type;
}
public String getProgramma() {
return programma;
}
public String getImg() {
return img;
}
public Date toDate()
{
DateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.ITALIAN);
Date date = null;
try {
date = format.parse(data);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
main Activity
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener
{
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private ImageView vangelo;
private ImageView santo;
private ImageView evento;
private ImageView notizia;
private DatabaseReference vangeloRef;
private DatabaseReference santoRef;
private DatabaseReference eventoRef;
private DatabaseReference notiziaRef;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout= (DrawerLayout) findViewById(R.id.drawer_layout); //finds the drawer layout view
mToggle= new ActionBarDrawerToggle(this, mDrawerLayout,R.string.Open, R.string.Close); //creates the action bar
mDrawerLayout.addDrawerListener(mToggle); //adds the action bat to the layout
mToggle.syncState(); //syncs the toggle state with the actual drawer layout
DatabaseReference RootRef=FirebaseDatabase.getInstance().getReference();
eventoRef=RootRef.child("MainEvent");
vangelo=(ImageView)findViewById(R.id.vangelo);
santo=(ImageView)findViewById(R.id.santo);
evento=(ImageView)findViewById(R.id.evento);
notizia=(ImageView)findViewById(R.id.notizia);
vangelo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
santo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
evento.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
notizia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
actionBar.setDisplayHomeAsUpEnabled(true);
NavigationView mNavigationView = (NavigationView) findViewById(R.id.nav_view);
if (mNavigationView != null) {
mNavigationView.setNavigationItemSelectedListener(this);
}
}
#Override
public void onStart()
{
super.onStart();
eventoRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Event ev= dataSnapshot.getValue(Event.class);
Log.v("Done",ev.getData());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem Item)
{
if(mToggle.onOptionsItemSelected(Item))
{
return true;
}
return super.onOptionsItemSelected(Item);
}
#Override
public boolean onNavigationItemSelected(MenuItem Item)
{
int id = Item.getItemId();
Intent intent;
if (id == R.id.preghiere)
{
intent= new Intent(this, Preghiere.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
else if ( id== R.id.bans)
{
intent= new Intent(this, Bans.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
else if (id== R.id.canzoni)
{
intent= new Intent(this, Canzoni.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
else if (id==R.id.calendario)
{
intent= new Intent(this, Calendario.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
else if (id== R.id.per_riflettere)
{
intent= new Intent(this, perRiflettere.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
else if( id== R.id.home)
{
intent= new Intent(this, this.getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Database tree
tree
I am trying to instantiate a single event object with the fields of "MainEvent" in the database but the code is returning null. How can I solve?
You have to retrieve data as follow:
eventoRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Event ev= snapshot.getValue(Event.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Related
My app has a post layout which have an edit button and the send button. All i want to do is to show only edit button if current user is viewing his/her post and not the send button. Just like a stackoverflow post, you can't edit other's post and can't send a message to yourself. I have tried boolean methods but still no solution. Thanks.
Activity that have showButtonsForCurrentUser() method ;
public class ViewPostActivity extends AppCompatActivity {
private static final String TAG = "ViewPostActivity";
//widgets
private TextView mTitle, mDescription, mPrice, mLocation;
//vars
private String mPostId;
private String userId;
private Post mPost;
private PostImages mPostImages;
private ViewPager viewPager;
private ImageView editPostIcon;
private WormDotsIndicator wormDotsIndicator;
public ViewAdapter viewAdapter;
public DatabaseReference reference;
public FirebaseUser currentUser;
public ArrayList<String> IMAGES = new ArrayList<>();
public ArrayList<Uri> mImageUris = new ArrayList<>();
private SquareImageView postImageView;
private User user;
//Dialog and Sheet vars
private Dialog deleteDialog;
private Button deleteBtnDialog;
private Button deleteBtnSheet;
private Button updateBtn;
private Button sendBtn;
private TextView titleTv, messageTv;
private ImageView closeIcon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_post);
mPostId = getIntent().getStringExtra(getString(R.string.arg_post_id));
mTitle = (TextView) findViewById(R.id.post_title);
mDescription = (TextView) findViewById(R.id.post_description);
mPrice = (TextView) findViewById(R.id.post_price);
mLocation = (TextView) findViewById(R.id.post_location);
postImageView = findViewById(R.id.post_image);
sendBtn = findViewById(R.id.send_msg);
viewPager = findViewById(R.id.view_pager_images);
editPostIcon = findViewById(R.id.edit_post_btn);
wormDotsIndicator = findViewById(R.id.dotsindicator);
editPostIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showBottomSheetDialog();
}
});
getPostInfo();
showButtonsForCurrentUser();
////MyPosts Layout/////
deleteBtnDialog = findViewById(R.id.dialog_btn);
deleteDialog = new Dialog(this);
////MyPosts Layout/////
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ViewPostActivity.this, MessageActivity.class);
intent.putExtra("userId", userId);
startActivity(intent);
}
});
}
public void showButtonsForCurrentUser(){
currentUser = FirebaseAuth.getInstance().getCurrentUser();
//sendBtn and editPostIcon are set to GONE.
if (currentUser.equals(userId)){
sendBtn.setVisibility(View.VISIBLE);
}else{
editPostIcon.setVisibility(View.VISIBLE);
}
}
private void getPostInfo(){
Log.d(TAG, "getPostInfo: getting the post information.");
reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child(getString(R.string.node_posts))
.orderByKey()
.equalTo(mPostId);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DataSnapshot singleSnapshot = dataSnapshot.getChildren().iterator().next();
if(singleSnapshot != null){
mPost = singleSnapshot.getValue(Post.class);
Log.d(TAG, "onDataChange: found the post: " + mPost.getTitle());
mTitle.setText(mPost.getTitle());
mDescription.setText(mPost.getDescription());
String price = "FREE";
if(mPost.getPrice() != null){
price = "$" + mPost.getPrice();
}
mPrice.setText(price);
String location = mPost.getCity();
mLocation.setText(location);
userId = mPost.getUser_id();
if (mPost.getImage() != null){
wormDotsIndicator.setVisibility(View.INVISIBLE);
postImageView.setVisibility(View.VISIBLE);
Picasso.get().load(mPost.getImage()).into(postImageView);
}else {
IMAGES = mPost.getPostImages();
for (int i = 0; i <IMAGES.size(); i++){
Uri myUri = Uri.parse(IMAGES.get(i));
mImageUris.add(myUri);
}
viewAdapter = new ViewAdapter(getApplication(), IMAGES);
viewPager.setAdapter(viewAdapter);
wormDotsIndicator.setViewPager(viewPager);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showBottomSheetDialog() {
final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(ViewPostActivity.this, R.style.BottomSheetDialogTheme);
LinearLayout linearLayout = findViewById(R.id.bottom_sheet_update_container);
View bottomSheetView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.bottom_sheet_update, linearLayout);
updateBtn = bottomSheetView.findViewById(R.id.update_btnn);
deleteBtnSheet = bottomSheetView.findViewById(R.id.delete_btnn);
bottomSheetDialog.setContentView(bottomSheetView);
bottomSheetDialog.show();
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent updateActivityIntent = new Intent(ViewPostActivity.this, UpdateActivity.class);
if (IMAGES != null){
updateActivityIntent.putStringArrayListExtra("IMAGES", IMAGES);
updateActivityIntent.putParcelableArrayListExtra("IMAGEURIS", mImageUris);
}else {
String singlePhotoUrl = mPost.getImage();
updateActivityIntent.putExtra("Single Photo url", singlePhotoUrl);
}
updateActivityIntent.putExtra("Başlık", mTitle.getText());
updateActivityIntent.putExtra("Açıklama", mDescription.getText());
updateActivityIntent.putExtra("Fiyat", mPrice.getText());
updateActivityIntent.putExtra("mPostId", mPostId);
startActivity(updateActivityIntent);
bottomSheetDialog.dismiss();
}
});
deleteBtnSheet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDeleteDialog();
}
});
}
public void showDeleteDialog(){
deleteDialog.setContentView(R.layout.positive_dialog);
closeIcon = deleteDialog.findViewById(R.id.close_dialog);
deleteBtnDialog = deleteDialog.findViewById(R.id.dialog_btn);
titleTv = deleteDialog.findViewById(R.id.titleTv);
messageTv = deleteDialog.findViewById(R.id.message_dialog);
closeIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteDialog.dismiss();
}
});
deleteDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
deleteDialog.show();
deleteBtnDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deletePost(mPostId);
finish();
overridePendingTransition( 0, 0);
startActivity(getIntent());
overridePendingTransition( 0, 0);
deleteDialog.dismiss();
}
});
}
private void deletePost(String deletePostId){
Bundle args = new Bundle();
args.putString(getString(R.string.arg_post_id), deletePostId);
Query deleteQuery = reference.child("posts").orderByChild("post_id").equalTo(deletePostId);
deleteQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot delData: dataSnapshot.getChildren()){
delData.getRef().removeValue();
Intent backIntent = new Intent(ViewPostActivity.this, SearchActivity.class);
startActivity(backIntent);
}
Toast.makeText(ViewPostActivity.this,"Data Deleted",Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ViewPostActivity.this,databaseError.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
private void status(String status){
currentUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("users").child(currentUser.getUid());
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("status", status);
reference.updateChildren(hashMap);
}
#Override
protected void onResume() {
super.onResume();
status("online");
}
#Override
protected void onPause() {
super.onPause();
status("offline");
}
}
what are the values for mPostId?
I would log the userID and currentuser values thats being retrieved, to check if there is no issue your query. The boolean part should work
My MainAcivity hosts 2 fragments, login and register. I have a LiveData observer on LoginFragment that observes user login live data, after which if user is authenticated MainMenuActivity intent will start. On main menu there's logout button that would start MainActivity and load LoginFragment.
But here's the problem, the observer on LoginFragment triggered immediately after loading the fragment, which straight up start MainMenuActivity intent again.
My LoginFragment:
public class LoginFragment extends Fragment {
public static LoginFragment newInstance(){
return new LoginFragment();
}
private LoginViewModel mLoginViewModel;
private LiveData<UserModelJSONPlaceholder> mUserModelLiveData;
private static final String TAG = "FragLogin";
private Button mBtnLogin;
private EditText mTxtUsername, mTxtPass;
private TextView mTxtRegister;
private CheckBox mCheckBoxRemember;
private TextView mTxtInvalid;
private Callbacks mCallbacks = null;
private ProgressBar mProgressBar;
private UserApiInterface mAPIInterface;
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mPreferencesEditor;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login,container,false);
mBtnLogin = view.findViewById(R.id.btnLogin_login);
mTxtUsername = view.findViewById(R.id.txtUsername);
mTxtPass = view.findViewById(R.id.txtPass);
mCheckBoxRemember = view.findViewById(R.id.checkBoxRememberMe);
mTxtRegister = view.findViewById(R.id.txtRegister_login);
mProgressBar = view.findViewById(R.id.progressBar);
mTxtInvalid = view.findViewById(R.id.txtInvalid);
mProgressBar.setVisibility(View.GONE);
mTxtInvalid.setVisibility(View.GONE);
mAPIInterface = APIClient.getClient().create(UserApiInterface.class);
mSharedPreferences = getContext().getSharedPreferences("login",Context.MODE_PRIVATE);
mPreferencesEditor = mSharedPreferences.edit();
setListener();
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLoginViewModel = new ViewModelProvider(this).get(LoginViewModel.class);
mUserModelLiveData = mLoginViewModel.getUserModelLiveData();
//observer would be triggered right after loading fragment after logout
mUserModelLiveData.observe(this, new Observer<UserModelJSONPlaceholder>() {
#Override
public void onChanged(UserModelJSONPlaceholder userModel) {
Log.d(TAG, "onChanged: Observer: "+userModel.getResponse());
mProgressBar.setVisibility(View.GONE);
String loginAuth = userModel.getResponse();
if(loginAuth.equals("OK")){
mPreferencesEditor.putString("name",userModel.getUserModel().getName());
mCallbacks.login_goMainMenu(userModel.getUserModel().getName());
}else{
mTxtInvalid.setVisibility(View.VISIBLE);
}
}
});
}
private void doLogin(){
mProgressBar.setVisibility(View.VISIBLE);
final String username = mTxtUsername.getText().toString().trim();
final String password = mTxtPass.getText().toString().trim();
mLoginViewModel.authLogin(username,password);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mCallbacks = (Callbacks) context;
}
private void setListener(){
mBtnLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
doLogin();
}
});
mTxtRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallbacks.login_goRegister();
}
});
mCheckBoxRemember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView.isChecked()){
mPreferencesEditor.putBoolean("rememberMe", true).apply();
Log.d(TAG, "onCheckedChanged: Checked");
}else{
mPreferencesEditor.putBoolean("rememberMe", false).apply();
Log.d(TAG, "onCheckedChanged: Unchecked");
}
}
});
}
public interface Callbacks{
void login_goMainMenu(String name);
void login_goRegister();
}
}
My MainMenuActivity:
public class MainMenuActivity extends AppCompatActivity {
private static final String ARG_NAME = "arg_name";
private Button mBtnEnterQ,mBtnCreateQ;
private TextView mTxtName;
private Toolbar mToolbar;
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
mBtnEnterQ = findViewById(R.id.btnEnterQ);
mBtnCreateQ = findViewById(R.id.btnCreateQ);
mTxtName = findViewById(R.id.txtUsername);
mToolbar = findViewById(R.id.toolbar);
mSharedPreferences = getSharedPreferences("login",MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
setSupportActionBar(mToolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.itemLogout:
doLogout();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void doLogout(){
mEditor.remove("rememberMe");
mEditor.apply();
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
finish();
}
}
and here's my ViewModel and Repo for LoginFragment:
public class LoginViewModel extends ViewModel {
private static final String TAG = "LoginVM";
private UserRepository mUserRepository;
LiveData<UserModelJSONPlaceholder> mUserModelLiveData;
public LoginViewModel() {
mUserRepository = UserRepository.getInstance();
}
public void authLogin(String username, String password){
mUserRepository.authLogin(username,password);
}
public LiveData<UserModelJSONPlaceholder> getUserModelLiveData() {
return mUserRepository.getUserModelLiveData();
}
}
public class UserRepository {
private static UserRepository instance;
private static final String TAG = "RepoUser";
private UserApiInterface mUserApiInterface;
MutableLiveData<UserModelJSONPlaceholder> userModelLiveData;
public static UserRepository getInstance(){
if(instance==null){
instance=new UserRepository();
}
return instance;
}
private UserRepository(){
mUserApiInterface = APIClient.getClient().create(UserApiInterface.class);
Log.d(TAG, "UserRepository: repoInit");
}
public void authLogin(String username, String password){
Log.d(TAG, "authLogin: REQUEST INIT");
Log.d(TAG, "authLogin: SERVER: "+ CONFIG.SERVER);
mUserApiInterface.getUser(username,password).enqueue(new Callback<UserModelJSONPlaceholder>() {
#Override
public void onResponse(Call<UserModelJSONPlaceholder> call, Response<UserModelJSONPlaceholder> response) {
if(response.isSuccessful()){
UserModelJSONPlaceholder r = response.body();
userModelLiveData.postValue(response.body());
}else{
Log.d(TAG, "onResponse: FAILED. "+response.errorBody());
}
}
#Override
public void onFailure(Call<UserModelJSONPlaceholder> call, Throwable t) {
Log.d(TAG, "onFailure: "+t.getMessage());
}
});
}
public LiveData<UserModelJSONPlaceholder> getUserModelLiveData() {
if(userModelLiveData == null)
userModelLiveData = new MutableLiveData<>();
return userModelLiveData;
}
}
Your problems is you make UserRepository is Singleton instance and always keep value of userModelLiveData easy way to fix it change method to this
public LiveData<UserModelJSONPlaceholder> getUserModelLiveData() {
userModelLiveData = new MutableLiveData<>();
return userModelLiveData;
}
Thank you for helping me. The menu didn't appear and the list view in the recycler view is unclickable.
This is the menu part.
public class QuizListActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_list);
mAuth = FirebaseAuth.getInstance();
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerBView);
new FirebaseDatabaseHelper().readQuiz(new FirebaseDatabaseHelper.DataStatus() {
#Override
public void DataIsLoaded(List<Quiz> quizzes, List<String> keys) {
new RecyclerConfig().setConfig(mRecyclerView, QuizListActivity.this, quizzes, keys);
}
#Override
public void DataIsInserted() {
}
#Override
public void DataIsUpdated() {
}
#Override
public void DataIsDeleted() {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
FirebaseUser user = mAuth.getCurrentUser();
getMenuInflater().inflate(R.menu.quizlistmenu, menu);
if(user!=null) {
menu.getItem(0).setVisible(true);
menu.getItem(1).setVisible(true);
menu.getItem(2).setVisible(true);
}
return super.onCreateOptionsMenu(menu);
}
public boolean onPrepareOptionsMenu(Menu menu)
{FirebaseUser user = mAuth.getCurrentUser();
if(user!=null) {
menu.getItem(0).setVisible(true);
menu.getItem(1).setVisible(true);
menu.getItem(2).setVisible(true);
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId())
{
case R.id.new_book:
startActivity(new Intent(this, NewQuestionActivity.class));
return true;
case R.id.user_approval:
startActivity(new Intent(this, Approval.class));
return true;
case R.id.signout:
mAuth.signOut();
invalidateOptionsMenu();
RecyclerConfig.logout();
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the menu.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/new_book"
android:title="New Question" />
<item
android:id="#+id/user_approval"
android:title="Registered User" />
<item
android:id="#+id/signout"
android:title="Sign Out" />
</menu>
This is the Recycler part.
public class RecyclerConfig
{
FirebaseAuth mAuth;
private static FirebaseUser user;
private Context mContext;
private QuizAdapter mQuizAdapter;
public void setConfig(RecyclerView mRecyclerView, Context context, List<Quiz> quizzes, List<String> keys)
{
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
mContext = context;
mQuizAdapter = new QuizAdapter(quizzes, keys);
mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
mRecyclerView.setAdapter(mQuizAdapter);
}
class QuizItemView extends RecyclerView.ViewHolder
{
private TextView mquestion,mans1,mans2,mans3,mans4,mcorrect,mcategoryid;
private String key;
public QuizItemView(ViewGroup parent)
{
super(LayoutInflater.from(mContext)
.inflate(R.layout.quizlistitem, parent, false));
mquestion = (TextView) itemView.findViewById(R.id.questiontv);
mans1 = (TextView) itemView.findViewById(R.id.ans1tv);
mans2 = (TextView) itemView.findViewById(R.id.ans2tv);
mans3 = (TextView) itemView.findViewById(R.id.ans3tv);
mans4 = (TextView) itemView.findViewById(R.id.ans4tv);
mcorrect = (TextView) itemView.findViewById(R.id.correcttv);
mcategoryid = (TextView) itemView.findViewById(R.id.categorytv);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(user!=null) {
Intent intent = new Intent(mContext, QuizDetailActivity.class);
intent.putExtra("key", key);
intent.putExtra("question", mquestion.getText().toString());
intent.putExtra("answer1", mans1.getText().toString());
intent.putExtra("answer2", mans2.getText().toString());
intent.putExtra("answer3", mans3.getText().toString());
intent.putExtra("answer3", mans4.getText().toString());
intent.putExtra("answer3", mcorrect.getText().toString());
intent.putExtra("categoryid", mcategoryid.getText().toString());
mContext.startActivity(intent);
}
/*else
{
mContext.startActivity(new Intent(mContext, SignInActivity.class));
}*/
}
});
}
public void bind(Quiz quizzes, String key)
{
mquestion.setText(quizzes.getQuestion());
mans1.setText(quizzes.getAnswer1());
mans2.setText(quizzes.getAnswer2());
mans3.setText(quizzes.getAnswer3());
mans4.setText(quizzes.getAnswer4());
mcorrect.setText(quizzes.getCorrect());
mcategoryid.setText(quizzes.getCategoryid());
this.key = key;
}
}
class QuizAdapter extends RecyclerView.Adapter<QuizItemView>
{
private List<Quiz> mQuizList;
private List<String> mKeys;
public QuizAdapter(List<Quiz> mQuizList, List<String> mKeys) {
this.mQuizList = mQuizList;
this.mKeys = mKeys;
}
#NonNull
#Override
public QuizItemView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new QuizItemView(parent);
}
#Override
public void onBindViewHolder(#NonNull QuizItemView holder, int position) {
holder.bind(mQuizList.get(position), mKeys.get(position));
}
#Override
public int getItemCount() {
return mQuizList.size();
}
}
public static void logout()
{
user = null;
}
}
This is the login / register part.
public class SignInActivity extends AppCompatActivity {
MaterialEditText edtNewEmail,edtNewPassword,edtnewName, edtnewAge, edtnewAddress, edtStatus; // for register
MaterialEditText edtEmail,edtPassword; //for Signin
Button btnRegister,btnSignIn;
FirebaseAuth mAuth;
FirebaseDatabase database;
DatabaseReference users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
mAuth = FirebaseAuth.getInstance();
//Firebase
database = FirebaseDatabase.getInstance();
users = database.getReference("User");
edtEmail = (MaterialEditText)findViewById(R.id.edtEmail);
edtPassword = (MaterialEditText)findViewById(R.id.edtPassword);
btnSignIn = (Button)findViewById(R.id.signInBtn);
btnRegister = (Button)findViewById(R.id.regBtn);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showSignUpDialog();
}
});
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn(edtEmail.getText().toString(),edtPassword.getText().toString());
}
});
}
private void signIn(final String user, final String pwd) {
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child(user).exists())
{
if(!user.isEmpty())
{
User login = dataSnapshot.child(user).getValue(User.class);
if(login.getPassword().equals(pwd))
{
Common.currentUser = login;
if(login.getStatus().equals("Admin"))
{
mAuth.signInWithEmailAndPassword(edtEmail.getText().toString(),
edtPassword.getText().toString());
Toast.makeText(SignInActivity.this, "User signed in", Toast.LENGTH_LONG).show();
Intent intent = new Intent(SignInActivity.this,QuizListActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish(); return;
}
else if(login.getStatus().equals("User") && login.getApproval().equals("Y"))
{
Intent homeactivity = new Intent(SignInActivity.this,Home.class);
startActivity(homeactivity);
finish();
}
else if(login.getStatus().equals("User") && login.getApproval().equals("N"))
{
Intent adminactivity = new Intent(SignInActivity.this,Home.class);
startActivity(adminactivity);
finish();
}
}
else
Toast.makeText(SignInActivity.this,"Login Failed",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(SignInActivity.this,"Please fill in",Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(SignInActivity.this,"User doesn't exist",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void showSignUpDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(SignInActivity.this);
alertDialog.setTitle("Sign Up");
//alertDialog.setMessage("Please fill full information");
LayoutInflater inflater = this.getLayoutInflater();
View activity_register = inflater.inflate(R.layout.activity_register,null);
//edtNewUserName = (MaterialEditText)activity_register.findViewById(R.id.edtNewUserName);
edtNewEmail = (MaterialEditText)activity_register.findViewById(R.id.edtNewEmail);
edtNewPassword = (MaterialEditText)activity_register.findViewById(R.id.edtNewPassword);
edtnewName = (MaterialEditText)activity_register.findViewById(R.id.edtnewName);
edtnewAge = (MaterialEditText)activity_register.findViewById(R.id.edtnewAge);
edtnewAddress = (MaterialEditText)activity_register.findViewById(R.id.edtnewAddress);
edtStatus = (MaterialEditText)activity_register.findViewById(R.id.edtStatus);
alertDialog.setView(activity_register);
//alertDialog.setIcon(R.drawable.ic_account_circle_black_24dp);
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final User user = new User(edtNewEmail.getText().toString(),
edtNewPassword.getText().toString(),edtnewName.getText().toString(),
edtnewAge.getText().toString(),edtnewAddress.getText().toString(),edtStatus.getText().toString(),
"N");
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child(user.getEmail()).exists())
Toast.makeText(SignInActivity.this,"User already exist.",Toast.LENGTH_LONG).show();
else
{
if(dataSnapshot.child(user.getStatus()).exists() && user.getStatus() == "Admin")
{
mAuth.createUserWithEmailAndPassword(edtNewEmail.getText().toString(),
edtNewPassword.getText().toString())
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
FirebaseDatabase.getInstance().getReference("User")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(user);
}
}
});
}
else {
users.child(user.getEmail())
.setValue(user);
Toast.makeText(SignInActivity.this, "User registered.", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
dialogInterface.dismiss();
}
});
alertDialog.show();
}
}
The login and register works well then after login the list recycler view is shown accurately but the menu didn't appear and the recycler view is unclickable.
For the menu, it previously stated that a null reference or something.
For your first question, which is why menu didn't appear because you didn't initialize the FirebaseUser. You need to initiliaze it at method onCreate.
at Class.
private FirebaseUser user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_list);
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
}
next, at your onCreateOptionsMenu.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.quizlistmenu, menu);
if(user!=null) {
menu.getItem(0).setVisible(true);
menu.getItem(1).setVisible(true);
menu.getItem(2).setVisible(true);
}
return super.onCreateOptionsMenu(menu);
}
I'm trying to delete the selected item in my RecyclerView, but when I click on my delete Button it just deletes the last item added. And after I delete the last item added I can not delete anymore. What am I missing?
MainActivity
public class MainWishActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private RecyclerView wishList;
private androidx.appcompat.widget.Toolbar mToolbar;
private ImageButton ibaddnewwishlist;
private CircleImageView NavProfileImage;
private TextView NavProfileFirstName, NavProfileLastName;
private FirebaseAuth mAuth;
private DatabaseReference UsersRef, WishListRef;
String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_wish);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Brukere");
WishListRef = FirebaseDatabase.getInstance().getReference().child("Ønskelister").child(currentUserID);
mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle(" Dine Ønskelister");
drawerLayout = (DrawerLayout)findViewById(R.id.drawable_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainWishActivity.this, drawerLayout, R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
ibaddnewwishlist = (ImageButton)findViewById(R.id.ib_addnewwishlist);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView = (NavigationView)findViewById(R.id.navigation_view);
wishList = (RecyclerView)findViewById(R.id.rv_wishlist);
wishList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
wishList.setLayoutManager(linearLayoutManager);
View navView = navigationView.inflateHeaderView(R.layout.navigation_header);
NavProfileImage = (CircleImageView)navView.findViewById(R.id.civ_navprofilepicture);
NavProfileFirstName = (TextView)navView.findViewById(R.id.tv_headerfirstname);
NavProfileLastName = (TextView) navView.findViewById(R.id.tv_headerlastname);
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
if (dataSnapshot.hasChild("fornavn")){
String firstname = dataSnapshot.child("fornavn").getValue().toString();
NavProfileFirstName.setText(firstname);
}
if (dataSnapshot.hasChild("etternavn")) {
String lastname = dataSnapshot.child("etternavn").getValue().toString();
NavProfileLastName.setText(lastname);
}
if (dataSnapshot.hasChild("profilbilde")){
String image = dataSnapshot.child("profilbilde").getValue().toString();
Picasso.with(MainWishActivity.this).load(image).placeholder(R.drawable.profile).into(NavProfileImage);
}
else{
Toast.makeText(MainWishActivity.this, "Profil navn finnes ikke...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
ibaddnewwishlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SendUserToWishListActivity();
}
});
DisplayUsersWishLists();
}
private void DisplayUsersWishLists() {
FirebaseRecyclerAdapter<WishListClass, WishListViewHolder > firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<WishListClass, WishListViewHolder>
(
WishListClass.class,
R.layout.wish_list_single_layout,
WishListViewHolder.class,
WishListRef
) {
#Override
protected void populateViewHolder(WishListViewHolder viewHolder, WishListClass model, final int position) {
final String Key = getRef(position).getKey();
viewHolder.setFornavn(model.getFornavn());
viewHolder.setDate(model.getDate());
viewHolder.setTitle(model.getTitle());
viewHolder.setProfilbilde(getApplicationContext(), model.getProfilbilde());
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent profileIntent = new Intent(MainWishActivity.this, UserWishItemActivity.class);
profileIntent.putExtra("Key", Key);
startActivity(profileIntent);
}
});
}
};
wishList.setAdapter(firebaseRecyclerAdapter);
}
public static class WishListViewHolder extends RecyclerView.ViewHolder{
View mView;
public WishListViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
}
public void setFornavn (String fornavn){
TextView wishlist_name = (TextView) mView.findViewById(R.id.tv_firstnamelist);
wishlist_name.setText(fornavn);
}
public void setProfilbilde (Context ctx, String profilbilde){
CircleImageView image = (CircleImageView) mView.findViewById(R.id.civ_profilepicturelist);
Picasso.with(ctx).load(profilbilde).into(image);
}
public void setDate (String date){
TextView wishlist_date = (TextView) mView.findViewById(R.id.tv_publisheddatelist);
wishlist_date.setText(" " + date);
}
public void setTitle (String title){
TextView wishlist_title = (TextView) mView.findViewById(R.id.tv_wishlisttitle);
wishlist_title.setText(title);
}
}
private void SendUserToWishListActivity(){
Intent addNewPostIntent = new Intent(MainWishActivity.this, AddWishListActivity.class);
startActivity(addNewPostIntent);
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null){
SendUserToLoginActivity();
}
else
{
CheckUserExistence();
}
}
private void CheckUserExistence(){
final String current_user_id = mAuth.getCurrentUser().getUid();
UsersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(current_user_id)){
SendUserToUserInfoAcitivity();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToUserInfoAcitivity(){
Intent setupIntent = new Intent(MainWishActivity.this, UserInfoActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void SendUserToLoginActivity() {
Intent loginIntent = new Intent(MainWishActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
private void SendUserToFindFriendsActivity(){
Intent findfriendsIntent = new Intent(MainWishActivity.this, FindFriendsActivity.class);
findfriendsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(findfriendsIntent);
finish();
}
#Override
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.navbtn_addwishlist:
SendUserToWishListActivity();
break;
case R.id.navbtn_profile:
Toast.makeText(this, "Profil", Toast.LENGTH_SHORT).show();
break;
case R.id.navbtn_home:
Toast.makeText(this, "Hjem", Toast.LENGTH_SHORT).show();
break;
case R.id.navbtn_friends:
Toast.makeText(this, "Venner", Toast.LENGTH_SHORT).show();
break;
case R.id.navbtn_findfriends:
SendUserToFindFriendsActivity();
break;
case R.id.navbtn_settings:
Toast.makeText(this, "Instillinger", Toast.LENGTH_SHORT).show();
break;
case R.id.navbtn_logout:
mAuth.signOut();
SendUserToLoginActivity();
break;
}
}
SecondActivity
public class UserWishItemActivity extends AppCompatActivity {
private TextView tvwishlisttitle;
private EditText etwishitem;
private Button btnaddwishitem;
private RecyclerView wishListitems;
private String currentUserID, databaseUserID;
private String Key, postRandomName;
private DatabaseReference WishListUsersClickRef, UsersRef, WishItemsRef, wishListRef,WishItemsRef1;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_add_wish_item);
Key = getIntent().getExtras().get("Key").toString();
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Brukere");
WishItemsRef = FirebaseDatabase.getInstance().getReference().child("Ønsker");
wishListRef = FirebaseDatabase.getInstance().getReference().child("Ønskelister").child(currentUserID).child(Key);
tvwishlisttitle = (TextView)findViewById(R.id.tv_userwishlisttitle);
etwishitem = (EditText)findViewById(R.id.et_wishitem);
btnaddwishitem = (Button)findViewById(R.id.btn_addwishitem);
btnaddwishitem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateWishlist();
}
});
wishListitems = (RecyclerView)findViewById(R.id.rv_wishlistitems);
wishListitems.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
wishListitems.setLayoutManager(linearLayoutManager);
WishListUsersClickRef = FirebaseDatabase.getInstance().getReference("Ønskelister").child(currentUserID).child(Key);
WishListUsersClickRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String title = dataSnapshot.child("title").getValue().toString();
databaseUserID = dataSnapshot.child("uid").getValue().toString();
tvwishlisttitle.setText(title);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DisplayWishListItems();
}
private void DisplayWishListItems() {
FirebaseRecyclerAdapter<WishItemClass, WishListItemsViewHolder > firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<WishItemClass, WishListItemsViewHolder>
(
WishItemClass.class,
R.layout.wish_list_item_layout,
WishListItemsViewHolder.class,
WishItemsRef.child(Key)
) {
#Override
protected void populateViewHolder(final WishListItemsViewHolder viewHolder, final WishItemClass model, final int position) {
viewHolder.setWishitemname(model.getWishitemname());
viewHolder.m1View.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(UserWishItemActivity.this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.endreslettjobb_dialog, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setTitle(model.getWishitemname());
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
final Button btndelete = (Button)dialogView.findViewById(R.id.btn_delete);
btndelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
WishItemsRef.removeValue();
}
});
return false;
}
});
}
};
wishListitems.setAdapter(firebaseRecyclerAdapter);
}
public static class WishListItemsViewHolder extends RecyclerView.ViewHolder{
View m1View;
public WishListItemsViewHolder(#NonNull View itemView) {
super(itemView);
m1View = itemView;
}
public void setWishitemname (String wishitemname){
TextView wishitem_name = (TextView) m1View.findViewById(R.id.tv_wishitemname);
wishitem_name.setText(wishitemname);
}
public void setUid (String uid){
}
}
private void CreateWishlist() {
postRandomName = String.valueOf(new Date().getTime());
final String wishlist = etwishitem.getText().toString().trim();
etwishitem.setText("");
wishListRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
HashMap postMap = new HashMap();
postMap.put("uid", currentUserID);
postMap.put("wishitemname", wishlist);
WishItemsRef.child(Key).child(postRandomName).updateChildren(postMap)
.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
AddItemActivity
private Spinner spwishlisttitle;
private Button btnsavewishlist;
private DatabaseReference UsersRef, wishListRef;
private FirebaseAuth mAuth;
private String saveCurrentDate, currentUserID, postRandomName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_wish_list);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Brukere");
wishListRef = FirebaseDatabase.getInstance().getReference().child("Ønskelister");
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
spwishlisttitle = (Spinner) findViewById(R.id.sp_wishlisttitle);
btnsavewishlist = (Button) findViewById(R.id.btn_savewishlist);
btnsavewishlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateWishlist();
}
});
}
private void CreateWishlist() {
Calendar calFordDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calFordDate.getTime());
postRandomName = String.valueOf(new Date().getTime());
final String wishlist = spwishlisttitle.getSelectedItem().toString().trim();
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String userFirstname = dataSnapshot.child("fornavn").getValue().toString();
String userProfileImage = dataSnapshot.child("profilbilde").getValue().toString();
HashMap postMap = new HashMap();
postMap.put("uid", currentUserID);
postMap.put("date", saveCurrentDate);
postMap.put("title", wishlist);
postMap.put("profilbilde", userProfileImage);
postMap.put("fornavn", userFirstname);
wishListRef.child(currentUserID).child(currentUserID + postRandomName).updateChildren(postMap)
.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
SendUserToMainActivity();
Toast.makeText(AddWishListActivity.this, "Ønskeliste opprettet", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(AddWishListActivity.this, "Error ocurred", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(AddWishListActivity.this, MainWishActivity.class);
startActivity(mainIntent);
}
}
I have edited my question with my code.
Hope this is helpful.
How to get the data from server and upload data to server using JSON?
please tell me.
This is QRActivity------------------------------------------------
final View.OnClickListener listener = new View.OnClickListener() {
#Override
public
void onClick(View v) {
btnSearch.setClickable(true);
// Server call with record_id
//DistributionDetails detDis <-- response json object from server call
QrActivityViewDetails detDis = new
QrActivityViewDetails(1002,"NORORG147530","No2,abcd Road , Colombo 03","0112233456");
Intent myIntent = new Intent(QrActivity.this, DistributionDetails.class);
myIntent.putExtra("QrActivityViewDetails", detDis);
startActivity(myIntent);
}
};
This is QrActivityViewDetails Class file
public class QrActivityViewDetails implements Serializable {
#SerializedName("DistributionID")
private int DistributionID;
#SerializedName("full_name")
private String full_name;
#SerializedName("full_address")
private String full_address;
#SerializedName("contact")
private String contact;
public QrActivityViewDetails(int DistributionID, String full_name, String full_address, String contact_number)
{
this.DistributionID = DistributionID;
this.full_name = full_name;
this.full_address = full_address;
this.contact = contact_number;
}
public
int getRecord_id() {
return DistributionID;
}
public
void setRecord_id(int record_id) {
this.DistributionID = record_id;
}
public
String getFull_name() {
return full_name;
}
public
void setFull_name(String full_name) {
this.full_name = full_name;
}
public
String getFull_address() {
return full_address;
}
public
void setFull_address(String full_address) {
this.full_address = full_address;
}
public
String getContact() {
return contact;
}
public
void setContact(String contact) {
this.contact = contact;
}
}
This is View Data Activity called DistributionDetails---------------
public class DistributionDetails extends AppCompatActivity {
private QrActivityViewDetails detQRV;
TextView ID ,Address ,name,contact;
Button btnDIR;
#Override
protected
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_distribution_details);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
ID = (TextView) findViewById(R.id.lblID);
Address = (TextView) findViewById(R.id.lblAddress);
name = (TextView) findViewById(R.id.lblUname);
contact = (TextView) findViewById(R.id.lblTelenum);
btnDIR = (Button) findViewById(R.id.btnDelivered);
IntendFill();
btnDIR.setOnClickListener(new View.OnClickListener() {
#Override
public
void onClick(View v) {
Intent intent = new Intent(DistributionDetails.this, FinalActivity.class);
startActivity(intent);
}
});
}
public void IntendFill() {
Intent intent = getIntent();
if (intent.hasExtra("QrActivityViewDetails")) {
detQRV = (QrActivityViewDetails) intent.getSerializableExtra("QrActivityViewDetails");
ID.setText(String.valueOf(detQRV.getRecord_id()));
Address.setText(String.valueOf(detQRV.getFull_address()));
name.setText(String.valueOf(detQRV.getFull_name()));
contact.setText(String.valueOf(detQRV.getContact()));
}
}
}