Android - Launch Fragment from Activity - java

i'm trying to launch a Fragment (a Listview) from an Activity.
The switch should start, when a button is clicked.
My Activity extends from Activity, the Fragment extends ListFragment.
I tried
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
AusgabenFragment ausgabenFragment = new AusgabenFragment();
transaction.replace(R.id.contentFragment, ausgabenFragment);
transaction.commit();
and
Intent intent;
intent = new Intent(getApplicationContext(), AusgabenFragment.class);
startActivity(intent);
The error from the intent try:
Unable to find explicit activity class
I know that I dont have to add Fragments to the AndroidManifest
Thanks for all the suggestions
EDIT: to be launched Fragment Source
public class AusgabenFragment extends ListFragment {
// 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 OnAusgabenInteractionListener mListener;
// TODO: Rename and change types of parameters
public static AusgabenFragment newInstance(String param1, String param2) {
AusgabenFragment fragment = new AusgabenFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public AusgabenFragment() {
}
private AusgabenDataSource dataSource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dataSource = new AusgabenDataSource(getActivity()); // context mit getActivity
try {
dataSource.open(); // kann Exception werfen daher try catch
} catch (SQLException e) {
e.printStackTrace();
}
List<Ausgaben> AusgabenList = dataSource.getAllAusgaben();
setListAdapter(new ArrayAdapter<Ausgaben>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, AusgabenList));
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnAusgabenInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent intent = new Intent(getActivity(),AusgabenDetailsActivity.class);
String Titel = l.getItemAtPosition(position).toString();
intent.putExtra("value_title",Titel);
getActivity().startActivity(intent);
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
}
}
public interface OnAusgabenInteractionListener {
// TODO: Update argument type and name
public void onAusgabenInteraction(String id);
}
}

#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnAusgabenInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
This code expects the activity that is hosting the fragment to implement OnAusgabenInteractionListener. It then throws an incorrect exception, to confuse you further.
If you want to use the code, your activity will need to implement OnAusgabenInteractionListener, whatever that is.

Related

Work with BroadcastReceiver in many fragments

I working with a PDA that has a laser scanner. For that I'm working with BroadcastReceiver in many fragment. I have one activity that has a BottomNavigationView to switch between three fragments. I'm using BroadcastReceiver like this :
package com.example.package.fragments;
public class MyFragment 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;
private final static String SCAN_ACTION = "scan.rcv.message";
ScanDevice sm;
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Doing my work
}
};
public MyFragment () {
// Required empty public constructor
}
public static MyFragment newInstance(String param1, String param2) {
CarteGriseFragment fragment = new CarteGriseFragment();
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) {
sm = new ScanDevice();
IntentFilter filter = new IntentFilter();
filter.addAction(SCAN_ACTION);
getContext().registerReceiver(mReceiver, filter);
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_carte_grise, container, false);
return view;
}
// 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 onResume() {
super.onResume();
sm = null;
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
}
#Override
public void onPause() {
super.onPause();
sm = null;
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
sm = null;
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
}
#Override
public void onDestroy() {
super.onDestroy();
sm = null;
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
}
#Override
public void onDestroyView() {
super.onDestroyView();
sm = null;
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
The problem is that, when I move to another fragment, BroadcastReceiver of the first fragment keep working in the second. In fact, when I scan something while being in the second fragment the BroadcastReceiver of the first fragment is called. I searched for many solutions, as you can see in the code above, I tried to unregister the BroadcastReceiver, but not working.
The code of the other fragment is similar to the code above.
I guess the problem is in navigation view all fragments stays in a visible state, hence onPause is not called. you can try to unsubscribe in this method setUserVisibleHint when isVisibleToUser = false
Maybe you can use RxJava.
You say "I have one activity".
Use RxJava like this.
You need to just one BroadcastReceiver in your activity.Listen it when triggered "onReceive" function then you send event with RxJava and listen this event in your fragments.

How to maintain fragment state when switching fragments

In my MainActivity class, I have a BottomNavigationView with 3 tabs that switch between activities (home, search, and personal). Whenever I click on any of the tabs, it pulls up the respective fragment, but I believe that I am calling a new fragment each and every time.
I need these fragments to maintain whatever changes are made in them (similarly to how Instagram does). Each fragment is currently very basic (newly created and unchanged), but I want to set them up in a way in which their states are saved when I switch to another fragment and restored when I go back to them.
Below is code for my main activity and the home fragment.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
navigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.content, new HomeFragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener =
new BottomNavigationView.OnNavigationItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
switch (item.getItemId()){
case R.id.HomeItem:
transaction.replace(R.id.content, new HomeFragment()).commit();
return true;
case R.id.SearchItem:
transaction.replace(R.id.content, new SearchFragment()).commit();
return true;
case R.id.PersonalItem:
transaction.replace(R.id.content, new PersonalFragment()).commit();
return true;
}
return false;
}
};
}
public class HomeFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
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 HomeFragment() {
// Required empty public constructor
}
// 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) {
// 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;
} else {
Toast.makeText(context, "Home Fragment Attached", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
You must use transaction.hide(fragment) and transaction.show(fragment) instead of transaction.replace, since replacing will delete the fragment and add it again, removing its saved state.
Doing it my way will call fragments' onPause and onReaume method, not resetting their state.
Hope it helps!

How to move one fragment to another fragment in android

I am developing an app contains fragments. I cannot move one fragment to another fragment.
When i use this code (reference from android value passing from fragment to fragment using recyclerview not working)
SpeedDialFragment fragobj = new SpeedDialFragment();
Bundle bundle=new Bundle();
bundle.putString("message", "From Activity");
fragobj.setArguments(bundle);
switchFragment(R.layout.fragment_page, fragobj);
It is not working.
My codes are shown below.
MainActivity java:
public class MainActivity extends AppCompatActivity implements PageFragment.OnFragmentInteractionListener {
ViewPager viewPage;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
startService(new Intent(this, LockScreenService.class));
}
private void initView() {
initViewPager();
}
private void initViewPager() {
viewPage = (ViewPager) this.findViewById(R.id.viewpage);
viewPage.setOffscreenPageLimit(3);
viewPage.setCurrentItem(1);
viewPage.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
#Override public Fragment getItem(int position) {
if (position < 2) {
return PageFragment.newInstance("", "");
} else {
return new AmapFragment();
}
}
#Override public int getCount() {
return 3;
}
});
}
#Override public void onFragmentInteraction(Uri uri) {
}
public void loadFragment(int id, Fragment fragment) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(id, fragment, fragment.toString());
ft.addToBackStack(null);
ft.commit();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.happiness.lockscreen.MainActivity"
>
<android.support.v4.view.ViewPager
android:id="#+id/viewpage"
android:layout_width="match_parent"
android:layout_height="match_parent"
></android.support.v4.view.ViewPager>
</RelativeLayout>
fragment_page.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:text="Speed Dial"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/buttonSpeedDial" />
</FrameLayout>
PageFragment.java
public class PageFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
Button button;
Context context;
private OnFragmentInteractionListener mListener;
public PageFragment() {
}
public static PageFragment newInstance(String param1, String param2) {
PageFragment fragment = new PageFragment();
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 view = inflater.inflate(R.layout.fragment_page, container, false);
button = (Button) view.findViewById(R.id.buttonSpeedDial);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("SpeedDialFragment", "clicked : ");
/*SpeedDialFragment fragment = new SpeedDialFragment(); // replace your custom fragment class
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
bundle.putString("key","value"); // use as per your need
fragment.setArguments(bundle);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(viewID,fragment);
fragmentTransaction.commit();*/
SpeedDialFragment fragobj = new SpeedDialFragment();
Bundle bundle=new Bundle();
bundle.putString("message", "From Activity");
fragobj.setArguments(bundle);
switchFragment(R.layout.fragment_page, fragobj);
}
});
return view;
}
public void switchFragment(int id, Fragment fragment) {
if (context == null)
return;
if (context instanceof MainActivity) {
MainActivity mainActivity = (MainActivity) context;
mainActivity.loadFragment(id, fragment);
}
}
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);
}
}
Please help me.
SpeedDialFragment.java
public class SpeedDialFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public SpeedDialFragment() {
// 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 PageFragment.
*/
// TODO: Rename and change types and number of parameters
public static PageFragment newInstance(String param1, String param2) {
PageFragment fragment = new PageFragment();
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) {
String strtext=getArguments().getString("message");
Log.d("SpeedDialFragment", "strtext : "+strtext);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_speeddial, container, false);
}
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);
}
}
if(context==null) return; You have not initialized your context object.
Try this
public void switchFragment(int id, Fragment fragment) {
if (getActivity() instanceof MainActivity) {
MainActivity mainActivity = (MainActivity) getActivity();
mainActivity.loadFragment(id, fragment);
}
}

how to intent with on click button from activity to fragment in android studio

how to intent with on click button from activity to fragment in android studio. please anyone tell me what is exact code to intent from activity to fragment with button click on activity.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mButNext = (Button) findViewById(R.id.btn_next);
mButNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(this, PropertyListFragment.class);
startActivity(i);
}
});
}
}
PropertyListFragment.class
public class PropertyListFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public static PropertyListFragment newInstance(String param1, String param2) {
PropertyListFragment fragment = new PropertyListFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public PropertyListFragment() {
// 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
String strtext = getArguments().getString("pincode");
return inflater.inflate(R.layout.fragment_property_list, 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(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;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
fragment_property_list.xml
<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"
android:orientation="vertical">
<FrameLayout
android:id="#+id/sample_content_fragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
Button mButNext = (Button) findViewById(R.id.btn_next);
mButNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PropertyListFragment plf = PropertyListFragment.newInstance("param1", "param2");
getSupportFragmentManager().beginTransaction().replace(R.id.sample_content_fragment, plf, "tag").commit();
}
});
You use an Intent to open another Activity.
If your goal is to show the Fragment in it's own Activity then create an intent to start the new Activity, and have the target Activity load your Fragment in onCreate. See Adding a Fragment to an Activity
If your goal is to show the Fragment in the same Activity then read slightly further down in the previous link about programmatically add the fragment to an existing ViewGroup

Passing data from activity to swipeable view fragment

Ok, I'm new to android programming and here is my problem. I've got an async task that collects json data from a server on a httpget request and updates a listview fragment in a swipeable view. I want a way to send data(a bunch of strings) from the main TabActivity class to the Tab1Fragment class.
I've done my level best at stripping down the code to the essentials.
NOTE: I've tried the bundle method that I've read in other similar questions, but they all end up throwing NULL pointer exceptions in the fragment, meaning the bundle isn't getting sent.(?)
This is my main Tab Activity:
TabActivity.java
public class TabActivity extends ActionBarActivity implements ActionBar.TabListener {
private String phoneno;
private static String url = "http://my/url/forjson";
//JSON Node Names
private static final String TAG_OPERATOR = "operator";
private static final String TAG_REGNO = "Reg No";
public String operator;
public String regNo;
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Details", "Others"};
Bundle bundle = new Bundle();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
Intent intent = getIntent();
phoneno = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
new JSONParse().execute();
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getSupportActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
/*Private Class to parse JSON*/
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TabActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("finally")
#Override
protected JSONObject doInBackground(String... args) {
//*
JSONParser jParser = new JSONParser();
// Getting JSON from URL
StringBuilder finalUrl = new StringBuilder();
JSONObject jsonForData = new JSONObject();
try{
finalUrl.append(url);
jsonForData = jParser.getJSONFromUrl(finalUrl.toString());
}catch (JSONException e) {
e.printStackTrace();
}
return jsonForData;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
Bundle bundle=new Bundle();
bundle.putString("oper", json.getString(TAG_OPERATOR));
bundle.putString("regNo", json.getString(TAG_REGNO));
mAdapter.getData(bundle);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
In the above code, please understand that the JSONPasrser class that I've instantiated returns a JSONObject from the url and it works. So, no issues there.
Further, my fragment class is a listview as follows:
Tab1Fragment.java
public class Tab1Fragment extends ListFragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
String abc = "No Details Presently Available";
//Fill all string values with something
String[] values = new String[2];
for(int i=0;i<values.length;i++)
values[i] = " ";
//Make Sure number of elements match
try{
values[0] = "Provider: " + getArguments().getString("oper");//Gives a NULL value
values[1] = "No: " + + getArguments().getString("regNo");//Gives a NULL value
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1,values);
// Assign adapter to ListView
setListAdapter(adapter);
}
catch(Exception e){
e.printStackTrace();
Log.w("Error","The App didn't have enough elements specified to populate the listview");
}
return rootView;
}
}
The "abc" string that I've hardcoded should ideally have details sent from the TabActivity class.
I want the above fragment to recieve data from the TabActivity class to populate the listview. Any help is appreciated :)
EDIT: I've changed the adapter class as follows based on Illegal Argument's suggestion.
So now, the bundle is passed as TabActivity->TabsPagerAdapter->Tab1Fragment
But still, NULL value returned.
My Adapter class is now as follows:
TabsPagerAdapter.java
public class TabsPagerAdapter extends FragmentStatePagerAdapter {
Bundle bundle = new Bundle();
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
Fragment fragment = new Tab1Fragment();
this.bundle.putString("operator", "hi");
fragment.setArguments(this.bundle);
return fragment;
case 1:
return new Tab2Fragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 2;
}
public void getData(Bundle bundle){
this.bundle = bundle;
}
}
I can see that you have successfully passed data via a bundle. Please remove this. from your code below:
this.bundle.putString("operator", "hi");
fragment.setArguments(this.bundle);
change it because it is not required to be accessed that way:
bundle.putString("operator", "hi");
fragment.setArguments(bundle);
On your Tab1Fragment.java you can try something like this:
if(getArguments()!=null){
String sentString = getArguments().getString("operator");
}

Categories

Resources