尝试在空对象引用上调用虚拟方法 'android.content.Context android.support.v4.app.FragmentActivity.getApplicationConte
Posted
技术标签:
【中文标题】尝试在空对象引用上调用虚拟方法 \'android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext()\'【英文标题】:Attempt to invoke virtual method 'android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext()' on a null object reference尝试在空对象引用上调用虚拟方法 'android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext()' 【发布时间】:2016-08-05 13:57:57 【问题描述】:以下是我的片段代码,我收到上述空异常错误
/**
* Created by USer on 09-04-2016.
*/
public class FeaturedFragment extends android.support.v4.app.Fragment
private List url;
private SliderLayout sliderLayout;
private GridView gridView;
private int firstVisiblepos;
AppnextAPI api;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
View rootView = inflater.inflate(
R.layout.featured, container, false);
url = new ArrayList<String>();
url.add("http://192.168.5.51/Wallpapers/Autumn.jpg");
url.add("http://192.168.5.51/Wallpapers/Tree.jpg");
url.add("http://192.168.5.51/Wallpapers/Flower.jpg");
url.add("http://192.168.5.51/Wallpapers/Lion.jpg");
api = new AppnextAPI(getActivity(), "my id");
sliderLayout = (SliderLayout) rootView.findViewById(R.id.slider);
gridView = (GridView) rootView.findViewById(R.id.gridView);
ThemeShowcase theme = new ThemeShowcase();
theme.execute("getThemes");
for (int i = 0; i < url.size(); i++)
TextSliderView textSliderView = new TextSliderView(getActivity().getApplicationContext());
textSliderView.image((String) url.get(i));
sliderLayout.addSlider(textSliderView);
sliderLayout.setDuration(4000);
sliderLayout.setPresetTransformer(SliderLayout.Transformer.Stack);
return rootView;
private class ThemeShowcase extends AsyncTask<String, Integer, ArrayList<ThemeModel>>
private final String NAMESPACE = "http://tempuri.org/";
private final String URL = "http://192.168.5.51/WebApplication/WebService.asmx";
private final String SOAP_ACTION = "http://tempuri.org/";
private String responseString;
private ArrayList model = null;
private ThemeModel dummy;
@Override
protected void onPreExecute()
super.onPreExecute();
model = new ArrayList<ThemeModel>();
@Override
protected ArrayList<ThemeModel> doInBackground(String... params)
try
SoapObject request = new SoapObject(NAMESPACE, params[0]);
PropertyInfo sayHelloPI = new PropertyInfo();
sayHelloPI.setName("page");
sayHelloPI.setValue("1");
sayHelloPI.setType(Integer.class);
request.addProperty(sayHelloPI);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION + params[0], envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
responseString = response.toString();
if (!responseString.equalsIgnoreCase("Error occured"))
JSONArray array = new JSONArray(responseString);
for (int i = 0; i < array.length(); i++)
JSONObject objct = array.getJSONObject(i);
dummy = new ThemeModel();
dummy.preview = objct.getString("Preview");
dummy.name = objct.getString("Name");
model.add(dummy);
catch (Exception e)
model = null;
return model;
return model;
@Override
protected void onPostExecute(ArrayList<ThemeModel> model)
if(model!=null)
gridView.setAdapter(new ImageAdapter(getActivity().getApplicationContext(), model));
firstVisiblepos = gridView.getFirstVisiblePosition();
else
try
Toast.makeText(getActivity().getApplicationContext(), "Site Unreachable", Toast.LENGTH_LONG).show();
catch (Exception e)
Log.d("MyApp","exception");
这是我的图像适配器
public class ImageAdapter extends BaseAdapter implements View.OnClickListener
private Context context;
private LayoutInflater inflater;
private ArrayList<ThemeModel> model;
public ImageAdapter(Context context,ArrayList<ThemeModel> model)
this.inflater = LayoutInflater.from(context);
this.context = context;
this.model = model;
@Override
public int getCount()
return model.size();
@Override
public Object getItem(int position)
return null;
@Override
public long getItemId(int position)
return 0;
@Override
public View getView(int position, View convertView, ViewGroup parent)
convertView = inflater.inflate(R.layout.custom_item,null);
CardView cardView = (CardView)convertView.findViewById(R.id.cardView);
cardView.setOnClickListener(this);
ImageView imageView = (ImageView)convertView.findViewById(R.id.imageView);
final ProgressBar progressBar = (ProgressBar)convertView.findViewById(R.id.progressbar);
TextView textView = (TextView)convertView.findViewById(R.id.contentName);
ImageButton imageButton = (ImageButton)convertView.findViewById(R.id.downloadButton);
textView.setText(model.get(position).getName());
Picasso.with(context).load(model.get(position).getPreview()).into(imageView, new Callback()
@Override
public void onSuccess()
progressBar.setVisibility(View.GONE);
@Override
public void onError()
);
return convertView;
@Override
public void onClick(View v)
我一直在下面的行上逼近
gridView.setAdapter(new ImageAdapter(getActivity().getApplicationContext(), model));
错误是
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext()' on a null object reference
我尝试过使用 getActivity()、getContext() 等,但它们都不起作用
【问题讨论】:
仅尝试getActivity()
我也试过了,但没有成功
doInBackground 需要多长时间才能完成它的任务?
显示你的图像适配器
***.com/questions/16920942/…查看此链接
【参考方案1】:
原因是因为当你在onPostExecute()
中调用getActivity()
时,Fragment
已经与Activity
分离(例如,当AsyncTask正在执行时,用户点击返回按钮退出活动) ,所以getActivity()
将为空。
解决方法是在getActivity()
之前,检查isAdded()
是否为真,如果不为真,则表示片段已经分离,调用getActivity()
将返回null。
记住在AsyncTask中,在调用getActivity()
之前,最好再次检查isAdded()
,因为在AsyncTask执行过程中用户可能随时退出活动。
【讨论】:
拯救了我的一天:“记住在 AsyncTask 中,在调用 getActivity() 之前的任何地方,最好再次检查 isAdded(),因为在 AsyncTask 执行期间用户可能随时退出活动。”以上是关于尝试在空对象引用上调用虚拟方法 'android.content.Context android.support.v4.app.FragmentActivity.getApplicationConte的主要内容,如果未能解决你的问题,请参考以下文章
尝试在空对象引用上调用虚拟方法 'android.graphics.Rect android.graphics.drawable.Drawable.getBounds()'
尝试在空对象引用上调用虚拟方法 'android.view.Window$Callback android.view.Window.getCallback()'
尝试在空对象引用上调用虚拟方法 'android.os.Handler android.support.v4.app.FragmentHostCallback.getHandler()'
尝试在空对象引用上调用虚拟方法 'void android.view.View.measure(int, int)'