NullPointerException on TextView from Fragment - java

I am currently working on a project in which I have text data retrieved from a web page displayed between 3 different tabs declared as fragments.
There's a button refresh at the bottom of each tab & whenever the user presses that button, the app retrieves the most recent data from the web site & displays it in one of the three tabs.
The logic on which the app chooses the tab to write the text into is the following:
Write data into Tab 1 (leftmost). If Tab 1 already contains data, write into Tab 2. If Tab 2 already contains data, write into Tab 3. If all tabs contain data, overwrite data in Tab 1 & start the cycle over.
Here is my code before getting into my problem. I am only posting the relevant code to avoid flooding this message.
MainActivity:
public class MainActivity extends AppCompatActivity implements
Tab1.OnFragmentInteractionListener, Tab2.OnFragmentInteractionListener,
Tab3.OnFragmentInteractionListener{
final static String url = "http://159.203.78.94/rpilog/weatherstation.txt";
public static TextView dataTextTab1;
public static TextView dataTextTab2;
public static TextView dataTextTab3;
static Context context;
public static TabLayout tabLayout;
public static int tabPosition;
public static boolean tab1Used = false;
public static boolean tab2Used = false;
public static boolean tab3Used = false;
public static int positionFactor = -1;
static String TAG;
public static String dataFromURL;
public static TextView test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Text placeholders for the data received from the URL.
dataTextTab1 = (TextView) findViewById(R.id.dataTextTab1);
dataTextTab2 = (TextView) findViewById(R.id.dataTextTab2);
dataTextTab3 = (TextView) findViewById(R.id.dataTextTab3);
context = getApplicationContext();
//Creating the tabs.
tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.addTab(tabLayout.newTab().setText("No data"));
tabLayout.addTab(tabLayout.newTab().setText("No data"));
tabLayout.addTab(tabLayout.newTab().setText("No data"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//ViewPager & PagerAdapter object to allow sliding tabs.
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public static void receiveString(){
RequestQueue queue = Volley.newRequestQueue(context);
//Requests a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dataFromURL = response;
if (positionFactor * 169 + 16 + 3 + 144 <= response.length()) {
if(tab1Used == false) {
tabPosition = 0;
TabLayout.Tab currentTab = tabLayout.getTabAt(tabPosition);
currentTab.setText(response.substring(positionFactor * 169, positionFactor * 169 + 16));
dataTextTab1.setText(response.substring(positionFactor * 169 + 16 + 3, positionFactor * 169 + 16 + 3 + 144));
tab1Used = true;
Log.e(TAG, "1ST TAB REACHED");
}
else if(tab1Used == true && tab2Used == false){
tabPosition = 1;
TabLayout.Tab currentTab = tabLayout.getTabAt(tabPosition);
currentTab.setText(response.substring(positionFactor * 169, positionFactor * 169 + 16));
dataTextTab2.setText(response.substring(positionFactor * 169 + 16 + 3, positionFactor * 169 + 16 + 3 + 144));
tab2Used = true;
Log.e(TAG, "2ND TAB REACHED");
}
else if(tab1Used == true && tab2Used == true && tab3Used == false){
tabPosition = 2;
TabLayout.Tab currentTab = tabLayout.getTabAt(tabPosition);
currentTab.setText(response.substring(positionFactor * 169, positionFactor * 169 + 16));
dataTextTab3.setText(response.substring(positionFactor * 169 + 16 + 3, positionFactor * 169 + 16 + 3 + 144));
tab3Used = true;
Log.e(TAG, "3RD TAB REACHED");
}
if(tab1Used == true && tab2Used == true && tab3Used == true){ //If there's data in all tabs => overwrite oldest.
tabPosition = 0;
TabLayout.Tab currentTab = tabLayout.getTabAt(tabPosition);
currentTab.setText(response.substring(positionFactor * 169, positionFactor * 169 + 16));
dataTextTab1.setText(response.substring(positionFactor * 169 + 16 + 3, positionFactor * 169 + 16 + 3 + 144));
Log.e(TAG, "1ST TAB OVER AGAIN");
tab2Used = false;
tab3Used = false;
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Error in data retrieval", Toast.LENGTH_LONG).show();
}
});
queue.add(stringRequest);
}
public void refresh(View view){ //Refresh action for FAB = onClick fct.
MainActivity.positionFactor++;
Toast.makeText(context, "Page refreshed", Toast.LENGTH_SHORT).show();
receiveString();
}
#Override
public void onFragmentInteraction(Uri uri) {
}
public static void showInfoPopup() { //Show popup info = onClick fct.
if (Menu.infoPopupDialog != null) {
Menu.infoPopupDialog.setContentView(R.layout.popup_layout);
Menu.infoPopupDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Menu.infoPopupDialog.show();
}
}
public static void showLocationPopup(){ //Show popup location = onClick fct.
if(Menu.locationPopupDialog != null){
Menu.locationPopupDialog.setContentView(R.layout.popup_location);
Menu.locationPopupDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Menu.locationPopupDialog.show();
}
}
PagerAdapter:
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNoOfTabs;
public PagerAdapter(FragmentManager fm, int numberOfTabs){
super(fm);
this.mNoOfTabs = numberOfTabs;
}
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
Tab1 tab1 = new Tab1();
return tab1;
case 1:
Tab2 tab2 = new Tab2();
return tab2;
case 2:
Tab3 tab3 = new Tab3();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return mNoOfTabs;
}
}
Tab1:
public class Tab1 extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public Tab1() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Tab1.
*/
// TODO: Rename and change types and number of parameters
public static Tab1 newInstance(String param1, String param2) {
Tab1 fragment = new Tab1();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
MainActivity.dataTextTab1 = rootView.findViewById(R.id.dataTextTab1);
return rootView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Tab2:
public class Tab2 extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public Tab2() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Tab2.
*/
// TODO: Rename and change types and number of parameters
public static Tab2 newInstance(String param1, String param2) {
Tab2 fragment = new Tab2();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_tab2, container, false);
MainActivity.dataTextTab2 = rootView.findViewById(R.id.dataTextTab2);
return rootView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Tab3:
public class Tab3 extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public Tab3() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Tab3.
*/
// TODO: Rename and change types and number of parameters
public static Tab3 newInstance(String param1, String param2) {
Tab3 fragment = new Tab3();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_tab3, container, false);
MainActivity.dataTextTab3 = rootView.findViewById(R.id.dataTextTab3);
return rootView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context="com.myapps.toualbiamine.weathertracker.MainActivity">
<!--<android.support.v7.widget.Toolbar-->
<!--android:id="#+id/toolbar"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="50dp"-->
<!--android:background="#color/colorPrimary"-->
<!--android:minHeight="?attr/actionBarSize"-->
<!--android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"-->
<!--app:popupTheme="#style/ThemeOverlay.AppCompat.Light">-->
<!--<TextView-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:text="Swipe to switch tabs"-->
<!--android:textSize="30dp"/>-->
<!--</android.support.v7.widget.Toolbar>-->
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="30dp"
android:background="#color/textColor"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/pager"
android:background="#color/background">
</android.support.v4.view.ViewPager>
</LinearLayout>
fragment_tab3.xml - fragment_tab1.xml & fragment_tab2.xml are simple copies:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.myapps.toualbiamine.weathertracker.Tab1"
android:orientation="vertical"
android:layout_weight="1"
android:background="#drawable/bg"
android:backgroundTintMode="multiply"
android:backgroundTint="#color/background">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Data"
android:textSize="40dp"
android:layout_gravity="center"
android:layout_marginTop="40dp"
android:textColor="#color/titleColor" />
<TextView
android:id="#+id/dataTextTab3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="120dp"
android:text="Data will come here"
android:textSize="15dp"
android:layout_gravity="center"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.FloatingActionButton
android:id="#+id/floatingActionButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="28dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:clickable="true"
app:backgroundTint="#color/background"
app:fabSize="normal"
app:srcCompat="#drawable/ic_refresh_black_24dp"
android:onClick="refresh"/>
</RelativeLayout>
</LinearLayout>
So, I've been trying to figure out a way around my problem & have done a lot of reading but I've been stuck here for now a week & it's the last part of my project.
Here is the issue. You can see that in my MainActivity class, in the method receiveString(), there is the following line:
dataTextTab3.setText(response.substring(positionFactor * 169 + 16 + 3, positionFactor * 169 + 16 + 3 + 144));
I used the same line for my two other TextViews dataTextTab1 & dataTextTab2 a few lines before in this same method.
This is the part where I parse the data that I want received from the website. The numbers correspond to a formula to determine the indexes of the substring I set the text to.
It works perfectly fine for my two other TextViews but when I reach the third TextView, dataTextTab3, I get a NullPointerException & I can't get my head around it to figure it out.
StackTrace:
E/AndroidRuntime: FATAL EXCEPTION: main Process:
com.myapps.toualbiamine.weathertracker, PID: 22340
java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.TextView.setText(java.lang.CharSequence)' on a
null object reference
at com.myapps.toualbiamine.weathertracker.MainActivity$2.
onResponse(MainActivity.java:139) at
com.myapps.toualbiamine.weathertracker.MainActivity$2
.onResponse(MainActivity.java:108) at
com.android.volley.toolbox.StringRequest.
deliverResponse(StringRequest.java:60) at
com.android.volley.toolbox.StringRequest.
deliverResponse(StringRequest.java:30) at
com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.
run(ExecutorDelivery.java:99) at
android.os.Handler.handleCallback(Handler.java:790) at
android.os.Handler.dispatchMessage(Handler.java:99) at
android.os.Looper.loop(Looper.java:164) at
android.app.ActivityThread.main(ActivityThread.java:6494) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.
run(RuntimeInit.java:438) at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
One more thing, I get that error if I refresh 3 times from the first tab to logically fill all the tabs at once, however, if I refresh the first tab, then go to the second one & refresh it, and then go to the third one & refresh it, I do not get the NullPointerException.
Is there a way to avoid that NPE whatever happens? I would like to make sure that the user can refresh 3 times from the first tab without having the app crashing.
Thank you very much, Community! Please, I place a lot of hope into you right now, be the hero I need.
PSA: not duplicate of "why am I getting a NPE" since I went through most of the posts & I am explicitly declaring and instantiating my variables.

When you start the MainActivity, typically it will instantiate the visible Fragment (tab1) and the next one over (tab2) but not beyond that until you switch tabs. That happens later, after you have already called onCreate. That means that in your onCreate you are getting null for dataTextTab3
You shouldn't be holding references in your activity to views in Fragments, since as they are not guaranteed to exist all the time.
If you want to force them to exist, you can call viewPager.setOffscreenPageLimit(3); to allow more off-screen fragments to be instantiated at startup.

Related

java - How to match the details of a Dialog from RecyclerViewAdapter to another Fragment upon clicking the button

I'm new to android coding, I've tried all the possible solution here and on YouTube but still struggling. I just want how to match the data from a dialog of a fragment to another fragment upon pressing the button. we're working on a simple project. :)
Here is what we want to do.Kindly watch this link:
https://imgur.com/tGdWcfq
We want to change the name that will match the dialog upon clicking the "set parameters' button
here's what we found online the difference is we have a dialog button
https://www.youtube.com/watch?v=ZXoGG2XTjzU
https://www.youtube.com/watch?v=69C1ljfDvl0
Here are the codes
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
Context mContext;
List<specieList> mData;
Dialog myDialog;
public RecyclerViewAdapter(Context mContext, List<specieList> mData) {
this.mContext = mContext;
this.mData = mData;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
Button b;
v = LayoutInflater.from(mContext).inflate(R.layout.row,parent,false);
final MyViewHolder vHolder = new MyViewHolder(v);
myDialog = new Dialog(mContext);
myDialog.setContentView(R.layout.fishpop);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
b = myDialog.findViewById(R.id.toasted);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView toastfish = (TextView) myDialog.findViewById(R.id.dialog_fish_id);
Toast.makeText(mContext,"Parameters are now set for " + toastfish.getText().toString(), Toast.LENGTH_SHORT).show();
// here upon clicking this button click we want to match the details in this dialog to another tab. Kindly watch the link above :)
}
});
vHolder.fish_choices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView dialog_fish = (TextView) myDialog.findViewById(R.id.dialog_fish_id);
TextView dialog_sciname = (TextView) myDialog.findViewById(R.id.dialog_sciname_id);
ImageView dialog_image = (ImageView) myDialog.findViewById(R.id.dialog_image_id);
dialog_fish.setText(mData.get(vHolder.getAdapterPosition()).getFish());
dialog_sciname.setText(mData.get(vHolder.getAdapterPosition()).getSciname());
dialog_image.setImageResource(mData.get(vHolder.getAdapterPosition()).getImage());
myDialog.show();
}
});
return vHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv_fish.setText(mData.get(position).getFish());
holder.tv_sciname.setText(mData.get(position).getSciname());
holder.img.setImageResource(mData.get(position).getImage());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private LinearLayout fish_choices;
private TextView tv_fish;
private TextView tv_sciname;
private ImageView img;
public MyViewHolder(View itemView) {
super(itemView);
fish_choices = (LinearLayout) itemView.findViewById(R.id.choices);
tv_fish = (TextView) itemView.findViewById(R.id.textView1);
tv_sciname = (TextView) itemView.findViewById(R.id.textView2);
img = (ImageView) itemView.findViewById(R.id.image);
}
}
}
Code for overview tab(This tab we want to match the content)
public class overview extends Fragment {
View v2;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public overview() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment overview.
*/
// TODO: Rename and change types and number of parameters
public static overview newInstance(String param1, String param2) {
overview fragment = new overview();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v2 = inflater.inflate(R.layout.fragment_overview, container, false);
Calendar calendar = Calendar.getInstance();
SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss");
String currentDate = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.getTime());
String currentTime = time.format(calendar.getTime());
TextView textViewDate =(TextView) v2.findViewById(R.id.date_id);
textViewDate.setText(currentDate);
TextView textViewTime =(TextView) v2.findViewById(R.id.time_id);
textViewTime.setText(currentTime);
return v2;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Code for Specie tab (this tab we want to refer)
public class specie extends Fragment {
View v;
private RecyclerView myrecyclerview;
private List<specieList> lstspecie;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public specie() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment specie.
*/
// TODO: Rename and change types and number of parameters
public static specie newInstance(String param1, String param2) {
specie fragment = new specie();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lstspecie = new ArrayList<>();
lstspecie.add(new specieList("Nile Tilapia", "Oreochromis niloticus", R.drawable.tilapia));
lstspecie.add(new specieList("Ayungin (Silver Perch)", "Bidyanus bidyanus", R.drawable.ayungin));
lstspecie.add(new specieList("Sugpo (Tiger Prawn)", "Penaeus monodon", R.drawable.hipon));
lstspecie.add(new specieList("Hito (Catfish)", "Siluriformes", R.drawable.hito));
lstspecie.add(new specieList("Giant Gourami", "Osphronemus goramy", R.drawable.giant));
lstspecie.add(new specieList("Bangus (Milkfish)", "Chanos chanos", R.drawable.bangus));
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_specie, container, false);
myrecyclerview = (RecyclerView)v.findViewById(R.id.specie_recycleview);
RecyclerViewAdapter recyclerAdapter = new RecyclerViewAdapter(getContext(), lstspecie);
myrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
myrecyclerview.setAdapter(recyclerAdapter);
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Thank you!
Using object oriented Approach
You can write a function in your activity and you can call a fragment's method from it, as you have your Fragment's reference in your Activity when you initialized it like
In Your Activity
class yourActivity ... {
// your other methods
public void callFragmentMethod(String params) {
// here call your fragment's method
fragment.method(params);
}
}
In your Fragment now
class yourFragment ... {
// your other methods
public void method(String params) {
// here call your fragment's method
here do whatever you want to do it with params
}
}
Now you can call your Activity's method either from another fragment or from Adapter, whatever you want
From Fragment you can call like
((yourActivity)getActivity()).callFragmentMethod(params);
From Adapter
((yourActivity)context).callFragmentMethod(params);
Call below method on your button click..
public void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frameContainer, fragment);
fragmentTransaction.addToBackStack(fragment.toString());
fragmentTransaction.commit();
}
pass frameContainer in constructor of your Adapter like..
new RecyclerViewAdapter(context, list, R.id.frameContainer);

Android Fragment getActivity().getApplicationContext() in onCreateView is null

So I have been trying to implement a feature in my app where all the Posts will be listed to a recyclerView within a Fragment. However, whenever I access getActivity().getApplicationContext(), its returning null.
From what I understand is that getActivity will only return null if the fragment has been detached. I thought that my fragment hasn't been detached yet isince I'm opening it first time.
getActivity().getApplicationContext() is called inside HomeFragment.java.
Here is my code:
HomeFragment.java
public class HomeFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
List<Post> posts = new ArrayList<>();
private RecyclerView postsRecyclerView;
private HomePostsAdapter pAdapter;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
//private Activity fragmentContext;
public HomeFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment HomeFragment.
*/
// TODO: Rename and change types and number of parameters
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
pAdapter = new HomePostsAdapter(posts);
RecyclerView.LayoutManager pLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
postsRecyclerView = (RecyclerView) container.findViewById(R.id.homePostsRcyclerV);
postsRecyclerView.setLayoutManager(pLayoutManager);
postsRecyclerView.setItemAnimator(new DefaultItemAnimator());
postsRecyclerView.setAdapter(pAdapter);
populatePostsDetails();
pAdapter.notifyDataSetChanged();
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void populatePostsDetails() {
posts.add(new Post(1, "A Post: The First One", "Once upon a time, there was this useless app", "July"));
posts.add(new Post(2, "The Story begins today", "It was I the allfather who did it!", "July"));
posts.add(new Post(3, "Another POST!", "what is the point of this thing h8uh?", "July"));
posts.add(new Post(4, "Dandandan", "asdasdasdasdasdasdasdasdasdasd", "July"));
posts.add(new Post(5, "A Post: The First One", "Once upon a time, there was this useless app", "July"));
posts.add(new Post(6, "The Story begins today", "It was I the allfather who did it!", "July"));
posts.add(new Post(7, "Another POST!", "what is the point of this thing h8uh?", "July"));
posts.add(new Post(8, "Dandandan", "asdasdasdasdasdasdasdasdasdasd", "July"));
posts.add(new Post(9, "A Post: The First One", "Once upon a time, there was this useless app", "July"));
posts.add(new Post(10, "The Story begins today", "It was I the allfather who did it!", "July"));
posts.add(new Post(11, "Another POST!", "what is the point of this thing h8uh?", "July"));
posts.add(new Post(12, "Dandandan", "asdasdasdasdasdasdasdasdasdasd", "July"));
}
}
HomePostsAdapter.java
public class HomePostsAdapter extends RecyclerView.Adapter<HomePostsAdapter.CustomViewHolder>{
private List<Post> posts;
public class CustomViewHolder extends RecyclerView.ViewHolder {
public TextView pTitle, pContent;
public CustomViewHolder(View view) {
super(view);
pTitle = (TextView) view.findViewById(R.id.postTitle);
pContent = (TextView) view.findViewById(R.id.postContent);
}
}
public HomePostsAdapter(List<Post> posts){
this.posts = posts;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.posts_list, parent, false);
return new CustomViewHolder(itemView);
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
Post post = posts.get(position);
holder.pTitle.setText(post.getPostTitle());
holder.pContent.setText(post.getPostContent());
}
#Override
public int getItemCount() {
return posts.size();
}
}
Post.java
public class Post {
int id;
String title;
String content;
String date_created;
// sets values for the posts
public Post(int p_id, String p_title, String p_content, String p_date_created) {
this.id = p_id;
this.title = p_title;
this.content = p_content;
this.date_created = p_date_created;
}
public int getPostId() {
return this.id;
}
public String getPostTitle() {
return this.title;
}
public String getPostContent() {
return this.content;
}
public String getPostDateCreated() {
return this.date_created;
}
}
Any help will be greatly appreciated!
Logcat:
03-02 23:18:03.974 3377-3377/com.example.darkestmidnight.lykeyfoods E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.darkestmidnight.lykeyfoods, PID: 3377
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
at com.example.darkestmidnight.lykeyfoods.activities.main_navigation.HomeFragment.onCreateView(HomeFragment.java:85)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Everything you're doing on onCreateView() (except for actually inflating the view), should be moved to onViewCreated(). You're calling container.findViewById(R.id.homePostsRcyclerV) before actually inflating or returning your layout - effectively looking for a RecyclerView in an empty container.
You should instead just return your newly inflated view in onCreateView() and move the logic acting on the view to onViewCreated(), where you are passed the View you just created.

How to initialize a Listview inside a fragment of Tab view android?

I have an activity which has three tabs. One fragment for each tabs. In the xml of the fragment layout I have a listview. I need to initialize this list view and populate it with data from the firebase. How can I do that?
My activity code is
public class AccountActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(AccountActivity.this,AddLeaveActivity.class));
}
});
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(getArguments().getInt(ARG_SECTION_NUMBER) == 1){
View rootView = inflater.inflate(R.layout.fragment_today, container, false);
return rootView;
} else if(getArguments().getInt(ARG_SECTION_NUMBER) == 2){
View rootView = inflater.inflate(R.layout.fragment_tomorrow, container, false);
return rootView;
} else {
View rootView = inflater.inflate(R.layout.fragment_dayafter, container, false);
return rootView;
}
//View rootView = inflater.inflate(R.layout.activity_account, container, false);
//TextView textView = (TextView) rootView.findViewById(R.id.section_label);
//textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
//return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "TODAY";
case 1:
return "TOMORROW";
case 2:
return "DAY AFTER";
}
return null;
}
}
}
and my fragment.java is
public class TodayFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public TodayFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment TodayFragment.
*/
// TODO: Rename and change types and number of parameters
public static TodayFragment newInstance(String param1, String param2) {
TodayFragment fragment = new TodayFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = firebaseDatabase.getReference();
DatabaseReference childRef;
ListView listView;
TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
textView = (TextView) getView().findViewById(R.id.todayfragmentheader);
textView.setText("Inside onCreate Fragment1");
listView = (ListView) getView().findViewById(R.id.listview);
displaylistview("20170130");
}
private void displaylistview(String str){
childRef = databaseReference.child(str);
// //databaseReference = firebaseDatabase.getReferenceFromUrl(leavedate);
FirebaseListAdapter<Leave> firebaseListAdapter = new FirebaseListAdapter<Leave>(
getActivity(),
Leave.class,
R.layout.leavelistview,
childRef
) {
#Override
protected void populateView(View v, Leave model, int position) {
((TextView)v.findViewById(R.id.lv_staffname)).setText(model.getName());
((TextView)v.findViewById(R.id.lv_type)).setText(model.getType());
((TextView)v.findViewById(R.id.lv_duration)).setText(model.getDuration());
}
};
listView.setAdapter(firebaseListAdapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_today, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Here the problem is not only the data is populating but also its not setting the text of the textview. But the data is populating and listing if I am using an activity. So I guess the data retrieving code is correct.
So where can is initialize the listview inside a fragment?

How I can eliminate my duplicate from list

I have a problem with the duplicate items in my list. I want to view my items from my database. If you want, in top of the list, there is the last item from database and if you scroll down you will see the historic (the rest element of database) but I don't know why... I have duplicate items here. Anyone can help me?
Code:
/**
* A fragment representing a list of Items.
* <p/>
* Large screen devices (such as tablets) are supported by replacing the ListView
* with a GridView.
* <p/>
* Activities containing this fragment MUST implement the {#link OnFragmentInteractionListener}
* interface.
*/
public class PlacesFragment extends Fragment implements AbsListView.OnItemClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
public static final int PAGE_SIZE = 5;
public static final int LIST_INIT_SIZE = 1;
ImageView imageView;
String[] test;
String text = "Central Park";
Date data = new Date();
String data_database = String.valueOf(data);
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
final List<PlaceListItem> items = new ArrayList<>();
/**
* The fragment's ListView/GridView.
*/
private AbsListView mListView;
/**
* The Adapter which will be used to populate the ListView/GridView with
* Views.
*/
private ListAdapter mAdapter;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public PlacesFragment() {
}
// TODO: Rename and change types of parameters
public static PlacesFragment newInstance(String param1, String param2) {
PlacesFragment fragment = new PlacesFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
// TODO: Change Adapter to display your content
// mAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, DummyContent.ITEMS);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_place, container, false);
Context ctx = view.getContext();
final DataBase dataBase = new DataBase(getActivity().getApplicationContext());
SQLiteDatabase db = dataBase.getReadableDatabase();
Cursor cr = dataBase.getInformation(dataBase);
cr.moveToFirst();
// if (!db.isOpen()) {
// dataBase.onCreate(db);
// }
// dataBase.onCreate(db);
//ctx.deleteDatabase(DataBase.TABLE_NAME);
final DetectionLocation detectionLocation = new DetectionLocation(ctx);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
Integer val = Integer.valueOf(prefs.getString("sync_frequency", ""));
final String sync_status = String.valueOf(val);
dataBase.insertInformation(dataBase, "Guid", String.valueOf(detectionLocation.getLongitude()), String.valueOf(detectionLocation.getLatitude()), "N", data, sync_status);
mListView = (AbsListView) view.findViewById(android.R.id.list);
for (int i = 0; i < LIST_INIT_SIZE; i++) {
items.add(new PlaceListItem(cr.getString(4), cr.getString(1), cr.getString(2)));
cr.moveToNext();
}
final CustomListAdapter adapter = new CustomListAdapter(getActivity(), items);
// dataBase.insertInformation(dataBase, "Guid", String.valueOf(detectionLocation.getLongitude()), String.valueOf(detectionLocation.getLatitude()), "N", data, sync_status);
EndlessScrollListener scroll = new EndlessScrollListener(PAGE_SIZE) {
Cursor cr = dataBase.getInformation(dataBase);
#Override
public void onLoadMore(int page, int totalItemsCount) {
cr.moveToFirst();
// dataBase.insertInformation(dataBase, "Guid", String.valueOf(detectionLocation.getLongitude()), String.valueOf(detectionLocation.getLatitude()), "N", data, sync_status);
for (int i = 0; i < totalItemsCount; i++) {
if (cr.isLast()) {
break;
}
items.add(new PlaceListItem(cr.getString(4), cr.getString(1), cr.getString(2)));
// adapter.add(new PlaceListItem(cr.getString(4), cr.getString(1), cr.getString(2)));
adapter.add(items.get(i));
cr.moveToNext();
}
adapter.notifyDataSetChanged();
}
};
// mListView.setOnScrollListener(scroll);
// mListView.setAdapter(adapter);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Cursor cr = dataBase.getInformation(dataBase);
cr.moveToFirst();
if (!data.toString().equals(cr.getString(4))) {
dataBase.insertInformation(dataBase, "Guid", String.valueOf(detectionLocation.getLongitude()), String.valueOf(detectionLocation.getLatitude()), "N", data, sync_status);
}
// TODO get newest entries and append on list
//items.add(new PlaceListItem(cr.getString(4), cr.getString(1), cr.getString(2)));
adapter.insert(new PlaceListItem(cr.getString(4), cr.getString(1), cr.getString(2)), 0);//
adapter.notifyDataSetChanged();
// mListView.invalidateViews();
}
});
}
}, 2/*val*/);
mListView.setOnScrollListener(scroll);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(this);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).id);
}
}
/**
* The default content for this Fragment has a TextView that is shown when
* the list is empty. If you would like to change the text, call this method
* to supply the text it should use.
*/
public void setEmptyText(CharSequence emptyText) {
View emptyView = mListView.getEmptyView();
if (emptyView instanceof TextView) {
((TextView) emptyView).setText(emptyText);
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(String id);
}
}
You can see on the following image that there are duplicate items (looking just on date). Link : http://i.stack.imgur.com/thN1Z.png
I have solved this issue passing the data in a set, that automatically remove duplicates.
LinkedHashSet<String> hs = new LinkedHashSet();
hs.addAll(items);
items.clear();
items.addAll(hs);

How to change fragment using Android studio navigation drawer

Hi can someone help me changing fragments using navigation drawer I tried some guides here none of them work
Here's my code
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment;
FragmentManager fragmentManager = getSupportFragmentManager(); // For AppCompat use getSupportFragmentManager
switch(position) {
default:
case 0:
fragment = PlaceholderFragment.newInstance(position + 1);
break;
case 1:
fragment = new profile_fragment();
break;
}
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
I want to add this fragment but I always get an error when click the 2nd item from the navigation drawer
package com.the.healthescort;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class profile_fragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment profile_fragment.
*/
// TODO: Rename and change types and number of parameters
public static profile_fragment newInstance(String param1, String param2) {
profile_fragment fragment = new profile_fragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public profile_fragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_profile_fragment, container, false);
return rootView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
You don't implement OnFragmentInteractionListener( in profile_fragment) in your MainActivity. Because your MainActivity call profile_fragment.
So you need to implement the listener OnFragmentInteractionListener in your MainActivity. Like that:
public class MainActivity extends ActionBarActivity
implements profile_fragment.OnFragmentInteractionListener {
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
use this method for replacing fragmnet :
public void selectItem(int position) {
switch (position) {
case 0:
Fragment fr2 = fragmentManager.findFragmentByTag("orders");
if (fr2 == null) {
fragmentManager
.beginTransaction()
.replace(R.id.sellers_frame_container,
new Sellers_Orders_Fragment(), "orders")
.commit();
} else {
fragmentManager.beginTransaction().show(fr2).commit();
}
break;
case 1:
Fragment fr3 = fragmentManager.findFragmentByTag("add_product");
if (fr3 == null) {
fragmentManager
.beginTransaction()
.replace(R.id.sellers_frame_container,
new Sellers_Add_Product_Fragment(),
"add_product").commit();
} else {
fragmentManager.beginTransaction().show(fr3).commit();
}
break;
}
}
Call this method on listview item click that is in your navigation drawer.
litview.onItemclickListener(.....){
selectItem(postion);
}

Categories