How can I hide some content from showing to recyclerview - java

I am working on code which I copied from somewhere as a learner. The app displays data in recyclerview, this data is coming from firebase database. All is working well, the data is displaying nicely in recyclerview.
My worry now is: i have added another recyclerview in the same activity. So now I have two recyclerviews with these IDs: recyclerview and recyclerview2. They are in one activity but in different layouts, and only one layout is visible at a time, and by clicking the button it hides one layout and shows another. For now the recyclerviews are showing same data.
What i want now is this: In these recyclerviews I have a TextView which changes text time by time. It sometimes shows this text 'CLOSED'. So i want all the data which has a textview which shows 'CLOSED' to be shown on recyclerview2 and will be unavailable on the first recyclerview.
So my issue is to make the data not to display on recyclerview (first one) if the textview is showing 'CLOSED' and i want the recyclerview2 to show only data which has a textview showing this text 'CLOSED'
I do not know where to start from. Below is my MainActivity.java where i want the code to be added.
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView, recyclerView2;
private DatabaseReference mDatabase, vDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
TextView rtrratio, rtrratiopercentage, tppipss, slpipss, commenting, entry, tp, sl, tv1, tv2, tv3;
RelativeLayout rSignals, rCalendar, rLessons, rServices, rContact;
ImageButton imsignals, imcalendar, imlessons, imservices, imcontact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
//defining main buttons (Image buttons)
imsignals = (ImageButton) findViewById(R.id.im_signals_id);
imcalendar = (ImageButton) findViewById(R.id.im_calendar_id);
imlessons = (ImageButton) findViewById(R.id.im_lessons_id);
imservices = (ImageButton) findViewById(R.id.im_services_id);
imcontact = (ImageButton) findViewById(R.id.im_contact_id);
//defining textviews
entry = (TextView) findViewById(R.id.entry);
tppipss = (TextView) findViewById(R.id.tpp);
slpipss = (TextView) findViewById(R.id.slp);
rtrratio = (TextView) findViewById(R.id.riskreward);
rtrratiopercentage = (TextView) findViewById(R.id.rrewardp);
commenting = (TextView) findViewById(R.id.comment);
tp = (TextView) findViewById(R.id.tp);
sl = (TextView) findViewById(R.id.sl);
//bottom navigation
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
//button definitions
Button btnRunning = (Button) findViewById(R.id.sRunning);
Button btnPending = (Button) findViewById(R.id.sPending);
Button btnClosed = (Button) findViewById(R.id.sClosed);
//layouts definitions for bottom navigation
rSignals = (RelativeLayout) findViewById(R.id.rlsignals);
rCalendar = (RelativeLayout) findViewById(R.id.rlcalendar);
rLessons = (RelativeLayout) findViewById(R.id.rllessons);
rServices = (RelativeLayout) findViewById(R.id.rlservices);
rContact = (RelativeLayout) findViewById(R.id.rlcontact);
//layouts definitions for signals layout
final RelativeLayout rRunning = (RelativeLayout) findViewById(R.id.rlRunning);
final LinearLayout rPending = (LinearLayout) findViewById(R.id.rlHistory);
final LinearLayout rClosed = (LinearLayout) findViewById(R.id.rlRating);
//initialize recyclerview and FIrebase objects
//for running signals
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
//for closed signals
recyclerView2 = (RecyclerView) findViewById(R.id.recyclerview2);
recyclerView2.setLayoutManager(new LinearLayoutManager(this));
recyclerView2.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
//for running signals
recyclerView.setLayoutManager(linearLayoutManager);
//for closed signals
recyclerView.setLayoutManager(linearLayoutManager);
//for signals get child as Blogzone
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blogzone");
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (mAuth.getCurrentUser() == null) {
Intent loginIntent = new Intent(MainActivity.this, RegisterActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
}
}
};
/////////////////////////////////////////////////////////////////////////////////////////////
//signals
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
FirebaseRecyclerAdapter<Blogzone, BlogzoneViewHolder> FBRA = new FirebaseRecyclerAdapter<Blogzone, BlogzoneViewHolder>(
Blogzone.class,
R.layout.card_items,
BlogzoneViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(BlogzoneViewHolder viewHolder, Blogzone model, int position) {
final String post_key = getRef(position).getKey().toString();
viewHolder.setPair(model.getPair());
viewHolder.setBuySell(model.getBuysell());
viewHolder.setOpenPrice(model.getOpenprice());
viewHolder.setTakeProfit(model.getTakeprofit());
viewHolder.setStopLoss(model.getStoploss());
viewHolder.setProfitPips(model.getProfitpips());
viewHolder.setLossPips(model.getLosspips());
viewHolder.setComment(model.getComment());
viewHolder.setResult(model.getResult());
viewHolder.setRewarding(model.getRewarding());
viewHolder.setRewardingP(model.getRewardingP());
//viewHolder.setImageUrl(getApplicationContext(), model.getImageUrl());
//viewHolder.setUserName(model.getUsername());
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Intent singleActivity = new Intent(MainActivity.this, SinglePostActivity.class);
// singleActivity.putExtra("PostID", post_key);
// startActivity(singleActivity);
}
});
}
};
//running signals
recyclerView.setAdapter(FBRA);
//closed signals
recyclerView2.setAdapter(FBRA);
}
public static class BlogzoneViewHolder extends RecyclerView.ViewHolder {
View mView;
public BlogzoneViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setPair(String pair) {
TextView post_pair = mView.findViewById(R.id.quote);
post_pair.setText(pair);
}
public void setBuySell(String buySell) {
TextView post_buysell = mView.findViewById(R.id.type);
post_buysell.setText(buySell);
}
public void setOpenPrice(String openPrice) {
TextView post_openprice = mView.findViewById(R.id.entry);
post_openprice.setText(openPrice);
}
public void setTakeProfit(String takeProfit) {
TextView post_takeprofit = mView.findViewById(R.id.tp);
post_takeprofit.setText("Tp: " + takeProfit);
}
public void setStopLoss(String stopLoss) {
TextView post_stoploss = mView.findViewById(R.id.sl);
post_stoploss.setText("Sl: " + stopLoss);
}
public void setProfitPips(String profitPips) {
//nothing
}
public void setLossPips(String lossPips) {
//nothing
}
public void setRewardingP(String comment) {
//nothing
}
public void setComment(String comment) {
//nothing
}
public void setRewarding(String rewarding) {
//nothing
}
public void setResult(String result) {
TextView post_result = mView.findViewById(R.id.status);
post_result.setText("result");
if (!post_result.getText().toString().trim().matches("Take Profit Hit")) {
post_result.setTextColor(Color.parseColor("#ffcc0000"));
} else if (!post_result.getText().toString().trim().matches("Stop Loss Hit")) {
post_result.setTextColor(Color.parseColor("#ff669900"));
} else if (!post_result.getText().toString().trim().matches("Pending...")) {
post_result.setTextColor(Color.parseColor("#000"));
} else {
post_result.setTextColor(Color.parseColor("#ffffff"));
}
}
}}
Help I am stack!

List<Blogzone> openedZones = new ArrayList<>();
List<Blogzone> closedZones = new ArrayList<>();
openedZones.addAll(mDatabase.stream().filter(zone -> zone.isOpened()).collect(Collectors.toList()));
closedZones.addAll(mDatabase.stream().filter(zone -> zone.isClosed()).collect(Collectors.toList()));
FirebaseRecyclerAdapter<Blogzone, BlogzoneViewHolder> FBRAopened = new FirebaseRecyclerAdapter<Blogzone, BlogzoneViewHolder>(
Blogzone.class,
R.layout.card_items,
BlogzoneViewHolder.class,
openedZones
) {
...
}
FirebaseRecyclerAdapter<Blogzone, BlogzoneViewHolder> FBRAclosed = new FirebaseRecyclerAdapter<Blogzone, BlogzoneViewHolder>(
Blogzone.class,
R.layout.card_items,
BlogzoneViewHolder.class,
closedZones
) {
...
}
//running signals
recyclerView.setAdapter(FBRAopened);
//closed signals
recyclerView2.setAdapter(FBRAclosed);

Related

Like hitting counter in recyclerview

How to implement like button hitting count in RecyclerView. I have already created a like button and counter TextView with this code but when I hit the like button the application crashes. This is my code, what's wrong? I am using toggle button for like option and a TextView for counting like hitting.
This is my viewholder
public class WritingsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView MainTitle;
public ImageView Mainimage;
public ImageView Profimage;
public TextView ProfName;
public TextView txv;
public ToggleButton liketglbtn;
public TextView MainDesc, Idvkanme;
private ItemClickListner itemClickListner;
public void setItemClickListner(ItemClickListner itemClickListner) {
this.itemClickListner = itemClickListner;
}
public WritingsViewHolder(View itemView) {
super(itemView);
MainTitle = (TextView)itemView.findViewById(R.id.RTitle);
Mainimage = (ImageView)itemView.findViewById(R.id.rImageView);
Profimage = (ImageView)itemView.findViewById(R.id.Profile_Image);
ProfName = (TextView)itemView.findViewById(R.id.Prof_Name);
MainDesc = (TextView)itemView.findViewById(R.id.rDescriptionTv);
Idvkanme = (TextView)itemView.findViewById(R.id.Idavaka_Name);
txv = (TextView)itemView.findViewById(R.id.tx);
liketglbtn = (ToggleButton) itemView.findViewById(R.id.likeToggleBtn);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
itemClickListner.onClick(v,getAdapterPosition(),false);
}
}
This is my activity
public class WritingsActivity extends AppCompatActivity {
RecyclerView recyclerView;
FirebaseRecyclerOptions<IdavakaModel> options;
FirebaseRecyclerAdapter<IdavakaModel, WritingsViewHolder> adapter;
DatabaseReference MCC;
String categoryId = "";
RecyclerView.LayoutManager layoutManager;
TextView smsCountText;
int pendingSMSCount = 10;
static Button notifCount;
static int mNotifCount = 0;
Button FBcard, YoutubeCard;
private static final String APP_ID = "ca-app-pub-8867939169855032~9998384849";
Button mSaveBtn, mShareBtn;
private long backPressedTime;
private Toast backToast;
private int mCounter = 0;
ToggleButton btn;
TextView txv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_writings);
FBcard = (Button) findViewById(R.id.button1);
FBcard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent toy = new Intent(WritingsActivity.this, IdavakaNewsUploadActivity.class);
startActivity(toy);
WritingsActivity.this.finish();
}
});
MobileAds.initialize(this,APP_ID);
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
//Bottom Navigation Bar
final BottomNavigationView bottomNavigationView = (BottomNavigationView)findViewById(R.id.botmnavigation);
bottomNavigationView.setSelectedItemId(R.id.action_privacy);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.myhome:
startActivity(new Intent(getApplicationContext(),MainActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.action_notification:
startActivity(new Intent(getApplicationContext(),ChristianNewsMainActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.action_privacy:
return true;
}
return false;
}
});
MCC= FirebaseDatabase.getInstance().getReference().child("Writings");
recyclerView = (RecyclerView) findViewById(R.id.readingroom_recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
LoadData(categoryId);
}
private void LoadData(String categoryId) {
options = new FirebaseRecyclerOptions.Builder<IdavakaModel>().setQuery(MCC,IdavakaModel.class).build();
adapter = new FirebaseRecyclerAdapter<IdavakaModel, WritingsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull WritingsViewHolder writingsViewHolder, int i, #NonNull IdavakaModel idavakaModel) {
writingsViewHolder.MainTitle.setText(idavakaModel.getTitle());
writingsViewHolder.MainDesc.setText(idavakaModel.getDesc());
writingsViewHolder.ProfName.setText(idavakaModel.getProfname());
writingsViewHolder.Idvkanme.setText(idavakaModel.getIdavakaname());
Picasso.get().load(idavakaModel.getPostimage())
.into(writingsViewHolder.Mainimage);
Picasso.get().load(idavakaModel.getProfimage())
.into(writingsViewHolder.Profimage);
writingsViewHolder.setItemClickListner(new ItemClickListner() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent detailsIntent = new Intent(WritingsActivity.this, IdavakaDetailActivity.class);
detailsIntent.putExtra("CategoryId", adapter.getRef(position).getKey());
startActivity(detailsIntent);
}
});
writingsViewHolder.liketglbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCounter++;
txv.setText(Integer.toString(mCounter));
}
});
}
#NonNull
#Override
public WritingsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.writngs_items, parent, false);
return new WritingsViewHolder(v);
}
};
adapter.startListening();
recyclerView.setAdapter(adapter);
}
#Override
public void onBackPressed() {
if (backPressedTime + 2000 > System.currentTimeMillis()) {
backToast.cancel();
super.onBackPressed();
WritingsActivity.this.finish();
return;
} else {
backToast = Toast.makeText(getBaseContext(), "See You Soon", Toast.LENGTH_SHORT);
backToast.show();
}
backPressedTime = System.currentTimeMillis();
WritingsActivity.this.finish();
}
public void onCustomToggleClick (View view) {
Toast.makeText(this, "Liked",Toast.LENGTH_SHORT).show();
}
}
You are getting NullPointerException because the TextView you are using is in Activity named txv where you are setting counter. But the problem is you have declared TextView in Activity but have not initialized anywhere in the Activity. You MUST initialize that variable via findViewbyId method before setting values.
Furthermore, you have initialized txv TextView and accessing on Activity that is why you are getting NLP. TextView is a part of Activity layout which you have not Initialized. On the hand you have initialized txv in Adapter which is of no use.

Method used alongside OnCreate() to update an activity?

I have an android studio activity that contains a RecyclerView, Adapter, and an invisible button at the bottom of the activity. Each itemView thats inside the RecyclerView also has a CheckBox. Inside my Adapter Class I have my Checkbox initialized and has something like - if checkbox.isChecked - then make public static int num = 1 else num = 2; This static variable is then sent to my Activity_main where my bottom button that I need to become Visible can be visible using an if statement that says - if Adapter.num == 1 then button.MakeVisible(true);
Issue is that it's in my Oncreate which is only called once the activity is made. The static number is sent no problem but the activity doesn't update to actually show this. I have to restart the activity to have the button actually become visible.
Adapter Class
public static int p = 0;
#Override
public void onBindViewHolder(#NonNull final Adapter.CustomViewHolder holder,
final int position) {
addedCars = new ArrayList<>();
holder.car.setText(mCars.get(position).getCarName());
holder.mCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(holder.mCheckBox.isChecked()){
Log.d("tag1", "checked");
addedCars.add(mCars.get(position));
String x = Integer.toString(addedCars.size());
Log.d("tag1", x );
p = 1;
holder.mButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
else {
Log.d("tag1", "unchecked");
addedCars.remove(mCars.get(position));
p = 2;
}
}
});
}
Activity_Main Class
public class MainActivity extends AppCompatActivity {
RecyclerView mRecyclerView;
Adapter mAdapter;
RecyclerView.LayoutManager mLayoutManager;
Button mButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.RecyclerView);
mButton = findViewById(R.id.button);
ArrayList<Car> cars = new ArrayList<>();
cars.add(new Car("Toyota"));
cars.add(new Car("Ford"));
cars.add(new Car("Tesla"));
mAdapter = new Adapter(cars);
mRecyclerView.setAdapter(mAdapter);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setHasFixedSize(true);
if (mAdapter.p == 1){
mButton.setVisibility(View.VISIBLE);
}
}
}
If you want to send the num p from RecyclerView Adapter to the activity you need an interface to do so following steps to be followed :
have tested my code in android hope this works for you
creating an interface in the adapter
// create an instance of OnItemChangeListener
public OnItemChangeListener onItemChangeListener;
public interface OnItemChangeListener {
void onItemChanged(int p);
}
//set the instance of onItemChangeListener from the main activity
public void setOnItemChangeListener(OnItemChangeListener onItemChangeListener) {
this.onItemChangeListener = onItemChangeListener;
}
holder.mCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(holder.mCheckBox.isChecked()){
Log.d("tag1", "checked");
addedCars.add(mCars.get(position));
String x = Integer.toString(addedCars.size());
Log.d("tag1", x );
p = 1;
/*
* notify updated value using call back
*/
onItemChangeListener.onItemChanged(p);
holder.mButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
2 finally notify update to the main activity
mAdapter = new Adapter(cars);
mAdapter.setOnItemChangeListener(new /*your adapter name */.OnItemChangeListener() {
#Override
public void onItemChanged(int p) {
// here you will get the latest updated value of p
// now you can update you view accordingly
}
});
mRecyclerView.setAdapter(mAdapter);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setHasFixedSize(true);

Firebase create a new object every time I click a button

I have a problem/ question. I want to save different objects to firebase realtime database every time I click a button, but I have a problem because, since I have a Shopping list I click more items and I want to save them to the database but it saves just the last item I clicked and I want to understand what I'm doing wrong. I'm new to Android / Firebase, it's the first time I'm doing it so if anyone can tell me what I'm doing wrong it would be awesome. Thank you so much. I will attach the code and the photo of the database.
Activity :
public class FirebaseSearch extends AppCompatActivity {
private EditText mSearchField;
private ImageButton mSearchBtn;
private ImageButton AddToCart;
private ImageButton Cart;
int position=0;
String searchText="";
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
public static int cart_count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_firebasesearch);
mUserDatabase = FirebaseDatabase.getInstance().getReference("Users");
mSearchField = findViewById(R.id.search_field);
mSearchBtn = findViewById(R.id.search_btn);
mResultList = findViewById(R.id.result_list_cart);
AddToCart = findViewById(R.id.imageButton2);
Cart = findViewById(R.id.cartButton);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(this));
mSearchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText);
}
});
Cart.setOnClickListener(new View.OnClickListener() {
private Object Tag="Activity";
#Override
public void onClick(View v) {
if (cart_count < 1) {
} else {
startActivity(new Intent(FirebaseSearch.this, CartActivity.class));
}
}
});
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(FirebaseSearch.this, "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery = mUserDatabase.orderByChild("Name").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
Users.class,
R.layout.list_layout,
UsersViewHolder.class,
firebaseSearchQuery
) {
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
viewHolder.getDetails(model.getName(), model.getSurname(),model.getPrice());
viewHolder.setDetails(model.getName(), model.getSurname(),model.getPrice());
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
}
#Override
protected void onStart() {
super.onStart();
invalidateOptionsMenu();
}
// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
String nome;
String surname;
Long prezzo;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
ImageButton addToCart = (ImageButton)mView.findViewById(R.id.imageButton2);
addToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Users a = new Users(nome,surname,prezzo);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Cart");
myRef.setValue(a);
}
});
}
public void getDetails(String name,String cognome,Long price){
nome=name;
surname=cognome;
prezzo=price;
}
public void setDetails(String name, String surname, Long price) {
TextView user_name = (TextView) mView.findViewById(R.id.name_text);
TextView user_surname = (TextView)mView.findViewById(R.id.status_text);
TextView user_price = (TextView)mView.findViewById(R.id.price);
user_name.setText(name);
user_surname.setText(surname);
user_price.setText(Long.toString(price));
}
}
}
enter code here
You need to use the push() method:
myRef.push().setValue(a);
Currently the last data you are adding is overriding the data before it. The push() method will create a random ID and separate each user.
Or if you are using firebase authentication then you can use the user uid instead of push() to separate each user that you are saving.

main activity reads the data again from the firebase database after coming back to the mainactivity

this is my MainActivity
private DatabaseReference mDatabaseReference;
private RecyclerView recyclerView;
private PlaceRecyclerAdapter placeRecyclerAdapter;
private List<Places> placesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Places");
placesList = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.action_add)
{
startActivity(new Intent(MainActivity.this,AddPostActivity.class));
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStart() {
super.onStart();
mDatabaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Places places = dataSnapshot.getValue(Places.class);
placesList.add(places);
placeRecyclerAdapter = new PlaceRecyclerAdapter(MainActivity.this,placesList);
recyclerView.setAdapter(placeRecyclerAdapter);
placeRecyclerAdapter.notifyDataSetChanged();
}
I am using this RecyclerAdapter to load cardview cards in the main activity
public PlaceRecyclerAdapter(Context context, List<Places> placesList) {
this.context = context;
this.placesList = placesList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.post_row,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Places places = placesList.get(position);
//String imageUrl= null;
holder.place.setText(places.getPlace());
holder.desc.setText(places.getDesc());
//imageUrl= places.getImage();
//todo: Use piccasso library to load images
//Picasso.with(context).load(imageUrl).into(holder.image);
}
#Override
public int getItemCount() {
return placesList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView place;
public TextView desc;
//public ImageView image;
public ViewHolder(View view) {
super(view);
place = (TextView) view.findViewById(R.id.postTitleList);
desc = (TextView) view.findViewById(R.id.postDescList);
//image = (ImageView) view.findViewById(R.id.postImageList);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION) {
Places clickedDataItem = placesList.get(pos);
//Toast.makeText(v.getContext(), "You clicked " + clickedDataItem.getPlace(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, Details.class);
intent.putExtra("NAME", clickedDataItem.getPlace());
intent.putExtra("DESC", clickedDataItem.getDesc());
intent.putExtra("IMG", clickedDataItem.getImage());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
}
}
and here is my Details activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
dPlace = (TextView) findViewById(R.id.detail_title);
dDesc = (TextView) findViewById(R.id.detail_desc);
dImage = (ImageView) findViewById(R.id.detail_image);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String name = bundle.getString("NAME");
String desc = bundle.getString("DESC");
String img = bundle.getString("IMG");
dPlace.setText(name);
dDesc.setText(desc);
Picasso.with(this).load(img).into(dImage);
now, clicking on a item in MainActivity I am able to go to the Details activity. suppose there are 3 items in database, and at first main activity shows only 3 items. but after going to Details activity, and then coming back to main activity, there are 6 items, the earlier 3 items are repeated. and if again I go to the Details activity and come back, there will be 9 items. I used (Activity)context).finish(); in RecyclerViewAdapter to finish the main activity, but I think it finishes the context from which I am able to get the details.
please help.
Sorry for my bad english.
Your firebase loading data items needs to go inside onCreate() as it will only gets called only once if its on backstack an onStart() will get called twice. So just implement the data item loading logic in onCreate instead of onStart()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Places places = dataSnapshot.getValue(Places.class);
placesList.add(places);
placeRecyclerAdapter = new PlaceRecyclerAdapter(MainActivity.this,placesList);
recyclerView.setAdapter(placeRecyclerAdapter);
placeRecyclerAdapter.notifyDataSetChanged();
}
}
Update
placesList.clear();
placesList.add(places);

Android-Picasso java.lang.IllegalArgumentException: Target must not be null. when the image view is in a custom layout for a alertdialog

I have java.lang.IllegalArgumentException: Target must not be null. when I try to download an image and put it in the imageView By picasso library. let me show you my code:
public class ads_show extends AppCompatActivity {
private Toolbar toolbar;
private ImageView img_view1;
private HashMap<String, Object> hmap;
private ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ads_show);
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
img = (ImageView) findViewById(R.id.ads_show_img);
TextView title = (TextView) findViewById(R.id.title_ads_show);
TextView desc = (TextView) findViewById(R.id.desc_ads_show);
TextView seller = (TextView) findViewById(R.id.seller_ads_show);
TextView phone = (TextView) findViewById(R.id.phone_ads_show);
TextView email = (TextView) findViewById(R.id.mail_ads_show);
TextView date = (TextView) findViewById(R.id.date_ads_show);
Bundle ads = getIntent().getExtras();
hmap = (HashMap<String, Object>) ads.get("ads");
Picasso.with(this).load((String) hmap.get("image_path"))
.resize(300, 150)
.into(img);
title.setText((String) hmap.get("title"));
desc.setText((String) hmap.get("description"));
seller.setText((String) hmap.get("seller"));
phone.setText((String) hmap.get("phone"));
email.setText((String) hmap.get("email"));
date.setText((String) hmap.get("date"));
}
public void onFullScreenClick(View v) {
try {
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.fullscreen_image_show,null);
img_view1 = (ImageView) findViewById(R.id.img_fullscreen);
Picasso.with(this).load((String)hmap.get("image_path")).into(img_view1);
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setView(layout);
alert.setCancelable(true);
alert.setNeutralButton("exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
} catch (Exception e) {
Log.i("app_error", "Full screen" + e.toString());
}
}
public void onBtnBackClick(View v) {
finish();
}
}
My problem is with onFullScreenClick method. and the image view in the onCreate method works fine.
You are forget to bind ImageView like ...
change in this line ...
img_view1 = (ImageView)layout.findViewById(R.id.img_fullscreen);

Categories