I have implemented a FragmentPagerAdapter of 4-lashes, and in each of them I load a fragment with a different view.
In one of them, pressing an image executed a AsyncTask to obtain a series of data from a server and loads a new class through an intent on the postExecute() method as follows:
//AsyncTask
private static class LoadJSON extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
mProgressItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
mProgressItem.setVisible(true);
mProgressItem.setActionView(R.layout.actionbar_indeterminate_progress);
mProgressItem.expandActionView();
}
#Override
protected String doInBackground(String... params) {
String url = params[0];
String data = MetodosJSON.getHttpResponse(url);
MetodosJSON.parseaJSON2(data, ini.ac);
return params[1];
}
protected void onPostExecute(String titulo) {
// start new activity
Intent i = new Intent(ini.c, PantallaInfo.class);
i.putExtra("title", titulo);
i.putExtra("URLser", urlSer);
ini.startActivity(i);
mProgressItem.setVisible(false);
}
}
I had this functionality in one activity and worked perfectly. Now to make the call from the fragment I have to make calls using a variable static of this class ('ini') and I get error in the line of code 'ini.startActivity (i),':
FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.Activity.startActivityForResult(Activity.java:3351)
at android.support.v4.app.FragmentActivity.startActivityForresult(FragmentActivity.java:674)
at android.app.Activity.startActivity(Activity.java:3522)
at com.packet.ClassName.AsyncTask.onPostExecute(ClassName.java:432)
I hope someone can help me, please.
Thank you very much.
...continue...my whole class
package com.test;
import ...
public class IniSelCategoria extends SherlockFragmentActivity {
static String urlIni;
static String urlSer;
GridView mGrid;
static Dialog dial;
DisplayMetrics metrics = new DisplayMetrics();
static int width, height;
private static MenuItem mProgressItem;
MyAdapter mAdapter;
ViewPager mViewPager;
static Context c, ac;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.iniselcategoria);
c = getBaseContext();
ac = getApplicationContext();
// Configuration
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
width = display.getWidth();
height = display.getHeight();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mAdapter = new MyAdapter(getSupportFragmentManager());
for(int i=0; i<4; i++) {
Fragment fragment = null;
switch(i) {
case 0:
fragment = Fragment1.newInstance();
break;
case 1:
fragment = Fragment2.newInstance();
break;
case 2:
fragment = Fragment3.newInstance();
break;
case 3:
fragment = Fragment4.newInstance();
break;
}
mAdapter.addFragment(fragment);
}
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAdapter);
// Intent information
Bundle recibido = getIntent().getExtras();
if(recibido != null) {
urlIni = recibido.getString("URLini");
}
}
final static IniSelCategoria ini = new IniSelCategoria();
//Options Menu
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.iniselcategoria, menu);
mProgressItem = menu.findItem(R.id.MenuProgress);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.MenuBuscador) {
Intent ic3 = new Intent(getBaseContext(), Menu_Buscador.class);
startActivity(ic3);
return true;
}else {
return super.onOptionsItemSelected(item);
}
}
//Creation of images
public static class ImageAdapter extends BaseAdapter {
private Context mContext;
final AppJSON json = (AppJSON) (IniSelCategoria.ac);
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return json.json1.GetNumSer();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView img;
if (convertView == null) {
img = new ImageView(mContext);
img.setAdjustViewBounds(true);
img.setScaleType(ImageView.ScaleType.FIT_CENTER);
} else {
img = (ImageView) convertView;
}
final String titulo = json.json1.GetTitle(position);
final int idSer = json.json1.GetIdSer(position);
// Configuration images
if("Recursos Naturales".equals(titulo)) {
img.setImageResource(R.drawable.ic_recursosnaturales);
}else if("Competitividad".equals(titulo)) {
img.setImageResource(R.drawable.ic_competitividad);
}else if("Calidad de Vida".equals(titulo)) {
img.setImageResource(R.drawable.ic_calidaddevida);
}else if("Participación".equals(titulo)) {
img.setImageResource(R.drawable.ic_participacion);
}else if("Transporte".equals(titulo)) {
img.setImageResource(R.drawable.ic_transporte);
}else{
Toast.makeText(IniSelCategoria.c, "Error", Toast.LENGTH_SHORT).show();
}
img.setOnClickListener(new ImageView.OnClickListener() {
public void onClick(View v) {
urlSer = urlIni + idSer;
// get data from the server
new CargarJSON(mContext).execute(urlSer, titulo);
}
});
return img;
}
}
//AsyncTask
private static class CargarJSON extends AsyncTask<String, Void, String> {
Context mContext;
public CargarJSON(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
mProgressItem.setVisible(true);
mProgressItem.setActionView(R.layout.actionbar_indeterminate_progress);
mProgressItem.expandActionView();
}
#Override
protected String doInBackground(String... params) {
String url = params[0];
String data = MetodosJSON.getHttpResponse(url);
MetodosJSON.parseaJSON2(data, IniSelCategoria.ac);
return params[1];
}
#Override
protected void onPostExecute(String titulo) {
super.onPostExecute(titulo);
// start new activity
Intent i = new Intent(mContext, PantallaInfo.class);
i.putExtra("title", titulo);
i.putExtra("URLser", urlSer);
ini.startActivity(i);
mProgressItem.setVisible(false);
}
}
public static class MyAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragmentList;
public MyAdapter(FragmentManager fm) {
super(fm);
mFragmentList = new ArrayList<Fragment>();
}
public void addFragment(Fragment fragment) {
mFragmentList.add(fragment);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
return ((CustomFragment) mFragmentList.get(position)).getPageTitle();
}
}
public static abstract class CustomFragment extends Fragment {
public abstract String getPageTitle();
}
public static class Fragment1 extends CustomFragment {
public static Fragment newInstance() {
Fragment f = new Fragment1();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.iniselareas, container, false);
// Some codes for layout such as findViewById
final GridView gridServ = (GridView)view.findViewById(R.id.myGrid);
if(height > width) {
gridServ.setNumColumns(1);
}else {
gridServ.setNumColumns(2);
}
gridServ.setAdapter(new ImageAdapter(getActivity()));
return view;
}
#Override
public String getPageTitle() {
// return TITLE_FOR_FRAGMENT
return "ÁREAS TEMÁTICAS";
}
}
public static class Fragment2 extends CustomFragment {
...
}
public static class Fragment3 extends CustomFragment {
...
}
public static class Fragment4 extends CustomFragment {
...
}
}
I don't know what c is
gridServ.setAdapter(new ImageAdapter(c)); // is c activity context
or
gridServ.setAdapter(new ImageAdapter(getActivity()));
getActivity()
public final Activity getActivity ()
Added in API level 11
Return the Activity this fragment is currently associated with.
Then you have
public ImageAdapter(Context c) {
mContext = c;
// you get the activity context here
// you can use the same
}
Pass the activity context to the constructor of asynctask.
new LoadJSON(mContext).execute(url,title);
// using mContext initialized in ImageAdapter
Then in the asynctask constructor
Context mContext;
public LoadJSON(Context context)
{
mContext = context; // get activity context
}
Also
#Override
protected void onPreExecute() {
super.onPreExecute();
Then
#Override
protected void onPostExecute(String titulo) {
super.onPostExecute(titulo);
Also use mContext to startActivity
Intent i = new Intent(mContext, PantallaInfo.class);
mContext.startActivity(i);
startActivity is a method of Activity class. Requires Activity context.
Related
I have 3 fragment in viewpager (LeftFragment, MidFragment and Right Fragment) LeftFragment contain a listview, when clicking on listview item,it sends an index (integer) from leftfragment to mid fragment, an image will be loaded on MidFragment. Errors here can be onCreateView happens before i set the arguments. So is there a way to solve my case. Sorry my skill english is bad. Thank you !
LeftFragment
public class LeftFragment extends Fragment{
private ListView listView;
private List<ParseObject> ob;
private ProgressDialog mProgressDialog;
private ListViewAdapter adapter;
private List<School> schoollist = null;
private View v;
MainActivity mainActivity = new MainActivity();
MidFragment midFragment = new MidFragment();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.left_fragment, container, false);
initComponent();
new RemoteDataTask().execute();
return v;
}
private void initComponent() {
listView = (ListView)v.findViewById(R.id.lv_left);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mainActivity.viewPager.setCurrentItem(1);
School school = schoollist.get(position);
midFragment.reloadData(Integer.parseInt(school.getIndex()));
}
});
}
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setTitle("Please wait a moment...");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
schoollist = new ArrayList<School>();
try{
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("School");
query.orderByAscending("index");
ob = query.find();
for (ParseObject name : ob){
School map = new School();
map.setIndex(String.valueOf(name.get("index")));
map.setCount(String.valueOf(name.get("count")));
map.setName(String.valueOf(name.get("name")));
schoollist.add(map);
}
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
adapter = new ListViewAdapter(getActivity(), schoollist);
listView.setAdapter(adapter);
mProgressDialog.dismiss();
super.onPreExecute();
}
}
}
MidFragment
public class MidFragment extends Fragment {
// private ProgressDialog mProgressDialog;
private ImageView mImageView;
private VideoView mVideoView;
private DisplayImageOptions options;
private ImageLoader imageLoader = ImageLoader.getInstance();
private Context mContext;
private ImageLoadingListener animateFirstListener;
private ArrayList<ParseObject> objectList = new ArrayList<>();
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// imageLoader.init(ImageLoaderConfiguration.createDefault(mContext));
// mImageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.build();
animateFirstListener = new AnimateFirstDisplayListener();
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.mid_fragment, container, false);
initComponent(view);
mContext = container.getContext();
return view;
}
private void initComponent(View view) {
mImageView = (ImageView) view.findViewById(R.id.image);
mVideoView = (VideoView) view.findViewById(R.id.video);
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mVideoView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// mProgressDialog = new ProgressDialog(getActivity());
// mProgressDialog.setTitle("Please wait a moment...");
// mProgressDialog.setMessage("Loading...");
// mProgressDialog.setIndeterminate(false);
}
public void reloadData(int index){
// mProgressDialog.show();
objectList.clear();
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Data");
query.whereEqualTo("school",(Number)index);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
objectList = (ArrayList<ParseObject>) list;
// mProgressDialog.dismiss();
if (!list.isEmpty())
openFirst();
}
});
}
private void openFirst(){
ParseObject parseObject = objectList.get(0);
ParseFile parseFile = parseObject.getParseFile("file");
if (parseObject.getNumber("type") == (Number)1){
}else{
// mVideoView.setVisibility(View.GONE);
// mImageView.setVisibility(View.VISIBLE);
imageLoader.displayImage(parseFile.getUrl(), mImageView, options, animateFirstListener);
}
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
MainActivity
public class MainActivity extends FragmentActivity{
public static MyPagerFragment myPagerFragment;
public static ViewPager viewPager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.viewPager);
myPagerFragment = new MyPagerFragment(getSupportFragmentManager());
viewPager.setAdapter(myPagerFragment);
viewPager.setCurrentItem(1);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public static class MyPagerFragment extends FragmentStatePagerAdapter {
public MyPagerFragment(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0: return new LeftFragment();
case 1: return new MidFragment();
case 2: return new RightFragment();
default: return null;
}
}
#Override
public int getCount() {
return 3;
}
}
}
LeftFragment
public class LeftFragment extends Fragment{
OnImageSelectedListener mCallback;
public interface OnImageSelectedListener {
public void onImageSelected(int position);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnImageSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnImageSelectedListener");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
mCallback.onImageSelected(position);
}
}
Main Activity
public class MainActivity extends FragmentActivity implements HeadlinesFragment.OnImageSelectedListener{
public void onArticleSelected(int position) {
midFragment.setImage(position);
}
}
MidFragment
public class MidFragment extends Fragment {
setImage(int position){
//set Image here this method will be called the user select a list in left fragment
}
}
Why does my pager adapter doesn't want to start from my first item. When I start ContainerIspiti activity, and show first fragment, the view pager dones't show the right element. Insted of first, view pager shows the second element, and I can't to swipe to first element of my array list. Does anybody have solution.
Here is my code for ConainterIspiti
public class ContainerIspiti extends FragmentActivity{
private Button next, previous, odgovori, informacije;
private TextView textPitanja, brojPitanja;
private ViewPager pager;
private PagerAdapter mPagerAdapter;
public static ArrayList<Pitanja> getAllPitanja;
public static ArrayList<Pitanje_has_Slika> getAllImages;
private Intent intent;
private DBTools db = new DBTools(this);
private ProgressDialog pDialog;
private int broj;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_container_pitanja);
Bundle bundle = new Bundle();
intent = getIntent();
Dohvati d = new Dohvati();
d.execute();
textPitanja = (TextView) findViewById(R.id.kategorijaTextViewPitanjeActivity);
brojPitanja = (TextView) findViewById(R.id.brojPitanjaTextViewPitanjeActivity);
pager = (ViewPager) findViewById(R.id.pagerPitanja);
pager.setCurrentItem(0, true);
bundle.putString("NAZIV_KATEGORIJE", intent.getStringExtra("NAZIV_KATEGORIJE"));
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Log.i("Position je sljedeci ", String.valueOf(position));
return PitanjaFragment.create(position);
}
#Override
public int getCount() {
Log.i("Velicina polja je ", String.valueOf(getAllPitanja.size()));
Log.i("Prvi eleemnt liste je", getAllPitanja.get(0).getTextPitanja());
return getAllPitanja.size();
}
}
private class Dohvati extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ContainerIspiti.this);
pDialog.setCancelable(false);
pDialog.setIndeterminate(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
getAllPitanja = db
.getAllPitanja(intent.getStringExtra("id_kategorije"));
Log.i("Ovoliki je get all pitanja", String.valueOf(getAllPitanja.size()));
getAllImages = db.getAllPitanjaImages();
Log.i("ovoliko je slika", String.valueOf(getAllImages.size()));
return null;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
pager.setAdapter(mPagerAdapter);
pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position) {
invalidateOptionsMenu();
brojPitanja.setText(String.valueOf(position) + "/" + String.valueOf(getAllPitanja.size()));
broj = position;
}
});
textPitanja.setText(intent.getStringExtra("NAZIV_KATEGORIJE"));
brojPitanja.setText(String.valueOf(broj) + "/" + getAllPitanja.size());
}
}
}
and here is my fragment activity
public class PitanjaFragment extends Fragment implements API{
public static final String ARG_PAGE = "page";
private int broj;
private ImageView image;
private TextView textPitanja;
private String uri;
private View view;
private ListView listView;
private Typeface custom_font;
private boolean odgovoreno, tocno;
private ArrayList<Odgovor> odgovorList;
private PitanjaAdapter adapter;
private DBTools db;
private List<Integer> kliknuti;
private HashMap<Integer, List<Integer>> odgBrojPitanja;
public static PitanjaFragment create(int pageNumber) {
PitanjaFragment fragment = new PitanjaFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
return fragment;
}
public PitanjaFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
broj = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_pitanja, container, false);
image = (ImageView) view.findViewById(R.id.imageSlikaImageView);
image.setOnClickListener(this);
textPitanja = (TextView) view.findViewById(R.id.textPitanjaTextViewPitanjaActivity);
db = new DBTools(getActivity());
listView = (ListView) view.findViewById(R.id.listView);
updateDisplay((broj+1));
return view;
}
public void updateDisplay(int z) {
odgovoreno = false;
tocno = true;
textPitanja.setText(stripHtml(String.valueOf(ContainerIspiti.getAllPitanja.get(z).getTextPitanja())));
image.setImageBitmap(null);
//info = ContainerIspiti.getAllPitanja.get(z).getInfo();
Log.d("Postoji", ContainerIspiti.getAllImages.get(z).getNazivSlike() + ", ");
for (int j = 0; j < ContainerIspiti.getAllImages.size(); j++) {
if (ContainerIspiti.getAllImages.get(j).getIdPitanja() == ContainerIspiti.getAllPitanja.get(z)
.getIdPitanja()
&& ContainerIspiti.getAllImages.get(j).getNazivSlike() != null) {
Log.i("Id pitanja slike + idpitanja pitanja + idSlike",
ContainerIspiti.getAllImages.get(j).getIdPitanja()
+ ", "
+ String.valueOf(ContainerIspiti.getAllPitanja.get(z)
.getIdPitanja()
+ ", "
+ ContainerIspiti.getAllImages.get(j).getIdSlika()));
image.setVisibility(View.VISIBLE);
//povecalo.setImageResource(R.drawable.gumb_pretrazi);
//povecalo.setEnabled(true);
uri = PregledZnakova.PHOTOS_BASE_URL
+ ContainerIspiti.getAllImages.get(j).getNazivSlike();
int rounded_value = 40;
DisplayImageOptions options = new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.placeholder).showStubImage(R.drawable.placeholder).cacheInMemory().cacheOnDisc().displayer(new RoundedBitmapDisplayer(rounded_value)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity().getApplicationContext()).defaultDisplayImageOptions(options).build();
ImageLoader.getInstance().init(config);
ImageLoader.getInstance().displayImage(uri, image,options);
break;
// }
} else {
image.setVisibility(View.GONE);
//povecalo.setImageResource(R.drawable.gumb_pretrazi_neaktivno);
//povecalo.setEnabled(false);
}
}
odgovorList = db.getAllOdgovore(Integer.toString(ContainerIspiti.getAllPitanja.get(z)
.getIdPitanja()));
adapter = new PitanjaAdapter(getActivity(),
R.layout.pitanja_entry, odgovorList);
listView.setAdapter(adapter);
for (int i=0;i<ContainerIspiti.getAllPitanja.size();i++){
if (ContainerIspiti.getAllPitanja.get(i).isTocno()){
Log.i("Ovo pitanje je tocno", ContainerIspiti.getAllPitanja.get(i).getTextPitanja());
}
}
}
#Override
public int getItemBroj() {
return broj;
}
#Override
public int getPosition() {
return broj;
}
#Override
public void setPosition(int position) {
this.broj = position;
}
#Override
public Fragment getFragment() {
return this;
}
}
Thanks for your time and your help.
In the onCreateView() method of your PitanjaFragment class, replace:
updateDisplay((broj+1));
with
updateDisplay(broj);
Try this. It should work.
[My condition]
Now in MainActivity, I create some Fragments in which there are some TextViews. And there's an asynchronous thread AsyncTask in MainActivity to obtain information from web. After AsyncTask finished obtaining it will update the text in TextViews mentioned above through callback method (The Fragment implements a OnInfoGotInterface and instanciate a method onInfoGot() in the interface. onInfoGot() will call the method setTextView() defined in the Fragment to update information).
[My problem]
When execute the program, I found that the time point when AsyncTask finishes get information from web precedes the time point when Fragment call onCreateView(). In another word, when AsyncTask call (OnInfoGotInterface)fragment.onInfoGot() to set the TextViews, the TextViews have not been instanciated yet (TextViews are instanciated in on CreateView() by rootView.findViewById() method). As a result, a NullPointerException showed up.
[I need a resolution]
Now I want to do like this: When AsyncTask finishes getting info from web and is going to call onInfoGot(), we stop it, and make it wait until the Fragment finish onCreateView(). After that we waken the AsyncTask and allow it update the fragment.
PS. Some suggest that I should call new AsyncTask.excute() after onCreateView() in the definition of Fragment. But here AsyncTask and Fragment are both created in MainActivity. They are two differnt task threads in MainActivity, one is used for showing data and the other is used for getting data from Web.
Could anyone give some advice? I would really appreciate it!
Here is the code:
MainActivity.java:
public class MainActivity extends Activity{
private List<City> cityList;
private ViewPager mPager; /*ViewPager for show the page of city info*/
private ScreenSlidePagerAdapter mPagerAdapter; /* Adapter for the ViewPager,
* ScreenSlidePagerAdapter is a subclass of FragmentStatePagerAdapter*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_city);
cityList = new ArrayList<City>();
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
init();
}
private void init(){
loadCities(); //Load cities from database into cityList
initFragments();
getCityInfo();
}
private void initFragments(){
mPagerAdapter.removeAllFragments();
for(City city: cityList){
PageFragment fragment = new PageFragment(city.getName());
mPagerAdapter.addFragment(fragment);
mPagerAdapter.notifyDataSetChanged();
}
}
private void getCityInfo(){
for(City city: cityList){
String cityName = city.getName();
obtainCityInfo(cityName);
}
}
private obtainCityInfo(String cityName){
String request = "http://example.abc.com/"
+ cityName + "&output=json";
new AccessWebServiceTask().execute(request, cityName);
}
private class AccessWebServiceTask extends AsyncTask<String, Void, CityInfo>{
#Override
protected CityInfo doInBackground(String... urls) {
String result = getWebContent(urls[0]); /*Access web through HTTP*/
String cityName = urls[1];
/*Transform the String result to a CityInfo object containing information of a city*/
CityInfo cityInfo = encodeJason(result, cityName);
return cityInfo;
}
protected void onPostExecute(CityInfo cityInfo){
OnCityGot(cityInfo);
}
}
public void onCityGot(CityInfo cityInfo){
if(cityInfo != null){
String cityName = cityInfo.getCityName();
/*Set the info field of a city object*/
cityList.getByName(cityName).setCityInfo(cityInfo);
mPagerAdapter.updateFragment(cityInfo);
}
}
}
ScreenSlidePagerAdapter.java
public class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter{
private List<PageFragment> fragmentsList;
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
fragmentsList = new ArrayList<PageFragment>();
}
public ScreenSlidePagerAdapter(FragmentManager fm, List<PageFragment> list){
super(fm);
fragmentsList = list;
}
#Override
public PageFragment getItem(int position) {
return fragmentsList.get(position);
}
#Override
public int getCount() {
return fragmentsList.size();
}
public void setFragmentsList(List<PageFragment> fragmentsList){
this.fragmentsList = fragmentsList;
notifyDataSetChanged();
}
public void addFragment(PageFragment f){
fragmentsList.add(f);
notifyDataSetChanged();
}
public void removeFragment(int position){
fragmentsList.remove(position);
notifyDataSetChanged();
}
public void removeAllFragments(){
fragmentsList.clear();
notifyDataSetChanged();
}
private PageFragment findFragmentByName(String cityName){
for(PageFragment fragment: fragmentsList){
if(fragment.getCityName().equals(cityName))
return fragment;
}
return null;
}
public void updateFragment(CityInfo cityInfo){
String cityName = cityInfo.getCityName();
OnCityInfoChanged fragment = (OnCityInfoChanged)findFragmentByName(cityName);
String population = cityInfo.getPopulation();
fragment.onCityInfoChanged(population);
notifyDataSetChanged();
}
}
PageFragment.java:
public class PageFragment extends Fragment implements OnCityInfoChanged{
private TextView cityNameText;
private TextView populationText;
String cityName;
String population;
public PageFragment(){}
public PageFragment(String cityName, String population){
this.cityName = cityName;
this.population = population
}
public PageFragment(CityInfo cityInfo){
this.cityName = cityInfo.getCityName();
this.population = cityInfo.getPopulation();
}
public PageFragment(String cityName){
this.cityName = cityName;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_city_page2, container, false);
cityNameText = (TextView)rootView.findViewById(R.id.city_name);
populationText = (TextView)rootView.findViewById(R.id.population);
setCityName(cityName);
setPopulation(population)
return rootView;
}
public void setCityName(String name){
cityNameText.setText(name);
}
public void setPopulation(String population){
populationText.setText(population);
}
public String getCityName(){
return cityName;
}
#Override
public void onCityInfoChanged(String population) {
//setCityName(cityName);
setPopulation();
}
}
I would advise to remove the AsyncTask AccessWebServiceTask from the MainActivity and put it in the Fragment PageFragment. And then in this fragment, override onActivityCreated, start the AsyncTask.
[EDIT]
Here is an update version of your code. Test it if it works :
MainActivity
public class MainActivity extends Activity{
private List<City> cityList;
private ViewPager mPager; /*ViewPager for show the page of city info*/
private ScreenSlidePagerAdapter mPagerAdapter; /* Adapter for the ViewPager,
* ScreenSlidePagerAdapter is a subclass of FragmentStatePagerAdapter*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_city);
cityList = new ArrayList<City>();
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
init();
}
private void init(){
loadCities(); //Load cities from database into cityList
initFragments();
}
private void initFragments(){
mPagerAdapter.removeAllFragments();
for(City city: cityList){
PageFragment fragment = PageFragment.newFragment(city.getName());
mPagerAdapter.addFragment(fragment);
}
}
}
ScreenSlidePagerAdapter :
public class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter{
private List<PageFragment> fragmentsList;
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
fragmentsList = new ArrayList<PageFragment>();
}
public ScreenSlidePagerAdapter(FragmentManager fm, List<PageFragment> list){
super(fm);
fragmentsList = list;
}
#Override
public PageFragment getItem(int position) {
return fragmentsList.get(position);
}
#Override
public int getCount() {
return fragmentsList.size();
}
public void setFragmentsList(List<PageFragment> fragmentsList){
this.fragmentsList = fragmentsList;
notifyDataSetChanged();
}
public void addFragment(PageFragment f){
fragmentsList.add(f);
notifyDataSetChanged();
}
public void removeFragment(int position){
fragmentsList.remove(position);
notifyDataSetChanged();
}
public void removeAllFragments(){
fragmentsList.clear();
notifyDataSetChanged();
}
}
PageFragment :
public class PageFragment extends Fragment {
private TextView cityNameText;
private TextView populationText;
private String cityName;
private String population;
public static final String CITY_NAME_KEY = "cityname";
public PageFragment(){}
public static PageFragment newFragment(String cityName){
PageFragment fragment = new PageFragment();
Bundle args = new Bundle();
args.putString(CITY_NAME_KEY, cityName);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate (Bundle savedInstanceState){
super.onCreate();
if(savedInstanceState != null){
this.cityName = savedInstanceState.getString(CITY_NAME_KEY);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_city_page2, container, false);
cityNameText = (TextView)rootView.findViewById(R.id.city_name);
populationText = (TextView)rootView.findViewById(R.id.population);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
if(this.cityName != null){
String request = "http://example.abc.com/" + cityName + "&output=json";
new AccessWebServiceTask().execute(request, cityName);
}
}
public void setCityName(String name){
cityNameText.setText(name);
}
public void setPopulation(String population){
populationText.setText(population);
}
public String getCityName(){
return cityName;
}
private class AccessWebServiceTask extends AsyncTask<String, Void, CityInfo>{
#Override
protected CityInfo doInBackground(String... urls) {
String result = getWebContent(urls[0]); /*Access web through HTTP*/
String cityName = urls[1];
/*Transform the String result to a CityInfo object containing information of a city*/
CityInfo cityInfo = encodeJason(result, cityName);
return cityInfo;
}
protected void onPostExecute(CityInfo cityInfo){
OnCityGot(cityInfo);
}
}
public void onCityGot(CityInfo cityInfo){
if(cityInfo != null){
String population = cityInfo.getPopulation();
setPopulation(population);
}
}
}
You can try ConditionVariable, it can be used to hold AsyncTask
private ConditionVariable mCondition = new ConditionVariable(false);
mCondition.block(); //used to block
// your condition
mCondition.open(); // used to open
First, you shouldn't use Fragment constructors with parameters. You should send the arguments to the fragment in bundle set to the fragments arguments. See: https://stackoverflow.com/a/15392591/360211
I would have the fragment call the obtainCityInfo method in it's onCreate. And no more lookups then, I can pass the OnCityInfoChanged to the async task for it to call on the onPostExecute.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_city_page2, container, false);
cityNameText = (TextView)rootView.findViewById(R.id.city_name);
populationText = (TextView)rootView.findViewById(R.id.population);
setCityName(cityName);
obtainCityInfo(cityName, this);
return rootView;
}
private obtainCityInfo(String cityName, OnCityInfoChanged callback){
String request = "http://example.abc.com/"
+ cityName + "&output=json";
new AccessWebServiceTask(callback).execute(request, cityName);
}
Could be this is a dupe, but I've been looking for solutions and they always slightly differ from my problem.
So:
I'm currently creating an app that has 2 fragments that are swipeable. TaskGroupFragment shows a list and when you click on an item it wil slide to TasksFragment and show you a sublist. What I have to do now is send the id of the selected item from groups to tasks so I can get the sublist out of SQLite.
I know I'm supposed to communicate through the connected MainActivity and I'm already at the point that I've created an interface in TaskGroupsFragment and implemented this in the activity. Tried and tested and the activity receives the TaskGroupID.
The part where I'm stuck is getting this info in TasksFragment. Especially using swipeview makes this harder.
My code:
MainPagerAdapter:
public class MainPagerAdapter extends FragmentStatePagerAdapter {
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0: return TaskGroupFragment.newInstance();
case 1: return TasksFragment.newInstance();
default: return TaskGroupFragment.newInstance();
}
}
#Override
public int getCount() {
return 2;
}
}
TaskGroupActivity (sending fragment):
public class TaskGroupFragment extends ListFragment {
private DoItDataSource dataSource;
private List<TaskGroups> groups;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_group, container, false);
dataSource = new DoItDataSource(getActivity());
dataSource.open();
JSONContainer jsonContainer = dataSource.sqliteToContainer();
dataSource.close();
groups = jsonContainer.getTask_groups();
TaskGroupAdapter adapter = new TaskGroupAdapter(getActivity(), groups);
setListAdapter(adapter);
return view;
}
public static TaskGroupFragment newInstance() {
TaskGroupFragment tgf = new TaskGroupFragment();
return tgf;
}
public interface OnTaskGroupSelectedListener {
public void onTaskGroupSelected(String taskGroupId);
}
OnTaskGroupSelectedListener mListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnTaskGroupSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " Interface not implemented in activity");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
((MainActivity)getActivity()).setCurrentItem(1, true);
mListener.onTaskGroupSelected(groups.get(position).getId());
}
}
MainActivity:
public class MainActivity extends FragmentActivity implements
TaskGroupFragment.OnTaskGroupSelectedListener{
private SharedPreferences savedValues;
private DoItDataSource dataSource = new DoItDataSource(this);
private String identifier, user, domain;
private JSONContainer containerToday;
private JSONContainer containerTomorrow;
public ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
identifier = savedValues.getString("Identifier", "");
pager = (ViewPager) findViewById(R.id.activity_main_pager);
pager.setAdapter(new MainPagerAdapter(getSupportFragmentManager()));
if (identifier == null || identifier.equals("")) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("APP_ID", APP_ID);
startActivity(intent);
}
}
#Override
protected void onResume() {
super.onResume();
identifier = savedValues.getString("Identifier", "");
user = savedValues.getString("User", "");
domain = savedValues.getString("Domain", "");
boolean onBackPressed = savedValues.getBoolean("OnBackPressed", false);
//
// getting lists
//
}
private void resultHandling(String json, String day) {
if (day.equals("today")) {
Gson gson = new Gson();
containerToday = gson.fromJson(json, JSONContainer.class);
jsonToSQLite(containerToday, "Today");
} else if (day.equals("tomorrow")) {
Gson gson = new Gson();
containerTomorrow= gson.fromJson(json, JSONContainer.class);
jsonToSQLite(containerTomorrow, "Tomorrow");
}
}
String taskGroupId = "";
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
// Enter missing link here?
}
}
TaskFragment (receiving fragment):
public class TasksFragment extends ListFragment
implements OnClickListener {
private final static String TAG = "TaskItemFragment logging";
private DoItDataSource dataSource;
private List<Tasks> tasks;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_item, container, false);
Button backButton = (Button)
view.findViewById(R.id.fragment_task_item_bar_back_button);
dataSource = new DoItDataSource(getActivity());
dataSource.open();
tasks = dataSource.getTasks("204"); // 204 is a placeholder, TaskGroupId should be here
dataSource.close();
TasksAdapter adapter = new TasksAdapter(getActivity(), tasks);
setListAdapter(adapter);
backButton.setOnClickListener(this);
return view;
}
public static TasksFragment newInstance() {
TasksFragment tif = new TasksFragment();
return tif;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(), "Clicked item " + position, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.fragment_task_item_bar_back_button:
((MainActivity)getActivity()).setCurrentItem(0, true);
break;
}
}
}
Solution
Thanks to Alireza! I had to make several changes to his proposed code, but in the end it helped me in finding the solution!
MainPageAdapter:
public class MainPagerAdapter extends FragmentStatePagerAdapter {
// ADDED
private String taskGroupId;
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0: return TaskGroupFragment.newInstance();
// MODIFIED
case 1:
Bundle args = new Bundle();
logcat("before setBundle " + taskGroupId);
args.putString("taskGroupId",taskGroupId);
Fragment fragment = new TasksFragment();
fragment.setArguments(args);
return fragment;
default: return TaskGroupFragment.newInstance();
}
}
// ADDED
public void setTaskGroupId(String id){
this.taskGroupId = id;
}
#Override
public int getCount() {
return 2;
}
}
MainActivity:
public class MainActivity extends FragmentActivity implements
TaskGroupFragment.OnTaskGroupSelectedListener{
private SharedPreferences savedValues;
private DoItDataSource dataSource = new DoItDataSource(this);
private String identifier, user, domain;
private JSONContainer containerToday;
private JSONContainer containerTomorrow;
// ADDED
private MainPagerAdapter adapter;
public ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
identifier = savedValues.getString("Identifier", "");
// ADDED
adapter = new MainPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.activity_main_pager);
// MODIFIED
pager.setAdapter(adapter);
if (identifier == null || identifier.equals("")) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("APP_ID", APP_ID);
startActivity(intent);
}
}
#Override
protected void onResume() {
super.onResume();
identifier = savedValues.getString("Identifier", "");
user = savedValues.getString("User", "");
domain = savedValues.getString("Domain", "");
boolean onBackPressed = savedValues.getBoolean("OnBackPressed", false);
//
// Getting lists
//
}
String taskGroupId = "";
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
// ADDED
adapter.setTaskGroupId(taskGroupId);
pager.setAdapter(adapter);
pager.setCurrentItem(1);
}
}
TaskFragment (receiving fragment):
public class TasksFragment extends ListFragment implements OnClickListener {
private final static String TAG = "TaskItemFragment logging";
private DoItDataSource dataSource;
private List<Tasks> tasks;
private String taskGroupId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_item, container, false);
Button backButton = (Button) view.findViewById(R.id.fragment_task_item_bar_back_button);
dataSource = new DoItDataSource(getActivity());
// ADDED
Bundle bundle = getArguments();
taskGroupId = bundle.getString("taskGroupId");
// MODIFIED
dataSource.open();
tasks = dataSource.getTasks(taskGroupId);
dataSource.close();
TasksAdapter adapter = new TasksAdapter(getActivity(), tasks);
setListAdapter(adapter);
backButton.setOnClickListener(this);
return view;
}
// CAN BE REMOVED?
//public static TasksFragment newInstance() {
// TasksFragment tif = new TasksFragment();
// return tif;
//}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(), "Clicked item " + position, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.fragment_task_item_bar_back_button:
((MainActivity)getActivity()).setCurrentItem(0, true);
break;
}
}
}
Please note that I'm using taskGroupId as a String, not an int.
First you need to make sure your adapter knows about taskGroupID. just add a variable and a public method to your adapter.
public class MainPagerAdapter extends FragmentStatePagerAdapter {
private int taskGroupId;
public void setTaskGroupId(int id){
this.taskGroupId = id;
}
}
then store a reference to your adapter in your activity. Now simply call this method whenever GroupId changes
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
adapter.setTastGroupId = taskGroupId; //data needed to initialize fragment.
adapter.setCurrentItem(1); //going to TasksFragment page
}
then you need to put some argumants before starting your fragment.
#Override
public Fragment getItem(int i) {
//this code is only for case 1:
Bundle args = new Bundle();
args.putInt("taskGroupId",taskGroupId);
Fragment fragment = new TasksFragment();
fragment.setArguments(args);
return fragment;
}
and lastly use this data in your TaskFragment to show the right content.
My app uses a ViewPager in portrait mode and a dual-fragment layout in landscape.
I am trying to kick off an AsyncTask, that is in the Fragment, from Activity. The AsyncTask is normally started from a menu item in the Actionbar, but I have a need to start it programatically from the Activity.
The menu item is an ImageView and I'm animating it while the AsyncTask is running. The code I have works fine in the dual-fragment landscape view, but I'm getting a NullPointerException on the menu item when in portrait mode.
Activity
public class Main extends SherlockFragmentActivity
{
private static List<Integer> mIds;
private static SparseArray<Fragment> mPageReferenceMap = new SparseArray<Fragment>();
#Override
public void onCreate(final Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
mViewPager = (ViewPager)findViewById(R.id.viewpager); //view pager exists, so we are using the portait layout
if (mViewPager != null)
{
mIds = new ArrayList<Integer>();
mIds.add(0);
mIds.add(1);
mIds.add(2);
}
else //in landscape
{
ListFragment lf = (ListFragment)getSupportFragmentManager().findFragmentById(R.id.fragmentList);
if (lf == null)
lf = new ListFragment();
DetailFragment df = (DetailFragment)getSupportFragmentManager().findFragmentById(R.id.fragmentDetail);
if (df == null)
{
df = new DetailFragment();
df.setArguments(getIntent().getExtras());
}
getSupportFragmentManager().beginTransaction().add(R.id.fragmentList, lf).commit();
getSupportFragmentManager().beginTransaction().add(R.id.fragmentDetail, df).commit();
}
final MyFragmentPagerAdapter fpa = (MyFragmentPagerAdapter)mViewPager.getAdapter();
ListFragment lf2 = (ListFragment)fpa.getFragment(0);
//this works if I use:
//(ListFragment)getSupportFragmentManager().findFragmentById(R.id.fragmentList);
lf2.RunTask();
}
private static class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
if (index == 0)
{
ListFragment lf = ListFragment.newInstance();
mPageReferenceMap.put(index, lf);
return lf;
}
else
{
DetailFragment df = DetailFragment.newInstance(mIds.get(index-1));
mPageReferenceMap.put(index, df);
return df;
}
public Fragment getFragment(int key) {
return mPageReferenceMap.get(key);
}
public void destroyItem(View container, int position, Object object) {
super.destroyItem(container, position, object);
mPageReferenceMap.remove(position);
}
#Override
public int getCount() {
return 4;
}
}
}
Fragment
public class ListingFragment extends SherlockListFragment
{
private MenuItem refreshItem;
public static ListingFragment newInstance() {
ListingFragment lf = new ListingFragment();
return lf;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.listing_layout, container, false);
}
private void StartAnimation() {
final LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ImageView ivRefresh = (ImageView)inflater.inflate(R.layout.refresh_view, null);
final Animation rotation = AnimationUtils.loadAnimation(getActivity(), R.anim.refresh);
ivRefresh.startAnimation(rotation);
//this is null
refreshItem.setActionView(ivRefresh);
}
public void StopAnimation()
{
if (refreshItem != null && refreshItem.getActionView() != null)
{
refreshItem.getActionView().clearAnimation();
refreshItem.setActionView(null);
}
}
public void RunTask()
{
new GetItems().execute();
}
private class GetItems extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute()
{
StartAnimation();
}
#Override
protected Void doInBackground(Void... unused)
{
...
}
protected void onPostExecute(final Void unused)
{
StopAnimation();
}
}
#Override
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
inflater.inflate(R.menu.keyword_menu, menu);
refreshItem = menu.findItem(R.id.get);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(final MenuItem item)
{
if (item.getItemId() == R.id.get) {
gi = new GetItems(getActivity(), null);
gi.execute();
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
}
I think following link provide you with your answer on how to avoid the nullpointer exception.
Fragment's instances may be recreated by the system at any time, that's why it's not easy to "hold a reference to them". You have to use the fragmentmanager.
adapter instance gone in fragment with listview