Work with BroadcastReceiver in many fragments - java

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.

Related

Cannot assign local value to global value

I am just a beginner in java/android. I was trying to pass location latitude and longitude to firebase. So I toast the message to see the value it was showing 0.0. I passed lat and long value from client.getlastlocation to the global value of lat and lon, but it is showing default value 0.0, why is this happening?
public class shopaction extends Fragment implements CompoundButton.OnCheckedChangeListener{
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
Location location;
GoogleApiClient googleApiClient;
FusedLocationProviderClient client;
private String mParam1;
private String mParam2;
String s;
Switch action;
public double lat,lon;
private OnFragmentInteractionListener mListener;
public shopaction() {
}
public static shopaction newInstance(String param1, String param2) {
shopaction fragment = new shopaction();
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) {
return inflater.inflate(R.layout.fragment_shopaction, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
action = (Switch) view.findViewById(R.id.action);
action.setOnCheckedChangeListener(this);
client = LocationServices.getFusedLocationProviderClient(getActivity());
Button button=(Button)view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
client.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
lat=location.getLatitude();
lon=location.getLongitude();
}
});
}
});
client.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
lat=location.getLatitude();
lon=location.getLongitude();
}
});
Toast.makeText(getActivity(),lat+"",Toast.LENGTH_LONG).show();
FirebaseDatabase firebaseDatabase=FirebaseDatabase.getInstance();
DatabaseReference databaseReference=firebaseDatabase.getReference();
databaseReference.child("shop").child("location").setValue(lat);
}
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;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(action.isChecked())
{
Toast.makeText(getActivity(),"Your shop is open",Toast.LENGTH_LONG).show();
action.setText("open");
s="open";
}
else
{
Toast.makeText(getActivity(),"Your shop is closed",Toast.LENGTH_LONG).show();
action.setText("close");
s="close";
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
The problem is that getLastLocation() returns a Task which then operates asynchronously. The location data are not available until the success listener call-back has actually been called. Meanwhile, your code proceeds to display a Toast using the current (default) values of 0 for lat and lon.
One way to fix this is to have your success listener callback display the toast, rather than your main code. So instead of this:
client.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
lat=location.getLatitude();
lon=location.getLongitude();
}
});
Toast.makeText(getActivity(),lat+"",Toast.LENGTH_LONG).show();
// Firebase update code that depends on location data
use this:
client.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
lat=location.getLatitude();
lon=location.getLongitude();
Toast.makeText(getActivity(),lat+"",Toast.LENGTH_LONG).show();
// Firebase update code that depends on location data
}
});

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

Android - Launch Fragment from Activity

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.

Categories

Resources