问题
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 {
...
}
}
回答1:
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 mContex
t to startActivity
Intent i = new Intent(mContext, PantallaInfo.class);
mContext.startActivity(i);
startActivity
is a method of Activity class. Requires Activity context.
来源:https://stackoverflow.com/questions/19120205/intent-in-asynctask-for-fragmentpageradapter