java Android Volley 空指针异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25697362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android Volley Null Pointer Exception
提问by user2793987
I'm attempting to convert a previously Activity-based tutorial to a Fragment, but I continue to run into the NullPointerException error on my Adapter.
我正在尝试将以前基于 Activity 的教程转换为 Fragment,但我继续在我的适配器上遇到 NullPointerException 错误。
The tutorial is based on thisand I have slimmed down the constructor for the Adapter because it used to be calling an Activity.
本教程基于此,我精简了 Adapter 的构造函数,因为它曾经调用一个 Activity。
There is one possible solution herebut nobody knows how to proceed with the same possible question.
这里有一种可能的解决方案,但没有人知道如何处理相同的可能问题。
I want to convert everything to a working Fragment. Please let me know if you need more information from me.
我想将所有内容转换为工作片段。如果您需要我提供更多信息,请告诉我。
Main converted class:
主要转换类:
public class mainViewController2 extends Fragment {
private static final String TAG = mainViewController2.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://api.androidhive.info/feed/feed.json";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.mainviewcontroller2_fragment, container, false);
listView = (ListView) v.findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
//where the error shows up?
listAdapter = new FeedListAdapter(feedItems);
listView.setAdapter(listAdapter);
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
return v;
}
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
FeedListAdapter:
FeedListAdapter:
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<FeedItem> feedItems;
Context context;
ImageLoader imageLoader;
public FeedListAdapter(Context ctx,List<FeedItem> feedItems) {
this.context= ctx;
this.feedItems = feedItems;
imageLoader = AppController.getInstance().getImageLoader();
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return feedItems.size();
}
@Override
public Object getItem(int location) {
return feedItems.get(location);
}
@Override
public long getItemId(int position) {
return position;
}
@SuppressLint("InflateParams")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.feed_item, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
TextView statusMsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
NetworkImageView profilePic = (NetworkImageView) convertView
.findViewById(R.id.profilePic);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
FeedItem item = feedItems.get(position);
name.setText(item.getName());
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance());
url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// user profile pic
profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
@Override
public void onError() {
}
@Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
return convertView;
}
}
LogCat errors:
LogCat 错误:
09-06 02:51:55.823: E/AndroidRuntime(8279): FATAL EXCEPTION: main
09-06 02:51:55.823: E/AndroidRuntime(8279): Process: com.rynovation.kline, PID: 8279
09-06 02:51:55.823: E/AndroidRuntime(8279): java.lang.NullPointerException
09-06 02:51:55.823: E/AndroidRuntime(8279): at androidFeedClasses.FeedListAdapter.<init>(FeedListAdapter.java:35)
09-06 02:51:55.823: E/AndroidRuntime(8279): at com.rynovation.kline.mainViewController2.onCreateView(mainViewController2.java:51)
09-06 02:51:55.823: E/AndroidRuntime(8279): at android.app.Fragment.performCreateView(Fragment.java:1700)
09-06 02:51:55.823: E/AndroidRuntime(8279): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
09-06 02:51:55.823: E/AndroidRuntime(8279): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
09-06 02:51:55.823: E/AndroidRuntime(8279): at android.app.BackStackRecord.run(BackStackRecord.java:684)
09-06 02:51:55.823: E/AndroidRuntime(8279): at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1453)
09-06 02:51:55.823: E/AndroidRuntime(8279): at android.app.FragmentManagerImpl.run(FragmentManager.java:443)
09-06 02:51:55.823: E/AndroidRuntime(8279): at android.os.Handler.handleCallback(Handler.java:733)
09-06 02:51:55.823: E/AndroidRuntime(8279): at android.os.Handler.dispatchMessage(Handler.java:95)
09-06 02:51:55.823: E/AndroidRuntime(8279): at android.os.Looper.loop(Looper.java:146)
09-06 02:51:55.823: E/AndroidRuntime(8279): at android.app.ActivityThread.main(ActivityThread.java:5487)
09-06 02:51:55.823: E/AndroidRuntime(8279): at java.lang.reflect.Method.invokeNative(Native Method)
09-06 02:51:55.823: E/AndroidRuntime(8279): at java.lang.reflect.Method.invoke(Method.java:515)
09-06 02:51:55.823: E/AndroidRuntime(8279): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
09-06 02:51:55.823: E/AndroidRuntime(8279): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
09-06 02:51:55.823: E/AndroidRuntime(8279): at dalvik.system.NativeStart.main(Native Method)
回答by user3902144
I guess you missed a simple code in your manifest file. Your AppController
package extends Application
, So the application tag in your manifest is searching for the AppController
but isn't able to find.
我猜你错过了清单文件中的一个简单代码。您的AppController
包 extends Application
,因此清单中的应用程序标记正在搜索AppController
但无法找到。
Just Write this simple code in your AndroidManifest.xml
只需在您的 AndroidManifest.xml
android:name = your.package.AppController
android:name = your.package.AppController
回答by David Passmore
A little late maybe, but a representative answer to user3902144's answer:
可能有点晚了,但对 user3902144 的回答有代表性:
Similar Answer to this question : Link
这个问题的类似答案:链接
You may have missed out this from your manifest:
您可能在清单中遗漏了这一点:
<application
android:name="<package-name>.app.AppController" // <-- this one
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
That's why onCreate never called and mInstance is null.
这就是为什么从不调用 onCreate 并且 mInstance 为空的原因。
Hope this helps :)
希望这可以帮助 :)
回答by bph
Looking at the error, it seems like you're calling getActivity()
inside onCreateView()
. You should be getting the activity in onActivityCreated
instead where it shouldn't be null.
查看错误,您似乎在调用getActivity()
inside onCreateView()
。您应该在onActivityCreated
不应该为空的地方获取活动。
回答by Piyush
Change this from
改变这个从
listView = (ListView) getActivity().findViewById(R.id.list);
to
到
listView = (ListView)v.findViewById(R.id.list);
This is because getActivity()
is generally used for as a Context
in Fragment. While you'r find id for your UI
elements in Fragment then you have to give reference of your View's
object which will be returned in onCreateView()
method.
这是因为getActivity()
通常用作Context
片段中的一个。当您UI
在 Fragment 中找到元素的id 时,您必须提供View's
将在onCreateView()
方法中返回的对象的引用。
Update:
更新:
Change your Adapter Like,
改变你的适配器喜欢,
listAdapter = new FeedListAdapter(getActivity(),feedItems);
Now in its Constructor
现在在它的构造函数中
ImageLoader imageLoader;
public FeedListAdapter(Context ctx,List<FeedItem> feedItems) {
this.context= ctx;
this.feedItems = feedItems;
imageLoader = AppController.getInstance().getImageLoader()
}
Now in your adapter class use context
variable as a Context
.
现在在您的适配器类中使用context
变量作为Context
.
回答by Mehroz Munir
Please check all your params carefully, make sure not to send any null value in params, if using some stored values then use the condition like below:
请仔细检查所有参数,确保不要在 params 中发送任何空值,如果使用某些存储值,则使用如下条件:
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
if(paramValue!= null)
params.put("paramKey", paramValue);
else
params.put("paramKey", "anyOtherDefaultValue");
return params;
}