Unable to update item in Firebase Database [closed] - android

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am new to android i have made a project to store members information in one activity and in another activity i display members in listView and on onlong clicking listview i open another activity to update members information but when i click on update button it adds that record instead of Updating.
My Firebase Structure :
My activity for storing :
public class MainActivity extends AppCompatActivity {
EditText txtname,txtage,txtheight,txtphone;
Button btnsave,btnRead;
Member member;
DatabaseReference reff;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtname = findViewById(R.id.txtname);
txtage =findViewById(R.id.txtage);
txtphone =findViewById(R.id.txtphone);
txtheight =findViewById(R.id.txtheight);
btnsave = (Button)findViewById(R.id.btnsave);
btnRead =(Button)findViewById(R.id.btnRead);
btnRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivity();
}
private void openActivity() {
Intent intent = new Intent(MainActivity.this, Retreivedata.class);
startActivity(intent);
}
});
member = new Member();
reff = FirebaseDatabase.getInstance().getReference().child("Member");
btnsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddUsers();
}
});
}
private void AddUsers(){
String name = txtname.getText().toString().trim();
String age = txtage.getText().toString().trim();
String phone = txtphone.getText().toString().trim();
String ht = txtheight.getText().toString().trim();
if(!TextUtils.isEmpty(name)) {
String id = reff.push().getKey();
Member member = new Member(id, name, age, phone, ht);
reff.child(id).setValue(member);
Toast.makeText(this,"User Inserted Successfully",Toast.LENGTH_LONG).show();
txtheight.setText("");
txtphone.setText("");
txtage.setText("");
txtname.setText("");
}else {
txtname.setError("Enter Name");
}
}
}
My activity for displaying records in listview:
public class Retreivedata extends AppCompatActivity {
ListView listView;
FirebaseDatabase database;
DatabaseReference ref;
ArrayList<Member> list;
ArrayAdapter<Member> adapter;
Member member;
Button btnDlt;
Boolean a=false;
String val="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retreivedata);
member = new Member();
listView =(ListView)findViewById(R.id.listView);
btnDlt = (Button) findViewById(R.id.btnDlt);
database = FirebaseDatabase.getInstance();
ref = database.getReference("Member");
list = new ArrayList<>();
adapter = new ArrayAdapter<Member>(this,R.layout.list_white_text,R.id.userInfo, list);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dts: dataSnapshot.getChildren())
{
member = dts.getValue(Member.class);
list.add(member);
}
listView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
btnDlt.setEnabled(false);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Boolean a=true;
Member member=adapter.getItem(position);
Toast.makeText(Retreivedata.this,"Do u want to delete this record!!",Toast.LENGTH_LONG).show();
if (a==true)
{
btnDlt.setEnabled(true);
}else{
btnDlt.setEnabled(false);
}
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Member member= adapter.getItem(position);
Intent intent = new Intent(Retreivedata.this, Update.class);
intent.putExtra("tem", member);
startActivity(intent);
return false;
}
});
btnDlt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ref.child(member.getMemberId()).removeValue();
Toast.makeText(Retreivedata.this, "Record deleted Successfully",
Toast.LENGTH_LONG).show();
adapter.remove(member);
adapter.clear();
}
});
}
}
My activity for updating record:
public class Update extends AppCompatActivity {
EditText EditTxtName,EditTxtAge,txtPhone,txtHeight;
Member member;
FirebaseDatabase db;
DatabaseReference reff;
Button btnUpdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
EditTxtName = (EditText)findViewById(R.id.EditTxtName);
EditTxtAge = (EditText)findViewById(R.id.EditTxtAge);
txtPhone = (EditText)findViewById(R.id.txtPhone);
txtHeight = (EditText)findViewById(R.id.txtHeight);
btnUpdate = (Button)findViewById(R.id.btnUpdate);
final Member member= (Member) getIntent().getSerializableExtra("tem");
EditTxtName.setText(member.getName());
EditTxtAge.setText(member.getAge());
txtPhone.setText(member.getPhone());
txtHeight.setText(member.getHeight());
reff = db.getInstance().getReference().child("Member");
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Update();
}
});
}
private void Update(){
final String mnam = EditTxtName.getText().toString().trim();
final String mage = EditTxtAge.getText().toString().trim();
final String mph = txtPhone.getText().toString().trim();
final String mhei = txtHeight.getText().toString().trim();
final String ID = reff.getKey();
if(TextUtils.isEmpty(mnam)) {
EditTxtName.setText("Plz enter name");}
if(TextUtils.isEmpty(mage)) {
EditTxtName.setText("Plz enter age");}
else{
final Member member = new Member(ID,mnam,mage,mph,mhei);
reff.child("Member").child(ID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
reff = FirebaseDatabase.getInstance().getReference();
reff.child("Member").child(ID).child("name").setValue(mnam);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Toast.makeText(Update.this,"Updated",Toast.LENGTH_LONG).show();
txtHeight.setText("");
txtPhone.setText("");
EditTxtName.setText("");
}
}
}
But after updating record it creates another record.Suggest me what changes has to be done on update button click.
Thnaks!!

First I assume that you implement Serializable for your Member class:
class Member implements Serializable{
.............
.............
.............
}
Since you are passing the member object to the update activity, why not use the ID in it to update the data:
//the update activity
public class Update extends AppCompatActivity {
//this is the member that you pass
Member member;
......
......
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.........
.........
//this is how you retrieve it
member= (Member) getIntent().getSerializableExtra("tem");
//this is your ref
reff = db.getInstance().getReference().child("Member");
........
........
}
//when you update
private void Update(){
final String mnam = EditTxtName.getText().toString().trim();
final String mage = EditTxtAge.getText().toString().trim();
final String mph = txtPhone.getText().toString().trim();
final String mhei = txtHeight.getText().toString().trim();
//update the name field
reff.child(member.getMemberId()).child("name").setValue(mnam);
}

Your problem is this line of code final String ID = reff.getKey()
That call generates a new ID which you then use in your update of the db. You need to replace the call to getKey with the ID of the member you want to update.

Related

Android RecyclerView does not refresh after insert

I have a problem with my RecyclerView.
I have a ProductDetailActivity which shows the detail of a product and i have a RecyclerView with its adapter in it.
The user can click on the give rating button which navigates to the RatingActivity where you can give a rating to the product.
The problem is that when i submit my rating and automatically go back to my RatingActivity, the RecyclerView does not get the recently added rating. i have to go back to my productlist and reclick on the product to see the recently added rating.
Here is my code:
ProductDetailActivity:
public class ProductDetailActivity extends AppCompatActivity {
public AppDatabase appDatabase;
private static final String DATABASE_NAME = "Database_Shop";
private RecyclerView mRecycleviewRating;
private RatingAdapter mAdapterRating;
private Button btnGoToRatingActivity;
List<Rating> ratings;
Product p;
int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_detail);
appDatabase = Room.databaseBuilder(getApplicationContext(),AppDatabase.class,DATABASE_NAME)
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build();
btnGoToRatingActivity = findViewById(R.id.btn_goToRatingActivity);
Intent intent = getIntent();
id = intent.getIntExtra("productid", -1);
// pour montrer tous les ratings d'un produit, tu fais un getall
p = appDatabase.productDAO().getProductById(id);
ImageView imageView = findViewById(R.id.imageDetail);
TextView textViewName = findViewById(R.id.txt_nameDetail);
TextView textViewAuthor = findViewById(R.id.txt_authorDetail);
TextView textViewCategory = findViewById(R.id.txt_categoryDetail);
TextView textViewDetail = findViewById(R.id.txt_descriptionDetail);
Picasso.get().load(p.getProductImage()).fit().centerInside().into(imageView);
textViewName.setText(p.getProductName());
textViewAuthor.setText(p.getProductAuthor());
textViewCategory.setText(p.getProductCategory());
textViewDetail.setText(p.getProductDescription());
ratings = appDatabase.ratingDAO().getRatingByProductId(id);
mRecycleviewRating = findViewById(R.id.recyclerRating_view);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecycleviewRating.setLayoutManager(linearLayoutManager);
//recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapterRating = new RatingAdapter(ratings);
mRecycleviewRating.setAdapter(mAdapterRating);
btnGoToRatingActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ProductDetailActivity.this, RatingActivity.class);
i.putExtra("productid", p.getProduct_id());
startActivity(i);
}
});
mAdapterRating.notifyDataSetChanged();
}
#Override
public void onResume() {
super.onResume();
ratings = appDatabase.ratingDAO().getRatingByProductId(id); // reload the items from database
mAdapterRating.notifyDataSetChanged();
System.out.println(mAdapterRating.ratings.size());
}
}
RatingActivity:
public class RatingActivity extends AppCompatActivity implements RatingGiveFragment.RatingListener {
RelativeLayout mRelativeLayout;
private Button btnConfirmRating;
private EditText mComment;
private RatingBar mRatingBar;
public AppDatabase appDatabase;
private RatingAdapter mAdapter;
List<Rating> ratings;
private static final String DATABASE_NAME = "Database_Shop";
Product p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rating);
appDatabase = Room.databaseBuilder(getApplicationContext(),AppDatabase.class,DATABASE_NAME)
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build();
int idProduct = RatingActivity.this.getIntent().getIntExtra("productid",-1);
p = appDatabase.productDAO().getProductById(idProduct);
mRatingBar = findViewById(R.id.rating_bar);
mComment = findViewById(R.id.txt_insertOpinionText);
mRelativeLayout = findViewById(R.id.activity_rating);
btnConfirmRating = findViewById(R.id.buttonConfirmRating);
mAdapter = new RatingAdapter(ratings);
btnConfirmRating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!checkEmptyFields()) {
Rating rating = new Rating(p.getProduct_id(),UserConnected.connectedUser.getUser_id(),mRatingBar.getRating(), UserConnected.connectedUser.getUsername(), mComment.getText().toString());
appDatabase.ratingDAO().insertRating(rating);
mAdapter.notifyDataSetChanged();
finish();
}else{
Toast.makeText(RatingActivity.this, "Empty Fields", Toast.LENGTH_SHORT).show();
}
}
});
}
/*private class insertRating extends AsyncTask<String,Integer, Integer>
{
#Override
protected Integer doInBackground(String... strings) {
Rating rating = new Rating(Integer.parseInt(strings[0]), Integer.parseInt(strings[1]), Integer.parseInt(strings[2]), strings[3], strings[4]);
appDatabase.ratingDAO().insertRating(rating);
return 1;
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if (integer == 1)
{
Toast.makeText(getApplicationContext(), getString(R.string.createRating), Toast.LENGTH_SHORT).show();
}
}
}*/
#Override
public void ratingChanged(int newRating) {
RatingTextFragment textFragment = (RatingTextFragment) getSupportFragmentManager().findFragmentById(R.id.fmt_text);
textFragment.setRating(newRating);
}
private boolean checkEmptyFields(){
if(TextUtils.isEmpty(mComment.getText().toString())){
return true;
}else{
return false;
}
}
}
RatingAdapter:
public class RatingAdapter extends RecyclerView.Adapter<RatingAdapter.RatingViewHolder> {
List<Rating> ratings;
public RatingAdapter(List<Rating> ratings){
this.ratings = ratings;
}
#NonNull
#Override
public RatingViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.rating_row,viewGroup, false);
return new RatingViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RatingViewHolder ratingViewHolder, int position) {
ratingViewHolder.ratingUsername.setText(ratings.get(position).getRatingUsername());
ratingViewHolder.ratingNumber.setText(String.valueOf(ratings.get(position).getRatingNumber()) + "/5");
ratingViewHolder.ratingComment.setText(ratings.get(position).getRatingText());
}
#Override
public int getItemCount() {
return ratings.size();
}
public static class RatingViewHolder extends RecyclerView.ViewHolder{
public TextView ratingUsername;
public TextView ratingNumber;
public TextView ratingComment;
public RatingViewHolder(#NonNull View itemView) {
super(itemView);
ratingUsername = itemView.findViewById(R.id.txt_usernamerating);
ratingNumber = itemView.findViewById(R.id.num_rating);
ratingComment = itemView.findViewById(R.id.txt_ratingComment);
}
}
}
Pictures:
You get no update in the ProductDetailActivity because you are not updating the data object ratings in the ProductDetailActivity that is the basis for the RatingAdapter.
It would be better to use startActivityForResult in the onClick()method of the ProductDetailActivity. Then you need to override the onActivityResult() method in the ProductDetailActivity. Evaluate the return values and update your data source if necessary, then call notifyDataSetChanged.
This is just pseudo code!
Changes to ProductDetailActivity:
btnGoToRatingActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ProductDetailActivity.this, RatingActivity.class);
i.putExtra("productid", p.getProduct_id());
// with this you are telling the activity to expect results and..
//..to deal with them in onActivityResult
startActivityForResult(i, 1);
}
});
// You do not need this next line because setting the adaper triggers the first
//mAdapterRating.notifyDataSetChanged();
}
Add the onActivityResult() method to the ProductDetailActivity.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
// trigger a method to update the data object that is linked to the adapter
ratings = appDatabase.ratingDAO().getRatingByProductId(id);
// and now that the data has actually been updated you can call notifyDataSetChanged!!
mAdapterRating.notifyDataSetChanged();
}
if (resultCode == Activity.RESULT_CANCELED) {
//Probably do nothing or make a Toast "Canceled"??
}
}
}
Changes to RatingActivity:
btnConfirmRating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!checkEmptyFields()) {
// I will just assume this works!
Rating rating = new Rating(p.getProduct_id(),UserConnected.connectedUser.getUser_id(),mRatingBar.getRating(), UserConnected.connectedUser.getUsername(), mComment.getText().toString());
appDatabase.ratingDAO().insertRating(rating);
Intent intent = new Intent();
//If you need to return some value.. do it here other you do not need it
//intent.putExtra("result", result);
setResult(Activity.RESULT_OK, intent);
finish();
}else{
Toast.makeText(RatingActivity.this, "Empty Fields", Toast.LENGTH_SHORT).show();
}
}
});
Please be aware in RatingActivity that in btnConfirmRating.setOnClickListener notifying the adapter with mAdapter.notifyDataSetChanged(); does nothing: firstly, because the adapter in the RatingActivity has nothing to do with the adapter in the ProductDetailActivity; secondly: you call finish(); in the next line of code.

I want to dynamically take inputs from a couple of views. How do I do that?

So, I have an activity in my app where I need to take in the number of tickets for different ticket classes that are retrieved from the backend. The number of ticket classes is also variable. How do I take the user input in this case? Each time the countdown_btn or countup_btn is pressed, I need to update an array that holds the number of tickets the user has chosen. How do I do this when the number of ticket classes itself is dynamic?
If the button 'pledge' is clicked, I want to take the respective inputs from each of the views here and somehow communicate it to the next activity using intent.
My app's code:
public class RewardsAndPledgeActivity extends AppCompatActivity {
DatabaseReference mRewardsRef;
RecyclerView rewards_list;
String Artcall_id;
String reward_id[];
Integer counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_rewards);
/* -------- Obtain the Event ID of the item that the user has selected on the RecyclerView ------*/
Intent intent = getIntent();
Artcall_id = intent.getStringExtra("Artcall_id");
/* ----------------------------------------------------------------------------------------------*/
mRewardsRef = FirebaseDatabase.getInstance().getReference().child("Rewards").child(Artcall_id);
rewards_list = (RecyclerView) findViewById(R.id.reward_list);
rewards_list.setHasFixedSize(true);
rewards_list.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Reward_List, RewardsViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Reward_List, RewardsViewHolder>(
Reward_List.class,
R.layout.single_reward_item_layout,
RewardsAndPledgeActivity.RewardsViewHolder.class,
mRewardsRef
) {
#Override
protected void populateViewHolder(final RewardsViewHolder viewHolder, Reward_List model, int position) {
final String reward_id = getRef(position).getKey();
viewHolder.setReward_ticket_amount_txt(model.getReward_ticket_amount_txt());
viewHolder.setReward_ticket_amount_class_name(model.getReward_ticket_amount_class_name());
viewHolder.setReward_ticket_class_desc(model.getReward_ticket_class_desc());
viewHolder.countdown_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer current_ticket_count = Integer.parseInt(viewHolder.ticket_counter.getText().toString());
if(current_ticket_count >0 ) {
viewHolder.ticket_counter.setText(String.valueOf(current_ticket_count - 1));
}
}
});
viewHolder.countup_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer current_ticket_count = Integer.parseInt(viewHolder.ticket_counter.getText().toString());
viewHolder.ticket_counter.setText(String.valueOf(current_ticket_count + 1));
}
});
}
};
rewards_list.setAdapter(firebaseRecyclerAdapter);
}
}
My database:
Image of the activity:

Duplicate values when clicking back button - FIXED

Here is my situation.
In this screen, I click the comments button.
The Comment activity opens and I type what I want.
The comment is added successfully in firebase and it takes me back in detail activity.
So far everything is great! Now let's add another comment. Now you see I get duplicate comments.
I hope you see that too. Now in the DetailActivity I have a method called queryFirebaseDb() and that method is called inside both onCreate() and onResume() methods. If I don't use the onResume() method the data will not be display after clicking the back button from the CommentActivity. You see where I am going now right? The question is how to avoid duplicate data after coming back from CommentActivity. Here is my code.
public class DetailActivity extends AppCompatActivity {
ArrayList<Comment> commentArrayList;
ImageView mImageView;
TextView mTitle;
TextView mDate;
TextView mDescription;
TextView mAuthor;
ToggleButton mFavBtn;
private TextView noCommentsTextView;
private TextView commentsTextView;
private ImageButton imageButton;
private FloatingActionButton mShareBtn;
private String newsTitle;
private String newsImage;
private String newsDate;
private String newsDescription;
private static String NEWS_SHARE_HASHTAG = "#EasyNewsApp";
private String date1;
private String date2;
private String newsUrl;
private String newsAuthor;
private Cursor favoriteCursor;
private DatabaseReference mDatabase;
private static Bundle bundle = new Bundle();
private Uri uri;
private RecyclerView mRecyclerView;
private DisplayCommentsAdapter displayCommentsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
mAuthor = (TextView) findViewById(R.id.detail_author);
mImageView = (ImageView) findViewById(R.id.detail_image_view);
mTitle = (TextView) findViewById(R.id.detail_title);
mDate = (TextView) findViewById(R.id.detail_publish_date);
mDescription = (TextView) findViewById(R.id.detail_description);
noCommentsTextView = (TextView)findViewById(R.id.noCommentsTextView);
commentsTextView = (TextView)findViewById(R.id.commentsTextView);
mShareBtn = (FloatingActionButton) findViewById(R.id.share_floating_btn);
mFavBtn = (ToggleButton) findViewById(R.id.fav_news_btn);
imageButton = (ImageButton)findViewById(R.id.detail_comment_image_btn);
mRecyclerView = (RecyclerView)findViewById(R.id.recycler_comments);
LinearLayoutManager manager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(manager);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.addItemDecoration(new SimpleDividerItemDecoration(this));
commentArrayList = new ArrayList<>();
mDatabase = FirebaseDatabase.getInstance().getReference();
mFavBtn.setTextOn(null);
mFavBtn.setText(null);
mFavBtn.setTextOff(null);
newsAuthor = i.getStringExtra("author");
newsImage = i.getStringExtra("image");
newsTitle = i.getStringExtra("newsTitle");
newsDate = i.getStringExtra("date");
newsDescription = i.getStringExtra("description");
newsUrl = i.getStringExtra("url");
date1 = newsDate.substring(0, 10);
date2 = newsDate.substring(11, 19);
Picasso.with(this).load(newsImage)
.placeholder(R.drawable.ic_broken_image)
.into(mImageView);
mTitle.setText(newsTitle);
mAuthor.setText("Author: " + newsAuthor);
mDescription.setText(newsDescription);
mDate.setText(date2 + ", " + date1);
mShareBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent shareIntent = createShareNewsIntent();
startActivity(shareIntent);
}
});
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent commentIntent = new Intent(DetailActivity.this, CommentActivity.class);
commentIntent.putExtra("newsTitle",newsTitle);
startActivity(commentIntent);
}
});
/**
* Handling the add/remove news part. We check if the specific news article
* exists in favourite.db.
*/
favoriteCursor = getContentResolver().query(FavouriteContract.FavouriteEntry.CONTENT_URI,
null,
FavouriteContract.FavouriteEntry.COLUMN_NEWS_TITLE + "=?",
new String[]{newsTitle},
null);
/**
* If yes then set the toggle button to true
*/
if (favoriteCursor.getCount() > 0) {
try {
mFavBtn.setChecked(true);
} finally {
favoriteCursor.close();
}
}
/**
* Else click the toggle button to add the news article as favourite
*/
mFavBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, final boolean isChecked) {
/**
* If checked the add the news article as favourite.
*/
if (isChecked) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
ContentValues contentValues = new ContentValues();
contentValues.put(FavouriteContract.FavouriteEntry.COLUMN_NEWS_TITLE, newsTitle);
contentValues.put(FavouriteContract.FavouriteEntry.COLUMN_NEWS_AUTHOR, newsAuthor);
contentValues.put(FavouriteContract.FavouriteEntry.COLUMN_NEWS_DESCRIPTION, newsDescription);
contentValues.put(FavouriteContract.FavouriteEntry.COLUMN_NEWS_URL, newsUrl);
contentValues.put(FavouriteContract.FavouriteEntry.COLUMN_NEWS_URL_TO_IMAGE, newsImage);
contentValues.put(FavouriteContract.FavouriteEntry.COLUMN_NEWS_PUBLISHED_AT, newsDate);
//The actual insertion in the db.
uri = getContentResolver().insert(FavouriteContract.FavouriteEntry.CONTENT_URI, contentValues);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(DetailActivity.this, "Article with title: " + newsTitle + " was added", Toast.LENGTH_SHORT).show();
}
}.execute();
} else {
/**
* If you uncheck the toggle button then delete the news article from the favourite db.
*/
Uri newsTitleOfFavNews = FavouriteContract.FavouriteEntry.buildNewsUriWithTitle(newsTitle);
//String title = uri.getPathSegments().get(1);// Get the task ID from the URI path
getContentResolver().delete(
newsTitleOfFavNews,
null,
null);
Toast.makeText(DetailActivity.this, "News article deleted from favourites ", Toast.LENGTH_SHORT).show();
}
}
});
queryFirebaseDb();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.detail_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId() == R.id.detail_browser_btn){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(newsUrl));
startActivity(browserIntent);
} if(item.getItemId() == android.R.id.home){
NavUtils.navigateUpFromSameTask(this);
return true;
}
return true;
}
private Intent createShareNewsIntent() {
Intent shareIntent = ShareCompat.IntentBuilder.from(this)
.setType("text/plain")
.setText(NEWS_SHARE_HASHTAG + "\n\n\n" + newsTitle
+ "\n\n\n" + newsDescription
+ "\n\n\n" + newsDate)
.getIntent();
return shareIntent;
}
#Override
protected void onStart() {
super.onStart();
//queryFirebaseDb();
}
#Override
protected void onRestart() {
super.onRestart();
queryFirebaseDb();
//displayCommentsAdapter.notifyDataSetChanged();
}
public void queryFirebaseDb(){
/**
* Querying the database to check if the specific article has comments.
*/
mDatabase = FirebaseDatabase.getInstance().getReference();
Query query = mDatabase.child("comments").orderByChild("newsTitle").equalTo(newsTitle);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for(DataSnapshot dataSnapshots : dataSnapshot.getChildren()){
Comment comment = dataSnapshots.getValue(Comment.class);
//mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
commentArrayList.add(comment);
displayCommentsAdapter = new DisplayCommentsAdapter(this,commentArrayList);
mRecyclerView.setAdapter(displayCommentsAdapter);
displayCommentsAdapter.setCommentsData(commentArrayList);
//Log.d(LOG_TAG, String.valueOf(commentArrayList.size()));
}
noCommentsTextView.setVisibility(View.GONE);
//commentsTextView.setVisibility(View.VISIBLE);
}else{
//Toast.makeText(DisplayComments.this,"There are no comments posted",Toast.LENGTH_LONG).show();
noCommentsTextView.setVisibility(View.VISIBLE);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
/*
#Override
protected void onPause() {
super.onPause();
bundle.putBoolean("ToggleButtonState", mFavBtn.isChecked());
}
#Override
public void onResume() {
super.onResume();
mFavBtn.setChecked(bundle.getBoolean("ToggleButtonState",false));
}
*/
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mFavBtn.setChecked(savedInstanceState.getBoolean("ToggleButtonState",false));
savedInstanceState.putParcelableArrayList("newsList",commentArrayList);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("ToggleButtonState",mFavBtn.isChecked());
outState.getParcelableArrayList("newsList");
}
}
and
public class CommentActivity extends AppCompatActivity {
private static final String REQUIRED = "Required";
private static final String TAG = CommentActivity.class.getSimpleName();
Toolbar toolbar;
DatabaseReference mDatabase;
EditText titleEt;
EditText bodyEt;
Button commentBtn;
String newsTitle;
Intent i;
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment);
toolbar = (Toolbar) findViewById(R.id.comment_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Add comment");
mDatabase = FirebaseDatabase.getInstance().getReference();
titleEt = (EditText) findViewById(R.id.comment_title);
bodyEt = (EditText) findViewById(R.id.comment_body);
commentBtn = (Button) findViewById(R.id.comment_btn);
i = getIntent();
newsTitle = i.getStringExtra("newsTitle");
commentBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
submitPost();
}
});
}
private void submitPost() {
final String title = titleEt.getText().toString();
final String body = bodyEt.getText().toString();
// Title is required
if (TextUtils.isEmpty(title)) {
titleEt.setError(REQUIRED);
return;
}
// Body is required
if (TextUtils.isEmpty(body)) {
bodyEt.setError(REQUIRED);
return;
}
// Disable button so there are no multi-posts
setEditingEnabled(false);
Toast.makeText(this, "Posting...", Toast.LENGTH_SHORT).show();
// [START single_value_read]
final String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
mDatabase.child("Users").child(userId).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user value
User user = dataSnapshot.getValue(User.class);
// [START_EXCLUDE]
if (user == null) {
// User is null, error out
Log.e(TAG, "User " + userId + " is unexpectedly null");
Toast.makeText(CommentActivity.this,
"Error: could not fetch user.",
Toast.LENGTH_SHORT).show();
} else {
// Write new post
name = dataSnapshot.child("name").getValue().toString();
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
String strDate = sdf.format(c.getTime());
writeNewPost(userId,strDate,name,newsTitle, title, body);
}
// Finish this Activity, back to the stream
setEditingEnabled(true);
finish();
// [END_EXCLUDE]
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
// [START_EXCLUDE]
setEditingEnabled(true);
// [END_EXCLUDE]
}
});
// [END single_value_read]
}
private void writeNewPost(String userId,String date,String
commentAuthor, String newsTitle, String commentTitle, String
commentBody){
String key = mDatabase.child("comments").push().getKey();
Comment comment = new Comment(userId, date,
commentAuthor,newsTitle,commentTitle,commentBody);
Map<String, Object> commentValues = comment.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/comments/" + key, commentValues);
mDatabase.updateChildren(childUpdates);
}
private void setEditingEnabled(boolean enabled) {
titleEt.setEnabled(enabled);
bodyEt.setEnabled(enabled);
if (enabled) {
commentBtn.setVisibility(View.VISIBLE);
} else {
commentBtn.setVisibility(View.GONE);
}
}
}
UPDATE
I used this
#Override
protected void onRestart() {
super.onRestart();
finish();
startActivity(getIntent());
}
and voila!
Some stuff I thought you would know when doing Android:
Basically, in android, you need to understand how the life cycle works. So, when you call queryFirebaseDb() from onCreate and from onResume, your app is doing two queries at the same time when activity starts initially.
Lifecycle is like this OnCreate -> onResume. So, it makes sense that when activity starts, query gets executed once on onCreate than on onResume based on your logic.
Answer is here
I noticed that you are using ArrayList<Comment> commentArrayList;, which is an ArrayList structure, which lets you have duplicate data. And, if you look into the behavior of Firebase and how your query is structured, it is like this,
Query query = mDatabase.child("comments").orderByChild("newsTitle").equalTo(newsTitle);
This query means that you are taking all the comments, the previous comment and the new comment, (not just new comment), which I think you either just want (1) to get recently added comment or (2) to replace the old comments with new one.
The first way of doing this sounds complicated to me, though that is not impossible. But, second way of doing is rather easy.
Therefore, to solve this,
simply, replace the arrayList you have with this data.
if(dataSnapshot.exists()){
ArrayList<Comment> tempComments = new ArrayList();
for(DataSnapshot dataSnapshots : dataSnapshot.getChildren()){
Comment comment = dataSnapshots.getValue(Comment.class);
//mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
tempComments.add(comment);
//Log.d(LOG_TAG, String.valueOf(commentArrayList.size()));
}
commentArrayList = tempComments; //assuming you want to store the data in the class fields
displayCommentsAdapter = new DisplayCommentsAdapter(this,commentArrayList);
mRecyclerView.setAdapter(displayCommentsAdapter);
displayCommentsAdapter.setCommentsData(commentArrayList);
noCommentsTextView.setVisibility(View.GONE);
//commentsTextView.setVisibility(View.VISIBLE);
}

Adding datas into an array to list in another activity

Below are the 3 java classes that I am using for my android application development. I would like to add the student data (name and phone number) from the AddActivity to be stored in MainActivity page after clicking "Add". I have researched on this and tried using an array but I am quite confused on how the logic must be for the code to send the datas keyed in AddActivity into the MainActivity page. Can anyone give me a guidance on how to work this out and would really be grateful if you could show me another way rather the way I am trying. I want the data to be stored in a ListView format in the MainActivity after each "Add" I have clicked in the AddActivity page. Do hope that someone will be able to guide me in doing this. Thank you.
MainActivity.java - https://jsfiddle.net/eb1fprnn/
public class MainActivity extends AppCompatActivity {
ListView listView;
Button addStudent;
ArrayList<Student> students = new ArrayList<Student>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add();
}
public void add() {
Student student;
addStudent = (Button) findViewById(R.id.add);
addStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
}
}
AddActivity.java - https://jsfiddle.net/40k5mas2/
public class AddActivity extends AppCompatActivity {
EditText name, phone;
Button add;
int FphoneNumber;
String Fname;
ArrayList<Student> students;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
students = (ArrayList<Student>) getIntent().getSerializableExtra("AddNewStudent");
setContentView(R.layout.activity_add);
edit();
addStudent();
}
public void edit() {
name = (EditText) findViewById(R.id.StudentName);
phone = (EditText) findViewById(R.id.phone);
final Button addStudent = (Button) findViewById(R.id.AddStudent);
name.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
addStudent.setEnabled(!name.getText().toString().trim().isEmpty());
Fname = name.getText().toString();
String phoneNumber = phone.getText().toString();
FphoneNumber = Integer.parseInt(phoneNumber);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void addStudent() {
add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this, MainActivity.class);
intent.putExtra("studentName",name.getText().toString() );
intent.putExtra("phoneNumber",phone.getText().toString());
startActivity(intent);
Student student = new Student(Fname, FphoneNumber);
students.add(student);
}
});
}
public void addStudent(){
add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this,Record.class);
startActivity(intent);
}
});
}
Student.java - https://jsfiddle.net/gy0g7b0s/
public class Student {
String mName;
int mPhoneNumber;
public Student (String name, int number){
mName = name;
mPhoneNumber = number;
};
public String getmName() {
return mName;
}
public String getmName(String newName) {
return (this.mName = newName);
}
public int getmPhoneNumber() {
return this.mPhoneNumber;
}
public int getmPhoneNumber(int newPhoneNumber) {
return (this.mPhoneNumber = newPhoneNumber);
}
#Override
public String toString() {
return String.format("%s\t%f",this.mName, this.mPhoneNumber);
[1] : [Image of Main Activity Page] http://imgur.com/a/pMWt4
[2] : [Image of Add Activity Page] http://imgur.com/a/8YvVc
you can store them as public static variable or create AddActivity constructor and get functions.
String student name; /*add value to this variable #onCreate or wherever in your AddActivity*/
public class AddActivity(/*here to pass data to addactivity*/){
//
}
public String getName(){
return this.name;
}
in another activity
AddActivity ac = new AddActivity();
String someName = ac.getName();
you can use this logic to pass data.
Edit
but if you want to pass data with Intent then just check intenr content onCreate()
Intent i = getIntent();
if(i.hasExtra("intentKey")){//check if it s not null
String name = i.getExtraString("intentKay");
}
The best solution I could find is, declare that array list as static and you could access those wherever you want provided if the classes are in the same package. But if you want to store those values, used shared preferences. Hope this may helps out.

Android - Pass an intent from one activity to another that implements a callback class with Firebase

I have two activities: AddUser and ToDo. ToDo implements a class with callback. ToDo allows the user to create a to do list, and the to do items will be displayed instantly in a recyclerView. User can add, update, or delete to do items in ToDo.
AddUser.java
public class AddUser extends AppCompatActivity implements View.OnClickListener{
private DatabaseReference mUserRef;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_user);
mUserRef = FirebaseDatabase.getInstance().getReference().child("users");
EditText etUserid = (EditText) findViewById(R.id.etUserid);
EditText etUsername = (EditText) findViewById(R.id.etUsername);
Button btnNext = (Button) findViewById(R.id.btnNext);
btnNext.setOnClickListener(this);
}
public void addUser(UserDetails userDetails){
userPushKey = mUserRef.push().getKey();
mUserRef.child(userPushKey).setValue(userDetails);
}
#Override
public void onClick(View v){
if(v == btnNext){
String inputUserid = etUserid.getText().toString();
String inputUsername = etUsername.getText().toString();
addUser(new UserDetails(inputUserid, inputUsername));
Intent intent = new Intent(AddUser.this,ToDo.class);
intent.putExtra("userKeyRef", userPushKey);
startActivity(intent);
}
}
}
ToDo.java
public class ToDo extends AppCompatActivity implements UserTodoAdapter.Callback {
private UserTodoAdapter mAdapter;
#Override
protcted void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo);
mAdapter = new UserTodoAdapter(this);
RecyclerView view = (RecyclerView) findViewById(R.id.recycler_view);
view.setHasFixedSize(true);
view.setAdapter(mAdapter);
}
#Override
public void onEdit(final UserTodo userTodo){
// some functions here
}
}
UserTodoAdapter.java
public class UserTodoAdapter extends RecyclerView.Adapter<UserTodoAdapter.ViewHolder> {
private List<UserTodo> mUserTodo;
private Callback mCallback;
private DatabaseReference mUserTodoRef;
public UserTodoAdapter(Callback callback) {
mCallback = callback;
mUserTodo = new ArrayList<>();
// need to get the push key from AddUser activity
mUserTodoRef = FirebaseDatabase.getInstance.getReference().child(users).child("Need the push key here").child("todo");
mUserTodoRef.addChildEventListener(new TodoChildEventListener());
}
private class TodoChildEventListener implements ChildEventListener{
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s){
// action here
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s){
// action here
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot){
// action here
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s){
// action here
}
#Override
public void onCancelled(DatabaseError databaseError){
// action here
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.a_custom_view, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position){
final UserTodo userTodo = mUserTodo.get(position);
holder.mTodoTitle.setText(userTodo.getTodoTitle());
holder.mTodoDesc.setText(userTodo.gerTodoDesc());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onEdit(userTodo);
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
removeTodo(mUserTodo.get(position));
return true;
}
});
}
#Override
public int getItemCount(){
return mUserTodo.size();
}
public interface Callback{
public void onEdit(UserTodo userTodo);
}
class ViewHolder extends RecyclerView.ViewHolder{
private TextView mTodoTitle;
private TextView mTodoDesc;
public ViewHolder(View itemView){
super(itemView);
mTodoTitle = (TextView) itemView.findViewById(R.id.tvTodoTitle);
mTodoDesc = (TextView) itemView.findViewById(R.id.tvTodoDesc);
}
}
public void addTodo(UserTodo userTodo){
mUserTodoRef.push().setValue(userTodo);
}
public void updateTodo(UserTodo userTodo, String newTodoTitle, String newTodoDesc){
userTodo.setTodoTitle(newTodoTitle);
userTodo.setTodoDesc(newTodoDesc);
mUserTodoRef.child(userTodo.getTodoKey()).setValue(userTodo);
}
public void removeTodo(UserTodo userTodo){
mUserTodoRef.child(userTodo.getTodoKey()).removeValue();
}
}
After the user clicked on Next button in AddUser activity, the user data is straightly added to Firebase, and the user will be redirected to ToDo page where the user can add to do items. How to pass the push key created in AddUser, so that when the user add the to do items, the items will be added under the user?
Is using intent the right way?
Please don't ask me why I need to let user add to do list right after the user is created. It's needed this way.
Thanks
Edit: I'm sorry I should mention that the intent should be passed to UserTodoAdapter class, so that in the Firebase database reference of UserTodoAdapter, I can point the reference to the key passed from AddUser.
I have classes UserDetails and UserTodo, for activities AddUser and ToDo respectively to handle data in Firebase.
Eventually the data will look like this:
{
"users":{
"push_id":{
"userid":"123456",
"username":"My User",
"todo_s":{
"push_id":{
"todo1":"Title1",
"todo_desc":"Description"
},
"push_id":{
"todo2":"Title2",
"todo_desc":"Description"
},
}
},
}
}
Passing via intent (from AddUser to ToDo) is fine. Or you can save it to local storage like SharedPreferences so your user doesn't have to create new user if the user has created a new user.
To pass the key value from your ToDo activity to the adapter, modify the adapter's constructor to accept a key parameter
public UserTodoAdapter(Callback callback, String key) {
mCallback = callback;
mUserTodo = new ArrayList<>();
mUserTodoRef = FirebaseDatabase.getInstance.getReference().child(users).child(key).child("todo");
}
And in the ToDo, instantiate the adapter by passing the string extra from the previous activity (AddUser).
mAdapter = new UserTodoAdapter(this, getIntent().getStringExtra("key"));

Categories

Resources