I'd like to be able to send an object from parsed JSON data displayed on a RecyclerView to a new activity on click. Below is the relevant code:
I've tried a few solutions but I don't get any results. I've been getting this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at athena.sentineljs.com.athena.RVNewsAdapter$NewsViewHolder.onClick(RVNewsAdapter.java:55)
RVNewsAdapter:
public class RVNewsAdapter extends RecyclerView.Adapter<RVNewsAdapter.NewsViewHolder> {
public static final String KEY_LINK = "link";
public static class NewsViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
private static final String TAG = "Hello";
CardView cv;
TextView date;
TextView link;
TextView title;
TextView today;
List<News> news;
public NewsViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cv);
date = (TextView) itemView.findViewById(R.id.date);
link = (TextView) itemView.findViewById(R.id.link);
title = (TextView) itemView.findViewById(R.id.heading);
today = (TextView) itemView.findViewById(R.id.today);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Context context = view.getContext();
Intent intent;
intent = new Intent(context, Details.class);
intent.putExtra("LINK", news.toString());
context.startActivity(intent);
}
}
List<News> news;
RVNewsAdapter(List<News> news) {
this.news = news;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public RVNewsAdapter.NewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itemnewsfeed, viewGroup, false);
NewsViewHolder nvh = new NewsViewHolder(v);
return nvh;
}
#Override
public void onBindViewHolder(NewsViewHolder newsViewHolder, int i) {
newsViewHolder.date.setText(news.get(i).date);
newsViewHolder.link.setText(news.get(i).link);
newsViewHolder.title.setText(news.get(i).title);
newsViewHolder.today.setText(news.get(i).today);
}
#Override
public int getItemCount() {
if (news != null) {
return news.size();
}
return 0;
}
}
Details activity:
public class Details extends AppCompatActivity {
private static final String TAG_LINK = "link";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent in = getIntent();
// Get JSON values from previous intent
String link = in.getStringExtra("link");
// Displaying all values on the screen
TextView lblLink = (TextView) findViewById(R.id.link);
lblLink.setText(link);
Log.d("Details", "Data not shown");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
You should send the news object like this
#Override
public void onClick(View view) {
Context context = view.getContext();
Intent intent = new Intent(context, Details.class);
int clickPosition = getAdapterPosition(); // get position of clicked item
News newObject = news.get(clickPosition); // get clicked new object from news(news is an ArrayList)
intent.putExtra("LINK", newObject);
context.startActivity(intent);
}
Also for pass the object via Intent correctly please see this answer
Related
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.
I have setup a WebViewActivity which gets the URL from the intent. I have setup an onClickListener for my Recyclerview which opens the WebViewActivity and loads the URL. However the WebView does not cache each an every page it opens. What changes should i make in the code?
WebViewActivity.java
public class WebViewActivity extends AppCompatActivity {
WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Search");
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
Intent intent = getIntent();
String url = intent.getStringExtra("url");
myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
myWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl(url);
}
#Override
public void onBackPressed() {
if(myWebView.canGoBack()){
myWebView.goBack();
}else{
super.onBackPressed();
finish();
}
}
}
ArticleAdapter.java
public class ArticleAdapter extends RecyclerView.Adapter<ArticleAdapter.ArticleViewHolder> {
private static final String TAG = "ArticleAdapter";
private Context mContext;
private ArrayList<String> mlist;
private String url;
public ArticleAdapter(Context context, ArrayList<String> list) {
mContext = context;
mlist = list;
}
#Override
public ArticleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.d(TAG, "onCreateViewHolder: called");
Log.d(TAG, "onCreateViewHolder: GOT REQUEST CALLED===================");
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
View view = layoutInflater.inflate(R.layout.article_list, parent, false);
return new ArticleViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ArticleViewHolder articleViewHolder, int i) {
if(mlist.size()!=0){
url = mlist.get(articleViewHolder.getAdapterPosition());
articleViewHolder.name.setText(url);
articleViewHolder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, WebViewActivity.class);
intent.putExtra("url", articleViewHolder.name.getText());
mContext.startActivity(intent);
}
});
}
}
class ArticleViewHolder extends RecyclerView.ViewHolder {
TextView name;
public ArticleViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.tv_title);
}
}
#Override
public int getItemCount() {
return mlist.size();
}
}
You can write URL to the shared preference or file (with append mode), then whenever you need history just read the contents from the location
If you want cache web URLs then there is an option for WebView
Java code
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
websettings.setAppCachePath(getContext().getCacheDir().toString());
websettings.setAppCacheEnabled(true);
websettings.setCacheMode(WebSettings.LOAD_DEFAULT);
this and this I have found useful, please refer these
Hello I'm trying to select an Image in an activity page and that selected image to update in my Fragment page. I've tried what I've learnt previously, but it's not working at all. Below is what I've attempted. I'm still new to android development, so please bear with me.
ProfileSettingsActivity.java:
public class ProfileSettingsActivity extends AppCompatActivity {
ImageView profileImage1;
ImageView profileImage2;
ImageView profileImage3;
ImageView profileImage4;
ImageView profileImage5;
ImageView profileImage6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_settings);
profileImage1 = (ImageView) findViewById(R.id.teamid00);
profileImage2 = (ImageView) findViewById(R.id.teamid01);
profileImage3 = (ImageView) findViewById(R.id.teamid02);
profileImage4 = (ImageView) findViewById(R.id.teamid03);
profileImage5 = (ImageView) findViewById(R.id.teamid04);
profileImage6 = (ImageView) findViewById(R.id.teamid05);
profileImage1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
}
public void setProfilePicture(View view) {
//Creating a Return intent to pass to the Main Activity
Intent returnIntent = new Intent();
//Figuring out which image was clicked
ImageView selectedImage = (ImageView) view;
//Adding stuff to the return intent
returnIntent.putExtra("imageID", selectedImage.getId());
setResult(RESULT_OK, returnIntent);
//Finishing Activity and return to main screen!
finish();
}
}
Below is the Fragment that contains the page I start on from and go to the ProfileSettingsActivity page
PeopleFragment.java:
public class PeopleFragment extends Fragment {
ImageButton settingsButton;
PieChart pieChart;
ImageButton profileImage;
private FirebaseAuth mAuth;
TextView fullName;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_people2, container,
false);
profileImage = (ImageButton) view.findViewById(R.id.imageButton4);
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent settingsClick = new Intent(getActivity(),
ProfileSettingsActivity.class);
getActivity().startActivityForResult(settingsClick,0);
}
});
fullName = (TextView) view.findViewById(R.id.userProfileFullName);
mAuth = FirebaseAuth.getInstance();
return view;
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}
/**
* Updates the view according to the authentication status.
* #param user the current FirebaseUser
*/
private void updateUI(FirebaseUser user) {
if (user != null) {
fullName.setText(user.getDisplayName());
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_CANCELED) return;
//Getting the Avatar Image we show to our users
ImageView avatarImage =
(ImageView)getView().findViewById(R.id.imageButton4);
//Figuring out the correct image
String drawableName = "profile1";
switch (data.getIntExtra("imageID",R.id.teamid00)) {
case R.id.teamid00:
drawableName = "profile1";
break;
case R.id.teamid01:
drawableName = "profile2";
break;
case R.id.teamid02:
drawableName = "profile3";
break;
case R.id.teamid03:
drawableName = "profile4";
break;
case R.id.teamid04:
drawableName = "profile5";
break;
case R.id.teamid05:
drawableName = "profile6";
break;
default:
drawableName = "profile1";
break;
}
int resID = getResources().getIdentifier(drawableName, "drawable",
getActivity().getPackageName());
avatarImage.setImageResource(resID);
}
}
Currently with what I have above, I can move from the fragment page to the activity page and I can press on the buttons to select the images and then the activity closes for me. But when I'm back on the fragment page, the profile image isn't updated at all, and displays the default one.
Try to use startActivityForResult() instead of getActivity().startActivityForResult(). So, change your Fragment code to:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent settingsClick = new Intent(getActivity(),
ProfileSettingsActivity.class);
startActivityForResult(settingsClick,0);
}
});
...
return view;
}
Note: This is not related to your problem.
You can simplify you activity code to this:
public class ProfileSettingsActivity extends AppCompatActivity {
ImageView profileImage1;
ImageView profileImage2;
ImageView profileImage3;
ImageView profileImage4;
ImageView profileImage5;
ImageView profileImage6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_settings);
profileImage1 = (ImageView) findViewById(R.id.teamid00);
profileImage2 = (ImageView) findViewById(R.id.teamid01);
profileImage3 = (ImageView) findViewById(R.id.teamid02);
profileImage4 = (ImageView) findViewById(R.id.teamid03);
profileImage5 = (ImageView) findViewById(R.id.teamid04);
profileImage6 = (ImageView) findViewById(R.id.teamid05);
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
};
profileImage1.setOnClickListener(clickListener);
profileImage2.setOnClickListener(clickListener);
profileImage3.setOnClickListener(clickListener);
profileImage4.setOnClickListener(clickListener);
profileImage5.setOnClickListener(clickListener);
profileImage6.setOnClickListener(clickListener);
}
public void setProfilePicture(View view) {
//Creating a Return intent to pass to the Main Activity
Intent returnIntent = new Intent();
//Figuring out which image was clicked
ImageView selectedImage = (ImageView) view;
//Adding stuff to the return intent
returnIntent.putExtra("imageID", selectedImage.getId());
setResult(RESULT_OK, returnIntent);
//Finishing Activity and return to main screen!
finish();
}
}
Probably you've got some problems with your onActivityResult method. Check these answers.
Also there is a solution that is going to work:
1. Tag your fragments when you create them:
FragmentTransaction fTrans = getFragmentManager().beginTransaction();
fTrans.add(R.id.main_layout, new PeopleFragment(), "PeopleFragmentTag"));
fTrans.commit();
2. Write method in PeopleFragment, which could setImage:
public void updateProfileImage(int profileImgID){
/* Update your image here */
}
3. Get a fragment by tag and call the method:
public void setProfilePicture(View view) {
/* Your code */
PeopleFragment peopleFragment = (PeopleFragment) getFragmentManager().findFragmentByTag("PeopleFragmentTag");
peopleFragment.updateProfileImage(selectedImage.getId());
}
Hope, I helped you somehow. Good luck!
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);
In my application I am about to refresh the current viewed fragment after searching an item from API. My search bar is coming from Fragment activity and, when the result is there, it will be viewed in the second fragment, but the problem is, when I click search, it will reset into the 1st fragment.
Here's my code:
private ViewPager mPager;
private MyPagerAdapter mAdapter;
ImageView settings_btn;
EditText search;
//EditText search;
ImageView community_icon;
ImageView loyalty_icon;
ImageView tokens_icon;
Context context;
public CustomerAccount customerAccount;
private MyPagerAdapter pagerAdapter;
String offer = "cheese";
ProgressDialog progressDialog;
CustomListAdapterMerchant adapter;
String searchname;
ArrayList<RowItemMerchant> rowItem;
JSONObject offerlist;
int i;
JSONObject merchantList;
RowItemMerchant items;
ListView listView;
Bundle extras;
String empty;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
if(savedInstanceState != null){
search.setText(savedInstanceState.getString("Key"));
}
search = (EditText) findViewById(R.id.searchView);
search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
ConstantSearch.SEARCHNAME = search.getText().toString();
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra("IPUTTEDMERCHANT", ConstantSearch.SEARCHNAME);
finish();
startActivity(intent);
Log.d("SearchName",ConstantSearch.SEARCHNAME);
return true;
}
return false;
}
});
search.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// You can identify which key pressed buy checking keyCode value
// with KeyEvent.KEYCODE_
if (keyCode == KeyEvent.KEYCODE_DEL) {
ConstantSearch.SEARCHNAME = "";
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra("IPUTTEDMERCHANT", ConstantSearch.SEARCHNAME);
finish();
startActivity(intent);
Log.e("IME_TEST", "DEL KEY");
}
return false;
}
});
Intent intent = getIntent();
Bundle bd = intent.getExtras();
if(bd != null) {
String getName = (String) bd.get("IPUTTEDMERCHANT");
search.setText(getName);
}
LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
boolean enabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!enabled) {
showDialogGPS();
}
mAdapter = new MyPagerAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.view_pager);
mPager.setAdapter(mAdapter);
final TextView ref1= (TextView) findViewById(R.id.ref1);
final TextView ref2= (TextView) findViewById(R.id.ref2);
final TextView ref3= (TextView) findViewById(R.id.ref);
final ImageView Image1 = (ImageView) findViewById(R.id.image1);
final ImageView Image2 = (ImageView) findViewById(R.id.image2);
final ImageView Image3 = (ImageView) findViewById(R.id.image3);
settings_btn = (ImageView) findViewById(R.id.settings_button);
settings_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent settings = new Intent(DashboardActivity.this, SettingsPromotion.class);
startActivity(settings);
}
});
ref1.setTextColor(ContextCompat.getColor(this, R.color.orange));
Image1.setImageResource(R.drawable.ic_community_on);
ref2.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image2.setImageResource(R.drawable.ic_loyalty_off);
ref3.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image3.setImageResource(R.drawable.ic_tokens_off);
ref1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(0);
setToDefault();
ref1.setTextColor(ContextCompat.getColor(DashboardActivity.this, R.color.orange));
Image1.setImageResource(R.drawable.ic_community_on);
}
});
loyalty.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(1);
setToDefault();
ref2.setTextColor(ContextCompat.getColor(DashboardActivity.this, R.color.orange));
Image2.setImageResource(R.drawable.ic_loyalty_on);
}
});
tokens.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(2);
setToDefault();
ref3.setTextColor(ContextCompat.getColor(DashboardActivity.this, R.color.orange));
Image3.setImageResource(R.drawable.ic_tokens_on);
}
});
}
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);{
String savedText = search.getText().toString();
savedInstanceState.putString("Key", savedText);
}
}
private void showDialogGPS() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Allow \"My App\" to access you location while you use tha app?");
builder.setMessage("My App uses this to help customers find places. connect with merchants and more");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(
new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
builder.setNegativeButton("Ignore", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void setToDefault()
{
TextView ref1 = (TextView) findViewById(R.id.ref1);
TextView ref2 = (TextView) findViewById(R.id.ref2);
TextView ref3 = (TextView) findViewById(R.id.ref3);
ImageView Image1 = (ImageView) findViewById(R.id.image1);
ImageView Image2 = (ImageView) findViewById(R.id.image2);
ImageView Image3 = (ImageView) findViewById(R.id.image3);
ref1.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image1.setImageResource(R.drawable.ic_community_off);
ref2.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image2.setImageResource(R.drawable.ic_loyalty_off);
ref3.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image3.setImageResource(R.drawable.ic_tokens_off);
}
public static class MyPagerAdapter extends FragmentPagerAdapter
{
private static final int NUM_ITEMS = 3;
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
private FragmentOne fragmentOne;
private FragmentTwo fragmentTwo;
private FragmentThree fragmentThree;
public MyPagerAdapter(FragmentManager fm)
{
super(fm);
mFragmentTags = new HashMap<Integer, String>();
fragmentOne = new FragmentOne();
fragmentTwo = new FragmentTwo();
fragmentThree = new FragmentThree();
}
#Override
public int getCount()
{
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position)
{
if (position == 0)
{
return fragmentOne;
}
else if (position == 1)
{
return fragmentTwo;
}
else if (position == 2)
{
return fragmentThree;
}
else
{
Log.e("AuthActivity", "ViewPager invalid position");
return null;
}
}
}