I'm making a simple app that adds a location to the list fragment in main page, and as I add more addresses to the list, whenever configuration changes, those addresses are carried over, which is expected.
However as you will see below, the empty list text shows up for some reason, and seems like when I add another new address hereafter, it will add to the very first place of the list.
Below is my main activity :
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation, mCurrentLocation;
private double currentLatitude, currentLongitude;
private String lastUpdateTime, addressMessage = null;
private AddressResultReceiver resultReceiver;
private MainList listFragment = new MainList();
//private boolean mRequestStatus = true;
private MaterialDialog dialog;
public boolean mAddressRequested = false;
private FragmentManager mFragmentManager;
private final String FRAGMENT_TAG = "main_list_tag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.build();
mFragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.add(R.id.list_frame, listFragment);
fragmentTransaction.commit();
dialog = new MaterialDialog(this)
.setTitle("Select an address")
.setPositiveButton("SELECT", new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
listFragment.list.add(addressMessage);
listFragment.mAdapter.notifyDataSetChanged();
}
})
.setNegativeButton("CANCEL", new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
FloatingActionButton floatingActionButton = (FloatingActionButton) findViewById(R.id.fab_button);
//LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkAirPlaneMode(getApplicationContext())) {
Toast.makeText(getApplicationContext(), "Air Plane Mode is ON, Please turn off to get location", Toast.LENGTH_LONG).show();
}
else if (!checkNetwork()) {
Toast.makeText(getApplicationContext(),"Unable to reach network, please check network settings",Toast.LENGTH_LONG).show();
}
else if (!checkLocationSettings(getApplicationContext())) {
showLocationSettings();
}
else {
startAddressLookUp();
mAddressRequested = true;
dialog.setMessage(addressMessage);
dialog.show();
}
}
});
}
#Override
public void onStart() {
super.onStart();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.build();
}
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
#Override
public void onResume() {
super.onResume();
if(mGoogleApiClient.isConnected()) {
LocationRequest locationRequest = createLocationRequest();
startLocationUpdates(locationRequest);
}
}
And list fragment class:
public class MainList extends ListFragment implements AdapterView.OnItemClickListener {
private int stateInt;
private final String FRAGMENT_KEY = "saved_fragment";
ArrayList<String> list = new ArrayList<>();
ArrayAdapter<String> mAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.list_fragment, container, false);
/*ListView view = (ListView) v.findViewById(android.R.id.list);
view.setEmptyView(v.findViewById(android.R.id.empty));
return view;*/
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
setListAdapter(mAdapter);
//mAdapter.notifyDataSetChanged();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(), "Item Pressed!", Toast.LENGTH_LONG).show();
}
}
How can avoid this? Am I missing the save application state or something else? Any help would be appreciated! Thanks in advance!
Thanks,
Paul
The onCreate method is called for every orientation change. And in the method you are adding the fragment again. That is why you get this behavior.
Check this for the correct way to do this.
Handling Configuration Changes with Fragments
FragmentManager fm = getFragmentManager();
mTaskFragment = (TaskFragment) fm.findFragmentByTag(TAG_TASK_FRAGMENT);
// If the Fragment is non-null, then it is currently being
// retained across a configuration change.
if (mTaskFragment == null) {
mTaskFragment = new TaskFragment();
fm.beginTransaction().add(mTaskFragment, TAG_TASK_FRAGMENT).commit();
}
Related
The problem I have been facing with the development is that there is a recyclerview inside my fragment which gets disappeared after I switch between two fragments on a particular activity. On the first time when the fragment loads everything works fine but afterwards I don't understand what goes wrong. I had tried to refer to various ways that people had posted over github like notifyDatasetChanged, etc. But nothing seems to work. I would appreciate if someone could help me out with this issue.
So here are my classes.
The ProfileFragment.java :
public class ProfileFragment extends Fragment {
FirebaseAuth firebaseAuth;
FirebaseUser user;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
StorageReference storageReference;
RecyclerView itemRecycler;
List<ModelProfile> modelProfiles;
AdapterProfile adapterProfile;
String storagePath= "Users_Profile_Cover_Image/-";
ImageView avatarIv,dp;
CardView card,cardArrow;
TextView nameTv, emailTv, phoneTv;
Button logout,update;
ExtendedFloatingActionButton fab;
ProgressDialog pd;
//..
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view= inflater.inflate(R.layout.fragment_profile, container, false);
firebaseAuth = FirebaseAuth.getInstance();
user= firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
storageReference= getInstance().getReference();
loadItems();
return view;
}
private void loadItems() {
//Problem could be here
GridLayoutManager layoutManager= new GridLayoutManager(getContext(),3);
itemRecycler.setHasFixedSize(true);
itemRecycler.setLayoutManager(layoutManager);
itemRecycler.setVisibility(View.VISIBLE);
CollectionReference ref =FirebaseFirestore.getInstance().collection("All_Posts");
com.google.firebase.firestore.Query query = ref.whereEqualTo("uid",uid);
FirestoreRecyclerOptions<ModelProfile> options = new FirestoreRecyclerOptions.Builder<ModelProfile>()
.setQuery(query,ModelProfile.class).build();
adapterProfile = new AdapterProfile(options,getActivity());
itemRecycler.setAdapter(adapterProfile);
adapterProfile.startListening();
query.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value,
#Nullable FirebaseFirestoreException e) {
if (e != null) {
return;
}
assert value != null;
Log.i("Size",String.valueOf(value.getDocuments().size()));
if (value.getDocuments().size() > 0) { // List is populated
card.setVisibility(View.GONE);
cardArrow.setVisibility(View.GONE);
} else { // List is empty
card.setVisibility(View.VISIBLE);
cardArrow.setVisibility(View.VISIBLE);
}
}
});
}
//
// #Override
// public void onStart() {
// super.onStart();
// adapterProfile.startListening();
// }
//
//
//
// #Override
// public void onStop() {
// super.onStop();
// adapterProfile.stopListening();
// }
#Override
public void onResume() {
super.onResume();
adapterProfile.startListening();
}
}
Adapter:-
public class AdapterProfile extends FirestoreRecyclerAdapter<ModelProfile,AdapterProfile.MyHolder> {
Context context;
public String im;
public AdapterProfile(#NonNull FirestoreRecyclerOptions<ModelProfile> options, Activity Context) {
super(options);
context = Context;
}
#Override
protected void onBindViewHolder(#NonNull MyHolder holder, int position, #NonNull ModelProfile model) {
String uid = model.getUid();
String uEmail =model.getuEmail();
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//..
}
class MyHolder extends RecyclerView.ViewHolder{
//..
}
Activity on which Fragment switching takes place
public class LandingActivity extends AppCompatActivity {
FirebaseAuth firebaseAuth;
DatabaseReference userDbRef;
FirebaseUser user;
String uid,dp;
ChipNavigationBar chipNavigationBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new InventoryFragment()).commit();
bottomMenu();
}
private void bottomMenu() {
chipNavigationBar.setOnItemSelectedListener(new ChipNavigationBar.OnItemSelectedListener() {
//problem could be here as well.........
#Override
public void onItemSelected(int i) {
Fragment fragment=null;
switch(i) {
case R.id.bottom_nav_2:
fragment = new CltFragment();
break;
case R.id.bottom_nav_3:
fragment = new MaceFragment();
break;
case R.id.bottom_nav_profile:
fragment = new ProfileFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
}
});
}
private void checkUserStatus()
{
FirebaseUser user= firebaseAuth.getCurrentUser();
if(user !=null)
{
uid=user.getUid();
}
else
{
startActivity(new Intent(LandingActivity.this,MainActivity.class));
finish();
}
}
#Override
public void onResume() {
//Problem could be here
super.onResume();
Intent intent = getIntent();
String frag = "";
if(intent.hasExtra("frag")) {
frag = intent.getExtras().getString("frag");
}
else
{
//..
}
switch(frag)
{
//..
case "ProfileFragment":
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ProfileFragment()).commit();
chipNavigationBar.setItemSelected(R.id.bottom_nav_profile,true);
break;
}
}
}
Thanks for having looked at my Problem!
Try using this
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container,new InventoryFragment()).commit();
Instead of this
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new InventoryFragment()).commit();
I want to make an app that has on the main screen a ViewPager with a map and a profile section. Therefore, for position = 0 in the ViewPager, there is the map and for position = 1, there is the profile.
For each one of those two "sections" on the main screen, I have two activities: the map.xml with the MapActivity.java and the profile.xml with Profile.java. Both of those are inflated in the EnumFrag java class, depending on the position ( you see there an if ).
I have two issues:
The first one is that when I try to slide left or right, the map moves, not the ViewPager to the next slide. I tried to put a shape on the edge, but it is not working like the slide gesture is passing through the shape. Any help here, please?
The second is related to the first one, the MapActivity.java class is not even running because onCreate is not running (I put a Toast there so display something and nothing happened). Any help, please? (I create the map class object).
map.xml contains a simple fragment with an id of map.
MapActivity.java:
public class MapActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap map;
private Location me;
private FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101;
#Override
protected void onCreate(Bundle savedInstanceState) {
Toast.makeText(this, "hey din onCreate", Toast.LENGTH_SHORT).show();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
getLastLocation();
}
private void getLastLocation() {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_CODE);
return;
}
Toast.makeText(getApplicationContext(), "hey...", Toast.LENGTH_SHORT).show();
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null){
me = location;
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapActivity.this);
}
else
Toast.makeText(getApplicationContext(), "Deschide-ti locatia", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
MapStyleOptions mapStyleOptions= MapStyleOptions.loadRawResourceStyle(this,R.raw.map_style);
googleMap.setMapStyle(mapStyleOptions);
LatLng point = new LatLng(me.getLatitude(),me.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().position(point).title("Me");
googleMap.animateCamera(CameraUpdateFactory.newLatLng(point));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(point,16));
googleMap.addMarker(markerOptions);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLastLocation();
}
}
}
}
Profile.java
public class Profile extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
EditText username = findViewById(R.id.usernameProfile);
username.setText(MainScreen.getUsername());
}
}
EnumFragment.java
public class EnumFragments extends PagerAdapter {
private Context context;
public EnumFragments(Context context) {
this.context = context;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view;
MapActivity mapActivity = new MapActivity();
switch (position){
case 0:
view = layoutInflater.inflate(R.layout.activity_profile,null);
break;
default:
view = layoutInflater.inflate(R.layout.activity_map,null);
break;
}
ViewPager viewPager = (ViewPager)container;
viewPager.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
ViewPager viewPager = (ViewPager)container;
View view = (View) object;
viewPager.removeView(view);
}
#Override
public int getCount() {
return 2;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
}
MainScreen.java
public class MainScreen extends AppCompatActivity {
private static String username;
private ViewPager viewPager;
private EnumFragments enumFragments;
private static int userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
Bundle extras = getIntent().getExtras();
userID = extras.getInt("userID");
username = extras.getString("username");
viewPager = findViewById(R.id.mainSlider);
EnumFragments enumFragments = new EnumFragments(this);
viewPager.setAdapter(enumFragments);
}
public static int getUserID() {
return userID;
}
public static String getUsername() {
return username;
}
#Override
public void onBackPressed() {
//Nothing
}
}
Why you don't add the MapActivity into the MainScreen Activity. You even don't use the MapActivity in your PagerAdapter class. I would make an other attribute in the constructor of your PagerAdapter, after this :
private MapActivity current;
public EnumFragments(MapActivity map_activity)
{
this.current = map_activity;
}
then I would put a getter method in the map_activity, wich returns a view, where you can see the current GoogleMap or other features.
Your problem is that you don't use the new MapActivity...
I hope that may helps you
Not able to pass the retrived list of data from retrofit to a recyclerview in fragment!
Tried some solutions but not working!
I have tried creating methods in fragment and passing but not working!
Getting null!
Activity
TabLayout tabLayout;
ViewPager viewPager;
RecyclerView recyclerView;
//vars
private Dto dto;
List<Post_DTO> post_dto_list=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
dto=new Dto();
UpdateList();
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
tabLayout=(TabLayout)findViewById(R.id.tabLayout);
viewPager=(ViewPager)findViewById(R.id.viewPager);
tabLayout.addTab(tabLayout.newTab().setText("Dashboard"));
tabLayout.addTab(tabLayout.newTab().setText("Converations"));
tabLayout.addTab(tabLayout.newTab().setText("Profile"));
PostFragment pf=new PostFragment();
pf.passData(getApplicationContext(),post_dto_list);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
//ft.add(R.id.posts_recyclerview, ft);
ft.addToBackStack(null);
ft.commit();
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final MyAdapter adapter = new MyAdapter(this,getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
System.out.println(tab.getPosition());
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void UpdateList() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(getString(R.string.postUrl))
.addConverterFactory(GsonConverterFactory.create())
.build();
PostsInterface postsInterface =retrofit.create(PostsInterface.class);
Call<Post_DTO_Resp> call= postsInterface.getPosts();
call.enqueue(new Callback<Post_DTO_Resp>() {
#Override
public void onResponse(Call<Post_DTO_Resp> call, Response<Post_DTO_Resp> response) {
//pDialog.dismiss();
if(!response.isSuccessful())
{
Toast.makeText(getApplicationContext(),"Loading the posts!",Toast.LENGTH_SHORT).show();
}
Post_DTO_Resp posts = response.body();
post_dto_list=posts.getPost_dto_list();
//dto.setList(post_dto_list);
}
#Override
public void onFailure(Call<Post_DTO_Resp> call, Throwable t) {
//pDialog.dismiss();
if(t.getMessage().equals("End of input at line 1 column 1 path $"))
{
Toast.makeText(getApplicationContext(), "There are no posts!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Api Error!", Toast.LENGTH_LONG).show();
}
}
});
}
}
Fragment!
public class PostFragment extends Fragment {
RecyclerView recyclerView;
View v;
Dto dtobject;
private static final String DESCRIBABLE_KEY = "list";
private Describable mDescribable;
List<Post_DTO> post_dto_list;
public PostFragment() {
// Required empty public constructor
}
public void passData(Context context, List<Post_DTO> list) {
//mContext = context;
post_dto_list = list;
// mIndex = pos;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
v=inflater.inflate(R.layout.fragment_posts, container, false);
recyclerView=(RecyclerView) v.findViewById(R.id.posts_recyclerview);
RecyclerViewAdapter recyclerViewAdapter=new RecyclerViewAdapter(getContext(),post_dto_list);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(recyclerViewAdapter);
//listupdater();
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Just want to get the post_dto_list from Activity to fragment class!
Suggestions please!
You can use a bundle to pass a list from activity to fragment.
In activity:
Bundle bundle = new Bundle();
bundle.putSerializable("list", mList);
mFragment.setArguments(bundle);
And then in your fragment:
mList = getIntent().getExtras().getSerializable("list"));
But the POJO that your list contains should be parcelable ( Parcelable better than Serializable).
Your POJO should be something like:
public class MyPOJO implements Parcelable {
For more info refer this.
I am trying to refresh a RecyclerView by assigning a new adapter to the RecyclerView but it is throwing a NullPointerException.
I have created a TabLayout which has three tabs and when you reselect the first tab the method is called to refresh the RecyclerView. But, I am getting a NullPointerException on recyclerViewAdapter.notifyDataSetChanged();. I have initialized recyclerViewAdapter in the onCreateView(); but I still get an Exception.
EDIT :
This is a fragment not an Activity, I cannot setContentView();. Please read the question before down voting or doing anything not helpful.
Please suggest a proper way if I am doing it wrong.
Fragment which has the RecyclerView :
Tab1.class :
public class Tab1 extends Fragment {
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;
private List<World> worldList;
private OnFragmentInteractionListener mListener;
private DBHelper helper;
private Context myContext;
private View view;
#Override
public void onStart() {
this.helper = new DBHelper(getContext());
recyclerViewAdapter = new RecyclerViewAdapter(getContext(), helper.getList());
super.onStart();
}
public Tab1() {
}
public void update() {
recyclerViewAdapter.notifyDataSetChanged();
}
#Override
public void onCreate(Bundle savedInstanceState) {
this.helper = new DBHelper(getContext());
this.worldList = new ArrayList<>();
this.worldList = helper.getList();
this.recyclerViewAdapter = new RecyclerViewAdapter(getContext(), this.worldList);
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_tab1, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerViewAdapter = new RecyclerViewAdapter(getContext(), worldList);
recyclerView.setAdapter(recyclerViewAdapter);
return view;
}
#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 {
void onFragmentInteraction(Uri uri);
}
}
The method is called from the MainActivity.class(When the Tab is re selected).
MainActivty.class :
public class MainActivity extends AppCompatActivity implements Tab1.OnFragmentInteractionListener, Tab2.OnFragmentInteractionListener, Tab3.OnFragmentInteractionListener {
DBHelper helper;
World world;
Location location;
GPSTracker tracker;
RecyclerViewAdapter adapter;
public static Context CONTEXT = null;
RecyclerView recyclerView;
public Tab1 tab1;
public static final String BROADCAST_ACTION = "e.wolverine2.thewalkingapp";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 123);
CONTEXT = getApplicationContext();
MessageReciever reciever = new MessageReciever(new Message());
Intent intent = new Intent(this, MyService.class);
intent.putExtra("reciever", reciever);
startService(intent);
tracker = new GPSTracker(getApplicationContext());
location = tracker.getLocation();
helper = new DBHelper(getApplicationContext());
tab1 = new Tab1();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
adapter = new RecyclerViewAdapter(getApplicationContext(), helper.getList());
final TabLayout tabLayout = (TabLayout) findViewById(R.id.myTabLayout);
tabLayout.addTab(tabLayout.newTab().setText("LOCATIONS"));
tabLayout.addTab(tabLayout.newTab().setText("TOTAL DISTANCE"));
tabLayout.addTab(tabLayout.newTab().setText("CALS"));
tabLayout.getTabAt(0).setIcon(R.drawable.ic_list);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_person_pin);
tabLayout.getTabAt(2).setIcon(R.drawable.ic_fitness_excercise);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//onError();
final ViewPager viewPager = (ViewPager) findViewById(R.id.myViewPager);
final PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);
viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
if (tab.getPosition() == 0) {
Tab1 tab1 = new Tab1();
tab1.update();
}
}
});
}
public void locationChanged(double longi, double lati) {
final Location location = new Location("");
location.setLatitude(lati);
location.setLongitude(longi);
world = new World();
String timeStamp = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(new Date());
world.setLongitude(location.getLongitude());
world.setLatitiude(location.getLatitude());
world.setDate(timeStamp);
world.setTime(timeStamp);
world.setLocation("Anonymous");
helper.addRow(world);
//tab1.update(getApplicationContext());
}
#Override
public void onFragmentInteraction(Uri uri) {
}
public class Message {
public void displayMessage(int resultCode, Bundle resultData) throws NullPointerException {
double longi = resultData.getDouble("longitude");
double lati = resultData.getDouble("latitude");
locationChanged(longi, lati);
//Toast.makeText(MainActivity.this, "TOASTY X : " + e.getMessage(), Toast.LENGTH_SHORT).show();
//Log.v("TOASTY X : ","" + e.getMessage());
}
}
public void onError() {
helper.onDropTable();
Toast.makeText(this, "TABLE DROPED!", Toast.LENGTH_SHORT).show();
}
}
Logcat :
java.lang.NullPointerException: Attempt to invoke virtual method 'void e.wolverine2.thewalkingapp.RecyclerViewAdapter.notifyDataSetChanged()' on a null object reference
at e.wolverine2.thewalkingapp.Tab1.update(Tab1.java:57)
at e.wolverine2.thewalkingapp.MainActivity$1.onTabReselected(MainActivity.java:101)
at android.support.design.widget.TabLayout.dispatchTabReselected(TabLayout.java:1177)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1136)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1128)
at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1427)
at android.support.design.widget.TabLayout$TabView.performClick(TabLayout.java:1537)
at android.view.View$PerformClick.run(View.java:23985)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6816)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1563)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1451)
Java Tip: When it gets here:
Tab1 tab1 = new Tab1();
tab1.update();
A new Tab is instantiated using the cunstructor:
public Tab1() {
}
in your Tab class. as you see the recyclerView is not initialized up to this point.So the recyclerView is actually Null!
Answer: To correctly implement fragment take a look at this:
https://stackoverflow.com/a/5161143/6094503
What you looking for is the following lines:
Fragment newFragment = new DebugExampleTwoFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(CONTENT_VIEW_ID, newFragment).commit();
but I think you need more study about fragments and how they're added to (or removed from) an activity
I´m trying to udate a ListView in a Fragment the only way it actually will work is if I instanciate the fragment new. adpter.notifyDataSetChanged() is not working? Whay not? Here the Code an Activity and the Fragment:
public class TimerList extends Activity{
private DataSource datasource;
TimerListFragment timerfragment;
IntervalListFragment intervalfragment;
public List<TimerObject> values;
public String name;
public String intervals;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.interval_fragment_container);
datasource = new DataSource(this);
datasource.open();
values = datasource.getAllComments();
if (savedInstanceState == null) {
Toast.makeText(getApplicationContext(), "MADE NEW FRAGMENTS", Toast.LENGTH_SHORT).show();
timerfragment = new TimerListFragment();
intervalfragment = new IntervalListFragment();
}
}
public void delete(Long position){
TimerObject timerobject = datasource.getTimerObject(position);
datasource.deleteComment(timerobject);
values = datasource.getAllComments();
}
#Override
protected void onStart() {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, timerfragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
super.onStart();
}
And my Fragment :
public class TimerListFragment extends ListFragment {
List<TimerObject> values ;
Activity a;
ArrayAdapter<TimerObject> adapter;
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
values = ((TimerList)getActivity()).getValues();
setBar();
adapter = new ArrayAdapter<TimerObject>(getActivity(), android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
super.onCreate(savedInstanceState);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
((TimerList)getActivity()).play(Long.valueOf(position));
super.onListItemClick(l, v, position, id);
}
public void setBar(){
ActionBar actionbar = getActivity().getActionBar();
actionbar.setTitle("Timer List");
}
public void update(){
setBar();
Toast.makeText(getActivity(), "UPDATE", Toast.LENGTH_LONG).show();
values = ((TimerList)getActivity()).getValues();
adapter.notifyDataSetChanged();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.interval_timer_list,
container, false);
return view;
}
#Override
public void onStart() {
update();
lv = getListView();
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {
final TimerObject selected = adapter.getItem(position);
final Dialog d = new Dialog(getActivity());
d.setContentView(R.layout.interval_deletetimer_dialog);
d.setTitle("Delete " + selected.getComment() + "?" );
ImageButton delete = (ImageButton) d.findViewById(R.id.delete);
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((TimerList)getActivity()).delete(Long.valueOf(selected.getId()));
update();
}
});
d.show();
return true;
}
});
super.onStart();
}
I tried to do something similar, and I solved this problem by simply redoing the fragment transaction.
In your case, you could accomplish this within your onListItemClick() method.
you could copy this:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, timerfragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
into your onListItemClick() method in your fragment
This resets the fragment. Unfortunately, this would also set your list to null. A way around this would be to make the values list a private static variable of the TimerListFragment class. That way, any changes made to the list will remain 'saved', and when you reload your fragment, it will be populated with the newly updated list.
hope this helps