How can set text in Fragment between Adapter?
Explain:
Fragment use explor.xml layout
Adapter use store_list.xml layout
Because I had used LocationListener in Fragment, so when I got the latitude and longitude, as same time I still got lat and lng from firebase DB.
double radLat1 = rad(camperSiteModel1.getCamperSiteLatitude());
double radLat2 = rad(latitude);
double a = radLat1 - radLat2;
double b = rad(camperSiteModel1.getCamperSiteLongitude()) - rad(longitude);
double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
+ Math.cos(radLat1) * Math.cos(radLat2)
* Math.pow(Math.sin(b / 2), 2)));
s = s * EARTH_RADIUS * 1.609344;
s = Math.round(s * 10000) / 10000;
Log.i("distance",s+"");
distance.setText(s);
I set distance = view.findViewById(R.id.distance); in Fragment and set distance.setText(s);
fragment.java
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_explore, container,false);
distance = view.findViewById(R.id.distance);
readDate();
}
private void readCampSite(){
//Firebase code ...
distance.setText(s);
}
Should I set TextView distance in adapter?
Adapter.java
public class ViewHolder extends RecyclerView.ViewHolder {
distance = itemView.findViewById(R.id.distance);
}
And final, how can setText in distance in fragment list.xml?
I got this error:
Attempt to invoke virtual method void
android.widget.TextView.setText(java.lang.CharSequence) on a null
object reference
Where has problem?
Related
Hello im trying to add a button but i keep getting this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.addView(android.view.View, android.view.ViewGroup$LayoutParams)' on a null object reference
this is my code, it works well in regular activity, its not working as a fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fav, container, false);
lSecond = (LinearLayout) v.findViewById(R.id.lSecond);
lThird = (LinearLayout) v.findViewById(R.id.lThird);
return v;
}
public void bCreate(String i)
{
LinearLayout.LayoutParams btnParams = new LinearLayout.LayoutParams(matchParent, wrapContent);
Button btnNew = new Button(this.getActivity());
btnNew.setBackgroundResource(R.drawable.button);
btnNew.setTextColor(Color.parseColor("#ffffff"));
btnNew.setText(i);
scale = getResources().getDisplayMetrics().density;
int top = (int) (5 * scale + 0.5f);
int bot = (int) (5 * scale + 0.5f);
if (Second < Third)
{
int left = (int) (10 * scale + 0.5f);
int right = (int) (5 * scale + 0.5f);
btnParams.leftMargin = left;
btnParams.rightMargin = right;
btnParams.topMargin = top;
btnParams.bottomMargin = bot;
lSecond.addView(btnNew, btnParams);
Second++;
btnNew.setOnClickListener(listen);
}
bCreate is getting called in onCreate, and String i - is a String from database
bCreate() is being called too early. You're trying to access lSecond before it has a value. Call bCreate() in onCreateView() just before the return.
I have a navigation drawer activity where i am attaching different fragments
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, rp_fragment.OnFragmentInteractionListener, sensors_fragment.OnFragmentInteractionListener, stats_fragment.OnFragmentInteractionListener {
I'm trying to modify the text property of a textview contained within a fragment but i keep getting a null pointer exception on the view (java.lang.NullPointerException: Attempt to invoke virtual method 'void com.teicrete.alucard.sempi.sensors_fragment.ctv_tvst(int)' on a null object reference).
Mainactivity:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (id == R.id.nav_camera) {
ft.replace(R.id.fragment_placeholder, new rp_fragment());
ft.commit();
} else if (id == R.id.nav_gallery) {
ft.replace(R.id.fragment_placeholder, new sensors_fragment());
ft.commit();
gentempdata();
sensors_fragment sf = (sensors_fragment)fm.findFragmentById(R.id.fragment_sensors);
sf.ctv_tvst(1);
Fragment:
public class sensors_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";
TextView ctv_tv;
TextView otv_tv;
View view;
...
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_sensors, container, false);
TextView ctv_tv = (TextView)view.findViewById(R.id.ctv_tv);
TextView otv_tv = (TextView)view.findViewById(R.id.otv_tv);
//ctv_tv.setText("Test"); Only this works
return view;
}
...
public void ctv_tvst(int mtext) {
ctv_tv.setText(mtext);
}
I've looked at similar posts here but i was not able to resolve my issue. The only place where i am able to modify the textview is within the onCreateView of the fragment (see code above). If i try to do it from the mainactivity or anywhere else i get the null pointer error.
Any insights?
Edit: Please see my response in android_griezmann's post.
For now, i am doing everything that i need to do, inside the fragment classes themselves and then i load them. I would still like to figure out why i can't access its methods or views externally.
Change those lines from onCreateView:
TextView ctv_tv = (TextView)view.findViewById(R.id.ctv_tv);
TextView otv_tv = (TextView)view.findViewById(R.id.otv_tv);
To:
ctv_tv = (TextView)view.findViewById(R.id.ctv_tv);
otv_tv = (TextView)view.findViewById(R.id.otv_tv);
Currently you are assigning reference to new object by TextView ctv_tv but actually you want this reference to be assigned to class field so you don't have to add TextView.
Your problem is Fragment itself not the TextView. You are getting fragment object as null not the textview.
So try to find the fragment like the below.
if (id == R.id.nav_gallery) {
ft.replace(R.id.fragment_placeholder, new sensors_fragment(),"YOUR_TAG_NAME");
ft.commit();
gentempdata();
sensors_fragment sf = (sensors_fragment) fm.findFragmentByTag("YOUR_TAG_NAME");
sf.ctv_tvst(1);
}
Also change this method too!
public void ctv_tvst(int mtext) {
ctv_tv.setText("" + mtext);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
TextView ctv_tv = (TextView)getView().findViewById(R.id.ctv_tv);
TextView otv_tv = (TextView)getView().findViewById(R.id.otv_tv);
}
override onactivity created, and then refer your views.. Infact it is the best place to get reference to your views withot getting NullPointer Exception
If you want to pass data while replacing or adding then pass the data in your fragment constructor like below
else if (id == R.id.nav_gallery) {
ft.replace(R.id.fragment_placeholder, new sensors_fragment("your data"));
ft.commit();
Then in your fragmet change the textview value based on the constructor's data
Here is the problem. Just remove the TextView
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_sensors, container, false);
**TextView** ctv_tv = (TextView)view.findViewById(R.id.ctv_tv);
**TextView** otv_tv = (TextView)view.findViewById(R.id.otv_tv);
//ctv_tv.setText("Test"); Only this works
return view;
}
Replace the following code
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_sensors,container, false);
TextView ctv_tv = (TextView)view.findViewById(R.id.ctv_tv);
TextView otv_tv = (TextView)view.findViewById(R.id.otv_tv);
//ctv_tv.setText("Test"); Only this works
return view;
}
with
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_sensors,container, false);
ctv_tv = (TextView)view.findViewById(R.id.ctv_tv);
otv_tv = (TextView)view.findViewById(R.id.otv_tv);
//ctv_tv.setText("Test"); Only this works
return view;
}
Create a variable String ctv_tv_string and assign the value in ctv_tvst() method do not assign to the TextView. it would not throw an error as you are not referring any ui element after this in oncreateview ctv_tv.setText(ctv_tv_string)
I've been searching for a while now, but I can't seem to find an answer to the following question:
Why does onCreateView never get triggered? This code is the code generated by Android Studio when creating a new MainActivity plus some of the code I wrote.
I want to use setTextConfig(...,...,...) to set the text in the text fields. But I can't seem to get them using findviewbyid(R.id....); because v is always null, even getView(); returns null.
public static class PlaceholderFragment extends Fragment {
private View v;
private EditText etCustomerName, etDeviceID;
private Spinner select;
public PlaceholderFragment() {
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_main, container, false);
return v;
}
public void setTextConfig(String customerName, String selectedOption, int deviceID){
View vv = getView();
//init form controls
etCustomerName = (EditText)vv.findViewById(R.id.etCustomerName);
etDeviceID = (EditText)v.findViewById(R.id.etDeviceId);
select = (Spinner)v.findViewById(R.id.select);
etCustomerName.setText(customerName);
ArrayAdapter adapter = (ArrayAdapter)select.getAdapter();
int index = adapter.getPosition(selectedOption);
select.setSelection(index);
etDeviceID = (EditText)getView().findViewById(R.id.etDeviceId);
etDeviceID.setText(Integer.toString(deviceID), TextView.BufferType.EDITABLE);
}
}
If you need more detailed info, just ask :)
I am trying to use the method
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new MappingPage();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
I have written a class called MappingPage(), if I try to use the above method, the fragment I create is of type MappingPage because has been extended and hence throw an error as the function returns a fragment (not a MappingPage Object)
EDIT:I am getting an error when I do
Fragment fragment = new MappingPage();
Eclipse tell me that I need to change fragment to type MappingPage, which means i have to change the return type of the function
two Questions
1) How are you supposed to put your custom fragments into this?
2) Why does the dummySectionFrament return a Fragment Object and not a DummySectionFragment object?
thanks in advance
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
here is my class
public class MappingPage extends Fragment
{
private MapView map;
private MapController myMapController;
public static final String ARG_SECTION_NUMBER = "1";
public MappingPage() {
}
public View onCreateView (LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Context context = new ContextThemeWrapper(getActivity(), R.style.fragment_theme);
//LayoutInflater Inflater = inflater.cloneInContext(context);
View view=inflater.inflate(R.layout.fragment_main_dummy, container, false);
return view;
}
#Override
public void onResume() {
map = (MapView)getActivity().findViewById(R.id.openmapview);
map.setBuiltInZoomControls(true);
myMapController = map.getController();
myMapController.setZoom(15);
super.onResume();
}
}
Regarding your first question, this should work. MappingPage is an indirect instance of the Fragment class, and you can therefore return it.
About question two, the method that you call always returns a specific type, like Fragment in the case of getItem(). However, this can be a subclass of that as well, and if you are sure it is, you can safely cast it to that subclass.
I have a class that I assign string values through standard get/set methods. After setting the values it returns them as expected. When I call the class values in another fragment they return null. I can't seem to figure it out.
How I set up the class and set the values.
public class BasicInfo_Assets_Fragment extends Fragment {
View view
public static Store_Model store_model = null;
...
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_basic_info, container, false);
...
zipCode = zip.getText().toString();
// set info
store_model = new Store_Model();
store_model.setZip(zipCode);
Log.v("STORE" , "Zip: " + store_model.getZip());
...
The Log.v prints out: "Zip: 47564" exactly as expected. However when I call the class in another fragment like this it gives me an error.
public class Options_ListFragment extends ListFragment {
View view;
public static Store_Model store_model = BasicInfo_Assets_Fragment.store_model;
....
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_options, container, false);
Log.v("STORE", "Zip: " + store_model.getZip()); <!--- ERROR
As noted in the code, trying to pull that value is giving me a null pointer exception. I do not understand how this class is losing its values. Maybe I just need another pair of eyes. Thanks for the help in advance
Edit
Thanks #Juan Jose Fidalgo and #SJuan76. I figured it out and I changed my code to the following in Options_ListFragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_options, container, false);
if (BasicInfo_Assets_Fragment.store_model != null) {
LinearLayout ll = (LinearLayout) view
.findViewById(R.id.assets_store_info);
ll.setVisibility(View.VISIBLE);
store = (TextView) view.findViewById(R.id.store);
phone = (TextView) view.findViewById(R.id.phone);
address = (TextView) view.findViewById(R.id.address);
city = (TextView) view.findViewById(R.id.city);
zip = (TextView) view.findViewById(R.id.zip);
state = (TextView) view.findViewById(R.id.state);
getStoreInfo();
}
public void getStoreInfo() {
String mStore = BasicInfo_Assets_Fragment.store_model.getStoreNum();
String mPhone = BasicInfo_Assets_Fragment.store_model.getPhoneNum();
String mAddress = BasicInfo_Assets_Fragment.store_model.getAddress();
String mCity = BasicInfo_Assets_Fragment.store_model.getCity();
String mZip = BasicInfo_Assets_Fragment.store_model.getZip();
String mState = BasicInfo_Assets_Fragment.store_model.getState();
store.setText("Store #: " + mStore);
phone.setText("Phone #: " + mPhone);
address.setText("Address: " + mAddress);
city.setText("City: " + mCity);
zip.setText("Zip: " + mZip);
state.setText("State: " + mState);
}
You are creating two variables. One as attribute in BasicInfo_Assets_Fragment, the other as attribute in Option_ListFragment. They are completely different variables.
If you have a reference to the BasicInfo_Assets_Fragment instance (lets call it biaf) in the Option_ListFragment, you can reference its view attribute as biaf.storeModel, and that will give what you want.
Best practice is to make storeModel private and add a getStoreModel() method to the BasicInfo_Assets_Fragment. Also, try to follow Java naming conventions.
The fragment
Options_ListFragment
public static Store_Model store_model = BasicInfo_Assets_Fragment.store_model;
is executed before than
BasicInfo_Assets_Fragment.onCreateView(...)
For this reason, when,
public static Store_Model store_model = BasicInfo_Assets_Fragment.store_model;
is executed, the variable
BasicInfo_Assets_Fragment.store_model
contains null value. So,
Options_ListFragment
public static Store_Model store_model = BasicInfo_Assets_Fragment.store_model;
get a null value.
The fragment
Options_ListFragment
public static Store_Model store_model = BasicInfo_Assets_Fragment.store_model;
is executed when the class Options_ListFragment is loaded by ClassLoader the first time that the class Options_ListFragment is invoked in any place of your code. You should look when Options_ListFragment is invoked.