I want to pass dogruYanlis value which is an integer array to these fragments. If I try to handle this with bundle it it sends anything. The array that I received in fragment class is always null. I think that I can't handle with bundle but I don't know how I can solve this problem...
The Activity that I want to send data
package oztiryaki.my;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class result extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private Bundle bundle;
int[] dogruYanlis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
toolbar = (Toolbar) findViewById(R.id.toolbarResult);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
Bundle list = getIntent().getExtras();
if(list == null){
return;
}
dogruYanlis = list.getIntArray("dogruYanlis");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
bundle = new Bundle();
bundle.putIntArray("dogruYanlis", dogruYanlis);
result2015Fragment f15 = new result2015Fragment();
f15.setArguments(bundle);
result2014Fragment f14 = new result2014Fragment();
f14.setArguments(bundle);
result2013Fragment f13 = new result2013Fragment();
f13.setArguments(bundle);
adapter.addFragment(f15, "2015");
adapter.addFragment(f14, "2014");
adapter.addFragment(f13, "2013");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
The one of fragment activity
package oztiryaki.my;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by oztir on 21.02.2016.
*/
public class result2015Fragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.result2015,container,false);
int[] dogruYanlis = getArguments().getIntArray("dogruYanlis");
if(dogruYanlis == null){
Toast.makeText(getActivity(),"null sory:(", Toast.LENGTH_LONG).show();
}
TextView ygs1hp = (TextView) v.findViewById(R.id.ygs1hp);
return v;
}
public void getArray(int[] dogruYanlis){
Toast.makeText(getActivity(),Integer.toString(dogruYanlis[0]), Toast.LENGTH_LONG).show();
}
}
I had a similar struggle, maybe this will help. In case if your variables in the activity are not changing after it is created, there is one simple way to reach out to the activity's variables from the fragment it creates:
get the context in the fragment
then you can get the value of the variable from the fragment
Context context;
public void onViewCreated(View v, Bundle savedInstanceState) {
context = getActivity();
int i = ((result)context).dogruYanlis[0];
}
Try to create a Fragment using the wizard that Android studio provides, which gives you a dummy Fragment, with all the Fragment methods you need to pass data and such:
package FRAGMENTS;
import android.app.Fragment;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class FragmentLifecycleDemo extends Fragment {
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String TEXT1 = "text1";
private static final String TEXT2 = "text2";
// the two strings are going to be used here
private TextView title;
private TextView subtitle;
private String text1;
private String text2;
private Context c;
private OnFragmentInteractionListener mListener;
public FragmentLifecycleDemo(Context c) {
// Required empty public constructor
this.c = c;
}
public static FragmentLifecycleDemo newInstance(String title, String subtitle, Context c) {
FragmentLifecycleDemo fragment = new FragmentLifecycleDemo(c);
Bundle args = new Bundle();
args.putString(TEXT1, title);
args.putString(TEXT2, subtitle);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(c, "Hi! onCreate has just been called.", Toast.LENGTH_SHORT).show();
if (getArguments() != null) {
text1 = getArguments().getString(TEXT1);
text2 = getArguments().getString(TEXT2);
}
}
private void init(View v) {
title = (TextView) v.findViewById(R.id.txtTry);
title.setText(text1);
subtitle = (TextView) v.findViewById(R.id.txtReal);
subtitle.setText(text2);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_lifecycle_demo, container, false);
init(v);
Toast.makeText(c, "Greetings from onCreateView!", Toast.LENGTH_SHORT).show();
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
Toast.makeText(c, "Is it me, or a button has just been pressed?", Toast.LENGTH_SHORT).show();
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Toast.makeText(c, "Howdy! I've just been attached to the activity.", Toast.LENGTH_SHORT).show();
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
Toast.makeText(c, "Oh no! I've been detached u.u", Toast.LENGTH_SHORT).show();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
As you can see, the method where you should get the Bundle is the onCreate one, that receives the data you want to be available on the Fragment, which was send from the constructor named newInstance.
Related
I am trying to implement fragments for a project in Android Studio. The point of the project is to select a color from a spinner in one fragment then pass it to the parent activity and then pass it from the parent activity to the second fragment to change the background color of the second fragment. The problem I am having is my listener in the palette activity is set to null despite the fact I invoke it in the onAttach function.
This is my code for the Fragment that causes the app to crash
package edu.temple.palettecolorapp;
import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Spinner;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link PaletteFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link PaletteFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class PaletteFragment extends Fragment {
private String colorArr[];
private String translationArr[];
Context parent;
private final String mParam1 = "colors";
private final String mParam2 = "translation";
public OnFragmentInteractionListener mListener;
public PaletteFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
*
* #return A new instance of fragment PaletteFragment.
*/
// TODO: Rename and change types and number of parameters
public static PaletteFragment newInstance(String colors[], String translation[]) {
PaletteFragment fragment = new PaletteFragment();
Bundle args = new Bundle();
args.putStringArray("colors", colors);
args.putStringArray("translation", translation);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
this.colorArr = getArguments().getStringArray(mParam1);
this.translationArr = getArguments().getStringArray(mParam2);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.parent = context;
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) parent;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
// this.parent = context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_palette, container, false);
Spinner spinner = v.findViewById(R.id.spinner);
PaletteAdapter pa = new PaletteAdapter(parent,colorArr,translationArr);
spinner.setAdapter(pa);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String c = colorArr[position];
mListener.onColorSelection(c);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return v;
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onColorSelection(String color);
}
}
This is in the main activity
package edu.temple.palettecolorapp;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
public class PaletteActivity extends AppCompatActivity implements PaletteFragment.OnFragmentInteractionListener {
PaletteFragment master;
ColorFragment subject;
FragmentTransaction ft;
private final String colors[] = {"blue", "green", "purple", "red", "gray", "cyan", "magenta", "yellow", "lime"};
private boolean isSelected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = getApplicationContext();
Resources res = context.getResources();
String title = res.getString(R.string.palette_title);
setTitle(title);
setContentView(R.layout.activity_palette);
String translation[] = res.getStringArray(R.array.colors);
PaletteFragment master = PaletteFragment.newInstance(colors,translation);
ColorFragment subject = ColorFragment.newInstance("magenta");
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment1,master);
ft.replace(R.id.fragment2,subject);
ft.addToBackStack(null);
ft.commit();
}
#Override
public void onColorSelection(String color) {
subject.updateBackgroundColor(color);
}
}
I am having trouble in this portion of the fragment in the 'onCreateView' method
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_palette, container, false);
Spinner spinner = v.findViewById(R.id.spinner);
PaletteAdapter pa = new PaletteAdapter(parent,colorArr,translationArr);
spinner.setAdapter(pa);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String c = colorArr[position];
mListener.onColorSelection(c);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return v;
}
The 'mListener.onColorSelection' call causes the error and this is what the output is
E/AndroidRuntime: FATAL EXCEPTION: main
Process: edu.temple.palettecolorapp, PID: 14867
java.lang.NullPointerException: Attempt to invoke virtual method 'void edu.temple.palettecolorapp.ColorFragment.updateBackgroundColor(java.lang.String)' on a null object reference
at edu.temple.palettecolorapp.PaletteActivity.onColorSelection(PaletteActivity.java:45)
at edu.temple.palettecolorapp.PaletteFragment$1.onItemSelected(PaletteFragment.java:87)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:944)
at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:933)
at android.widget.AdapterView.access$300(AdapterView.java:53)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:898)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Edit2: added ColorFragment 'updateBackgroundColor' method
import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* to handle interaction events.
* Use the {#link ColorFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ColorFragment extends Fragment {
private View v;
TextView t;
String color;
private final String KEY = "color";
public ColorFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters
* #return A new instance of fragment ColorFragment.
*/
// TODO: Rename and change types and number of parameters
public static ColorFragment newInstance() {
ColorFragment fragment = new ColorFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
this.color = getArguments().getString(KEY);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_color, container, false);
t = v.findViewById(R.id.textView);
t.setBackgroundColor(Color.BLACK);
return v;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
public void updateBackgroundColor(String c){ // causing problems
t.setBackgroundColor(Color.parseColor(c));
}
}
Apparently ColorFragment subject in PaletteActivity is null when calling #onColorSelection().
Please check the assignment of value for the variable and make sure it is not null.
#Override
public void onColorSelection(String color) {
subject.updateBackgroundColor(color);
}
EDIT:
change the line:
ColorFragment subject = ColorFragment.newInstance("magenta");
TO:
subject = ColorFragment.newInstance("magenta");
I am quite new to Android programming! I have managed to have TTS work but not for fragments. I am trying to swipe some images, and speak something each time I do that. I am not getting any error, however, the text is not spoken. Here's the code:
package com.example.nightrain.sliderTTS1;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.Locale;
public class Wild extends FragmentActivity{
ImageFragmentPagerAdapter imageFragmentPagerAdapter;
ViewPager viewPager;
public static final String[] IMAGE_NAME = {
"1", "2", "3"};
static final int NUM_ITEMS = IMAGE_NAME.length;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
imageFragmentPagerAdapter = new ImageFragmentPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(imageFragmentPagerAdapter);
}
public static class ImageFragmentPagerAdapter extends FragmentPagerAdapter {
public ImageFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
SwipeFragment fragment = new SwipeFragment();
return fragment.newInstance(position);
}
}
public static class SwipeFragment extends Fragment implements TextToSpeech.OnInitListener {
private static TextToSpeech tts;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View swipeView = inflater.inflate(R.layout.swipe_fragment, container, false);
ImageView imageView = (ImageView) swipeView.findViewById(R.id.imageView);
Bundle bundle = getArguments();
int position = bundle.getInt("position");
String imageFileName = IMAGE_NAME[position];
int imgResId = getResources().getIdentifier(imageFileName, "drawable", "com.example.nightrain.sliderTTS1");
imageView.setImageResource(imgResId);
tts = new TextToSpeech( getActivity(), SwipeFragment.this );
speak("help");
return swipeView;
}
static SwipeFragment newInstance(int position) {
SwipeFragment swipeFragment = new SwipeFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", position);
swipeFragment.setArguments(bundle);
return swipeFragment;
}
public void onInit(int status) {
Log.d("Speech", "OnInit - Status ["+status+"]");
if (status == TextToSpeech.SUCCESS) {
Log.d("Speech", "Success!");
tts.setLanguage(Locale.US);
}
}
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void speak( String text){
tts.speak( text, TextToSpeech.QUEUE_FLUSH, null, "1" );
}
}
}
Figured it out. I was trying to use speak() before onInit(). It is interesting that I could use speak outside onInit() with no issues in activity, however, for fragment I needed to mode the speak() method and all necessary code inside onInit(). Since it is system called, I could found no way to force it to work outside it.
please help me.
just want to know how can i refresh listview after i click imagebutton in my item.
here is my button onclick inside adapter..
buttonHeart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (arg0 != null) {
FragmentOne_DbAdapter database=new FragmentOne_DbAdapter(context);
database.open();
if(favorite.matches("0")) {
database.updateItemFavorite(_id,"1");
buttonHeart.setImageResource(R.drawable.heartred);
//Toast.makeText(arg0.getContext(),favorite,Toast.LENGTH_LONG).show();
}else if(favorite.matches("1")){
database.updateItemFavorite(_id, "0");
buttonHeart.setImageResource(R.drawable.heart);
//Toast.makeText(arg0.getContext(),favorite,Toast.LENGTH_LONG).show();
}
}
}
});
here is my complete adapter..
package com.magicstarme.virtualsongbook;
import android.content.Context;
import android.database.Cursor;
import android.media.Image;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.ArrayList;
/**
* Created by Joe on 6/29/2016.
*/
public class FragmentOne_Adapter extends CursorAdapter {
public FragmentOne_Adapter(Context context, Cursor c, int flags) {
super(context, c, flags);
// TODO Auto-generated constructor stub
}
#Override
public void bindView(View view, final Context context, Cursor cursor) {
// TODO Auto-generated method stub
TextView txtTitle = (TextView) view.findViewById(R.id.title);
TextView txtArtist = (TextView) view.findViewById(R.id.artist);
TextView txtVolume = (TextView) view.findViewById(R.id.volume);
TextView txtNumber = (TextView) view.findViewById(R.id.number);
final ImageButton buttonHeart = (ImageButton) view.findViewById(R.id.heart);
final int _id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
String title = cursor.getString(cursor.getColumnIndexOrThrow("title"));
String artist = cursor.getString(cursor.getColumnIndexOrThrow("artist"));
String volume = cursor.getString(cursor.getColumnIndexOrThrow("volume"));
final String favorite = cursor.getString(cursor.getColumnIndexOrThrow("favorite"));
String number = cursor.getString(cursor.getColumnIndexOrThrow("number"));
// Populate fields with extracted properties
txtTitle.setText(title);
txtArtist.setText(artist);
txtVolume.setText(volume);
txtNumber.setText(number);
if(favorite.matches("0")) {
buttonHeart.setImageResource(R.drawable.heart);
}else if(favorite.matches("1")){
buttonHeart.setImageResource(R.drawable.heartred);
}
buttonHeart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (arg0 != null) {
FragmentOne_DbAdapter database=new FragmentOne_DbAdapter(context);
database.open();
if(favorite.matches("0")) {
database.updateItemFavorite(_id,"1");
buttonHeart.setImageResource(R.drawable.heartred);
//Toast.makeText(arg0.getContext(),favorite,Toast.LENGTH_LONG).show();
}else if(favorite.matches("1")){
database.updateItemFavorite(_id, "0");
buttonHeart.setImageResource(R.drawable.heart);
//Toast.makeText(arg0.getContext(),favorite,Toast.LENGTH_LONG).show();
}
}
}
});
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
return LayoutInflater.from(context).inflate(R.layout.fragment_fragment_one_slview, parent, false);
}
}
and here is my fragment..
package com.magicstarme.virtualsongbook;
import android.content.Context;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link FragmentOne.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link FragmentOne#newInstance} factory method to
* create an instance of this fragment.
*/
public class FragmentOne extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public FragmentOne() {
// 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 FragmentOne.
*/
// TODO: Rename and change types and number of parameters
public static FragmentOne newInstance(String param1, String param2) {
FragmentOne fragment = new FragmentOne();
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);
}
}
private FragmentOne_DbAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
private FragmentOne_Adapter FragmentOneAdapter;
ListView listView;
EditText player1ESearch;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_fragment_one, container, false);
TabHost host = (TabHost) rootView.findViewById(R.id.tabHost);
host.setup();
//Tab 1
TabHost.TabSpec spec = host.newTabSpec("SONG LIST");
spec.setContent(R.id.tab1);
spec.setIndicator("SONG LIST");
host.addTab(spec);
player1ESearch = (EditText) rootView.findViewById(R.id.player1Search);
listView = (ListView) rootView.findViewById(R.id.slPlayer1ListView);
dbHelper = new FragmentOne_DbAdapter(getActivity());
dbHelper.open();
//Clean all data
//dbHelper.deleteAllPlayer1();
//Add some data
dbHelper.insertPlayer1Songlist();
//Generate ListView from SQLite Database
displayPlayer1ListView();
ImageButton dplayer1ESearch=(ImageButton) rootView.findViewById(R.id.delete);
dplayer1ESearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
player1ESearch.setText("");
}
});
//Tab 2
spec = host.newTabSpec("NEW SONGS");
spec.setContent(R.id.tab2);
spec.setIndicator("NEW SONGS");
host.addTab(spec);
//Tab 3
spec = host.newTabSpec("FAVORITES");
spec.setContent(R.id.tab3);
spec.setIndicator("FAVORITES");
host.addTab(spec);
return rootView;
}
private void displayPlayer1ListView() {
Cursor cursor = dbHelper.fetchAllPlayer1();
FragmentOneAdapter = new FragmentOne_Adapter(getActivity(), cursor, 0);
listView.setAdapter(FragmentOneAdapter);
player1ESearch.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
FragmentOneAdapter.getFilter().filter(s.toString());
}
});
FragmentOneAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchPlayer1ByTitle(constraint.toString());
}
});
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Simple call notifyDataSetChanged(); when you click in button for refresh your ListView
buttonHeart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
...
notifyDataSetChanged();
}
});
Basically your list view is connected with adapter. You need to notify this adapter to redraw the list view. Can you give more information where exactly your button click listener code is (in which class). If it is inside your adapter class (like I suppose) you can do something like this in your click listener code (some where inside the method public void onClick(View arg0) ) :
YourAdapterClassName.this.notifyDataSetChanged();
Update your adapter constructor to accept the Fragment as a parameter.
Something like :
public CustomAdapter(Context context, int id, HomeFragment fragment) {
this.fragment = fragment;
}
then you call methods using the fragment variable.
fragment.doSomething();
and in this method you can refresh the list using notifyDataSetChanged();
I have fragment view pager in activity, that creates a number of pages of entered number before. In each fragment, i have recycler view that needs to update each time user moves to the relevant page. on resume() of each fragment I have getter of data from main activity.
What I am experiencing is while I'm going to next page first time it's not updated, but if after some page movements I would back to it, it is updated, with same resume() code.
I tried some delays after updating the data, it didn't help.
So if before updating data I would check every page it would work as I planned, but if the page was not created before (due to pager adapter) but I still use the same code for updating, it does not work.
I would be glad for some help, stacked on it for 2 days already.
Main Activity:
package com.slavafleer.tipcalculator02;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.slavafleer.tipcalculator02.recycler.PageHeaderAdapter;
import java.util.ArrayList;
public class ManualModeActivity extends AppCompatActivity implements
PageHeaderAdapter.Callbacks, DinerFragment.Callbacks {
private int mDinersAmount;
private ViewPager mViewPagerDiners;
private PageHeaderAdapter mHeaderAdapter;
private DinersPagerAdapter mDinersPagerAdapter;
private ArrayList<Order> mOrders;
public ArrayList<Order> getOrders() {
return mOrders;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual_mode);
mOrders = new ArrayList<>();
// Get diners amount from previous activity
Intent intent = getIntent();
mDinersAmount = intent.getIntExtra(Constants.KEY_DINNERS_AMOUNT, 1);
// Initialise PageHeader Recycler
mHeaderAdapter = new PageHeaderAdapter(this, mDinersAmount, this);
final RecyclerView recyclerPageHeader = (RecyclerView) findViewById(R.id.recyclerViewPagerHeader);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerPageHeader.setLayoutManager(linearLayoutManager);
recyclerPageHeader.setAdapter(mHeaderAdapter);
// Initialise ViewPager
mViewPagerDiners = (ViewPager) findViewById(R.id.viewPagerDiners);
FragmentManager fragmentManager = getSupportFragmentManager();
mDinersPagerAdapter = new DinersPagerAdapter(fragmentManager, mDinersAmount);
mViewPagerDiners.setAdapter(mDinersPagerAdapter);
// ViewPager Listener - synchronise with headers recycler
mViewPagerDiners.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
// Gets position for selected page
#Override
public void onPageSelected(int position) {
mHeaderAdapter.selectItem(position);
linearLayoutManager.smoothScrollToPosition(recyclerPageHeader, null,position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
// HeaderPage Adapter Callbacks
// Scroll ViewPager by clicked Header
#Override
public void onItemClick(int position) {
mViewPagerDiners.setCurrentItem(position, true);
}
// DinerFragment.OrderDialog.Callbacks
// Send data to PagerAdapter that would sent to each fragment
#Override
public void onDialogAddClick(Order order) {
Log.d("test", "onDialogAddClick");
mOrders.add(order);
mDinersPagerAdapter.updateOrders();
}
}
PagerAdapter
package com.slavafleer.tipcalculator02;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
/**
* PagerAdapter for ManualModeActivity ViewPager
*/
public class DinersPagerAdapter extends FragmentPagerAdapter {
private int mDinersAmount;
private ArrayList<DinerFragment> mDinerFragments;
public DinersPagerAdapter(FragmentManager fm, int dinersAmount) {
super(fm);
mDinersAmount = dinersAmount;
mDinerFragments = new ArrayList<>();
}
#Override
public Fragment getItem(int position) {
// Insert diners amount to fragment
Bundle bundle = new Bundle();
bundle.putInt(Constants.KEY_DINNERS_AMOUNT, mDinersAmount);
bundle.putInt(Constants.KEY_CURRENT_PAGE, position);
DinerFragment dinerFragment = new DinerFragment();
dinerFragment.setArguments(bundle);
mDinerFragments.add(dinerFragment); // save fragments references
return dinerFragment;
}
// Diners amount + All
#Override
public int getCount() {
return mDinersAmount + 1;
}
// Update order list in each fragment of view pager
public void updateOrders() {
for(DinerFragment dinerFragment : mDinerFragments) {
dinerFragment.onResume();
}
}
}
Fragment
package com.slavafleer.tipcalculator02;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.slavafleer.tipcalculator02.recycler.OrdersAdapter;
import java.util.ArrayList;
/**
* Diner Fragment Class
*/
public class DinerFragment extends Fragment implements OrderDialog.Callbacks {
private ArrayList<Order> mOrders = new ArrayList<>();
private RecyclerView mRecyclerViewOrders;
private ImageView mImageViewAddOrderButton;
private int mDinersAmount;
private OrdersAdapter mOrdersAdapter;
private int mDinerId;
private Callbacks mCallbacks;
public DinerFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("test", "onCreateView");
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_diner, container, false);
mCallbacks = (Callbacks) inflater.getContext();
// Get Diners Amount
final Bundle bundle = getArguments();
if(bundle != null) {
mDinersAmount = bundle.getInt(Constants.KEY_DINNERS_AMOUNT);
mDinerId = bundle.getInt(Constants.KEY_CURRENT_PAGE);
Log.d("test", "onCreateView " + mDinerId);
}
mRecyclerViewOrders = (RecyclerView) view.findViewById(R.id.recyclerViewOrders);
mOrdersAdapter = new OrdersAdapter(getActivity(), mOrders);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerViewOrders.setLayoutManager(linearLayoutManager);
mRecyclerViewOrders.setAdapter(mOrdersAdapter);
// Due to the bug, we could use just listener and not OnClick in Fragment
mImageViewAddOrderButton = (ImageView) view.findViewById(R.id.imageViewAddButton);
mImageViewAddOrderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Integer> currentPage = new ArrayList<>();
currentPage.add(mDinerId);
OrderDialog orderDialog = new OrderDialog(getActivity(),
mDinersAmount, currentPage, DinerFragment.this);
orderDialog.show();
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
Log.d("test", "onResume " + mDinerId);
ManualModeActivity activity = (ManualModeActivity) getActivity();
mOrders = activity.getOrders();
for(Order order : mOrders) {
Log.d("test", order.getPrice() + "");
}
int size = mOrders.size();
mOrdersAdapter.notifyDataSetChanged();
mRecyclerViewOrders.smoothScrollToPosition(size);
}
// Blank OrderDialog.Callbacks
// used due to Implements for creation OrderDialog
#Override
public void onDialogAddClick(Order order) {
mCallbacks.onDialogAddClick(order);
}
public interface Callbacks {
void onDialogAddClick(Order order);
}
}
Instead of using onResume use the onPageSelected method and used the passed fragment for context to call the updating method in the fragment.
Finally what I did is replacing mOrdersAdapter.notifyDataSetChanged() on recreating the adapter. I understand that is not a very smart solution but visually it does work as I needed.
I would not mark it as answer cause I still want to know why it acts like I wrote before.
Thanks again.
// mOrdersAdapter.notifyDataSetChanged();
mOrdersAdapter = new OrdersAdapter(getActivity(), mOrders);
mRecyclerViewOrders.setAdapter(mOrdersAdapter);
ViewPager adapter creates 2 fragments at the same time. for instance when you're on page 0, it also creates page 1(lifecycle for page 1: OnCreate->OnCreateView->OnResume->OnPause->OnResume).When you swipe to page 1 only method that is being called is SetMenuVisibility. So in order to update data for page 1 is to call setMenuVisibilty inside of Fragment:
#Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if(menuVisible && isResumed()){
settingAdapter();
}
}
So here inside of settingAdapter i reloaded data.
so far,it's the best trick i made toward fragments with recyclerviews inside viewpager. But still there are few milliseconds delay for populating fragment with new data)))
I hope this will help you
I have two fragments, lets call them Fragment A and Fragment B, which are a part of a NavigationDrawer (this is the activity they a bound to). In Fragment A I have a button. When this button is pressed, I would like another item added to the ListView in Fragment B.
What is the best way to do this? Use Intents, SavedPreferences, making something public(?) or something else?
EDIT 5: 20/7/13 This is with srains latest code
This is the NavigationDrawer that I use to start the fragments:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Navigation_Drawer extends FragmentActivity {
public DrawerLayout mDrawerLayout; // Creates a DrawerLayout called_.
public ListView mDrawerList;
public ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mNoterActivities; // This creates a string array called _.
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
// Just setting up the navigation drawer
} // End of onCreate
// Removed the menu
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
if (position == 0) {
Fragment qnfragment = new QuickNoteFragment();
((FragmentBase) qnfragment).setContext(this);
Bundle args = new Bundle(); // Creates a bundle called args
args.putInt(QuickNoteFragment.ARG_nOTERACTIVITY_NUMBER, position);
qnfragment.setArguments(args);
fragmentManager.beginTransaction()
.replace(R.id.content_frame, qnfragment).commit();
} else if (position == 3) {
Fragment pendViewPager = new PendViewPager(); // This is a ViewPager that includes HistoryFragment
((FragmentBase) pendViewPager).setContext(this);
Bundle args = new Bundle();
pendViewPager.setArguments(args);
fragmentManager.beginTransaction()
.replace(R.id.content_frame, pendViewPager).commit();
}
// Update title etc
}
#Override
protected void onPostCreate(Bundle savedInstanceState) { // Used for the NavDrawer toggle
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) { // Used for the NavDrawer toggle
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
This is QuickNoteFragment:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class QuickNoteFragment extends FragmentBase implements OnClickListener {
public static final String ARG_nOTERACTIVITY_NUMBER = "noter_activity";
Button b_create;
// removed other defining stuff
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.quicknote, container, false);
int i = getArguments().getInt(ARG_nOTERACTIVITY_NUMBER);
String noter_activity = getResources().getStringArray(
R.array.noter_array)[i];
FragmentManager fm = getFragmentManager();
setRetainInstance(true);
b_create = (Button) rootView.findViewById(R.id.qn_b_create);
// Removed other stuff
getActivity().setTitle(noter_activity);
return rootView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.qn_b_create:
String data = "String data";
DataModel.getInstance().addItem(data);
break;
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
}
}
public interface OnItemAddedHandler { // Srains code
public void onItemAdded(Object data);
}
}
This is HistoryFragment (Remember it is part of a ViewPager):
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.RiThBo.noter.QuickNoteFragment.OnItemAddedHandler;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class HistoryFragment extends FragmentBase implements OnItemAddedHandler {
ListView lv;
List<Map<String, String>> planetsList = new ArrayList<Map<String, String>>();
SimpleAdapter simpleAdpt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.history, container, false);
initList();
ListView lv = (ListView) view.findViewById(R.id.listView);
simpleAdpt = new SimpleAdapter(getActivity(), planetsList,
android.R.layout.simple_list_item_1, new String[] { "planet" },
new int[] { android.R.id.text1 });
lv.setAdapter(simpleAdpt);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view,
int position, long id) {
// We know the View is a TextView so we can cast it
TextView clickedView = (TextView) view;
Toast.makeText(
getActivity(),
"Item with id [" + id + "] - Position [" + position
+ "] - Planet [" + clickedView.getText() + "]",
Toast.LENGTH_SHORT).show();
}
});
registerForContextMenu(lv);
return view;
}
private void initList() {
// We populate the planets
planetsList.add(createPlanet("planet", "Mercury"));
planetsList.add(createPlanet("planet", "Venus"));
planetsList.add(createPlanet("planet", "Mars"));
planetsList.add(createPlanet("planet", "Jupiter"));
planetsList.add(createPlanet("planet", "Saturn"));
planetsList.add(createPlanet("planet", "Uranus"));
planetsList.add(createPlanet("planet", "Neptune"));
}
private HashMap<String, String> createPlanet(String key, String name) {
HashMap<String, String> planet = new HashMap<String, String>();
planet.put(key, name);
return planet;
}
// We want to create a context Menu when the user long click on an item
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) menuInfo;
// We know that each row in the adapter is a Map
HashMap map = (HashMap) simpleAdpt.getItem(aInfo.position);
menu.setHeaderTitle("Options for " + map.get("planet"));
menu.add(1, 1, 1, "Details");
menu.add(1, 2, 2, "Delete");
}
#Override
public void onItemAdded(Object data) {
// to add item
String string = String.valueOf(data);
Toast.makeText(getContext(), "Data: " + string, Toast.LENGTH_SHORT).show();
planetsList.add(createPlanet("planet", string));
}
#Override
public void onStart() {
super.onStart();
DataModel.getInstance().setOnItemAddedHandler(this);
}
}
This is FragmentBase:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
public class FragmentBase extends Fragment {
private FragmentActivity mActivity; // I changed it to FragmentActivity because Activity was not working, and my `NavDrawer` is a FragmentActivity.
public void setContext(FragmentActivity activity) {
mActivity = mActivity;
}
public FragmentActivity getContext() {
return mActivity;
}
}
This is DataModel:
import android.util.Log;
import com.xxx.xxx.QuickNoteFragment.OnItemAddedHandler;
public class DataModel {
private static DataModel instance;
private static OnItemAddedHandler mOnItemAddHandler;
public static DataModel getInstance() {
if (null == instance) {
instance = new DataModel();
}
return instance;
}
public void setOnItemAddedHandler(OnItemAddedHandler handler) {
mOnItemAddHandler = handler;
}
public void addItem(Object data) {
if (null != mOnItemAddHandler)
mOnItemAddHandler.onItemAdded(data);
else {
Log.i("is context null?", "yes!");
}
}
}
Thank you
I suggest you to use interface and MVC, that will make your code much more maintainable.
First you need an interface:
public interface OnItemAddedHandler {
public void onItemAdded(Object data);
}
Then, you will need a data model:
public class DataModel {
private static DataModel instance;
private static OnItemAddedHandler mOnItemAddHandler;
public static DataModel getInstance() {
if (null == instance) {
instance = new DataModel();
}
return instance;
}
public void setOnItemAddedHandler(OnItemAddedHandler handler) {
mOnItemAddHandler = handler;
}
public void addItem(Object data) {
if (null != mOnItemAddHandler)
mOnItemAddHandler.onItemAdded(data);
}
}
When you click the button, you can add data into the datamodel:
Object data = null;
DataModel.getInstance().addItem(data);
Then, the FragmentB implements the interface OnItemAddedHandler to add item
public class FragmentB implements OnItemAddedHandler {
#Override
public void onItemAdded(Object data) {
// to add item
}
}
also, When the FragmentB start, you should register itself to DataModel:
public class FragmentB implements OnItemAddedHandler {
#Override
public void onItemAdded(Object data) {
// to add item
}
#Override
protected void onStart() {
super.onStart();
DataModel.getInstance().setOnItemAddedHandler(this);
}
}
You also can add DataModel.getInstance().setOnItemAddedHandler(this); to the onCreate method of FragmentB
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DataModel.getInstance().setOnItemAddedHandler(this);
// do other things
}
update
you can send string simply:
String data = "some string";
DataModel.getInstance().addItem(data);
then on FragementB
public class FragmentB implements OnItemAddedHandler {
#Override
public void onItemAdded(Object data) {
// get what you send into method DataModel.getInstance().addItem(data);
String string = String.valueOf(data);
}
}
update
OK. You have add DataModel.getInstance().setOnItemAddedHandler(this) in onCreateView method, so there is no need to add it in onStart() method. You can remove the whole onStart method.
onStart will be called on the fragment start, we do not need to call it in onCreateView. And on onItemAdded will be call when call the method DataModel.getInstance().addItem(data), we do not need to call it in onCreateView neither.
so, you can remove the code below from onCreateView method:
DataModel.getInstance().setOnItemAddedHandler(this);
// remove the methods below
// onItemAdded(getView());
// onStart();
You have another fragment where there is a button, you can add the codes below in the clickhandler function:
String data = "some string";
DataModel.getInstance().addItem(data);
update3
I think the HistoryFragment has been detached after you when to QuickNoteFragment
You can add code to HistoryFragment to check:
#Override
public void onDetach() {
super.onDetach();
Log.i("test", String.format("onDetach! %s", getActivity() == null));
}
update4
I think HistoryFragment and QuickNoteFragment should has an parent class, named FragmentBase:
public class FragmentBase extends Fragment {
private Activity mActivity;
public void setContext(Activity activity) {
mActivity = mActivity;
}
public Activity getContext() {
return mActivity;
}
}
HistoryFragment and QuickNoteFragment extends FragmentBase. Then when you switch between them, you can call setContext to set a Activity, like:
private void selectItem(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
if (position == 0) {
Fragment qnfragment = new QuickNoteFragment();
qnfragment.setContext(this);
// ...
} else if (position == 1) {
Fragment pagerFragment = new RemViewPager();
pagerFragment.setContext(this);
// ...
}
}
now, we can get a non-null activity in HistoryFragment by calling getContext, so we can change onItemAdded method to:
#Override
public void onItemAdded(Object data) {
// to add item
String string = String.valueOf(data);
Toast.makeText(getContext(), "Data: " + string, Toast.LENGTH_SHORT).show();
planetsList.add(createPlanet("planet", string));
}
I hope this would work.
Some good design principals:
An activity can know everything pubic about any Fragment it contains.
A Fragment should not know anything about the specific Activities that contain it.
A Fragment should NEVER know about other fragments that may or may not be contained in the Parent activity.
A suggested approach (informal design pattern) based on these principles.
Each fragment should declare an interface to be implemented by its parent activity:
public class MyFragment extends Fragment
{
public interface Parent
{
void onMyFragmentSomeAction();
}
private Parent mParent;
public onAttach(Activity activity)
{
mParent = (Parent) activity;
}
// This would actually be in a listener. Simplifying to save typing.
void onSomeButtonClick(View button)
{
mParent.onMyFragmentSomeAction();
}
}
And the activity should implement the appropriate interfaces for all of its contained fragments.
public class MyActivity extends Activity
implements MyFragment.Parent,
YourFragment.Parent,
HisFragment.Parent
{
[usual Activity code]
void onMyFragmentSomeAction()
{
if yourFragment is showing
{
yourFragment.reactToSomeAction();
}
if hisFragment is showing
{
hisFragment.observeThatSomeActionHappened();
}
[etc]
}
The broadcast approach is good, too, but it's pretty heavyweight and it requires the target Fragment to know what broadcasts will be sent by the source Fragment.
Use Broadcast. Send a boradcast from A, and B will receive and handle it.
Add a public method to B, for example, public void addListItem(), which will add data to listview in B. Fragment A try to find the instance of Fragment B using FragmentMananger.findFragmentByTag() and invoke this method.