大家好,我需要一点帮助,因为我在调用片段时正在接受他的异常。 我已经创建了一个自定义列表适配器,我将它分配给我的片段的列表视图。 我认为使用Volley进行的网络通话可能是一个问题。 我们应该在片段内部进行网络呼叫?我已经尝试过OnResume,OnActivityCreated和OnCreateView。 我已经测试了它,并且从Web服务正确地获取了数据但是我将我的ArrayList数据传递给Custom Adapter并且我在setAdapter方法null异常时收到了错误。 以下是我的实现
NewsFragment.java
public class NewsFragment extends Fragment {
private ListView listView;
private FeedListAdapter listAdapter;
private List<News> feedItems;
private String URL_FEED = "http://stajevi.com/api/Haber/Listele";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onResume() {
super.onResume();
feedItems = new ArrayList<News>();
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Cache.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 JSONArray(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonArrayRequest jsonReq=new JsonArrayRequest(URL_FEED, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray jsonArray) {
if (jsonArray != null)
parseJsonFeed(jsonArray);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
volleyError.printStackTrace();
}
});
jsonReq.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS*2,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_register, container, false);
listView = (ListView) rootView.findViewById(R.id.list);
if(feedItems==null)
Toast.makeText(getContext(),"feed items is null",Toast.LENGTH_SHORT).show();
listAdapter = new FeedListAdapter(getActivity(), feedItems);
if(listAdapter==null)
Toast.makeText(getContext(),"list adapter is null",Toast.LENGTH_SHORT).show();
else
listView.setAdapter(listAdapter);
return rootView;
}
private void parseJsonFeed(JSONArray response) {
try {
Toast.makeText(getContext(),((JSONObject)response.get(0)).getString("NewsShortTitle"),Toast.LENGTH_LONG).show();
for (int i = 0; i < response.length(); i++) {
JSONObject feedObj = (JSONObject) response.get(i);
News item = new News();
// item.setNewsActive(feedObj.getBoolean("NewsActive"));
// item.setNewsCreateUserId(feedObj.getString("NewsCreateUserId"));
item.setNewsDescription(feedObj.getString("NewsDescription"));
// item.setNewsEndDate(feedObj.getString("NewsEndDate"));
// item.setNewsID(feedObj.getInt("NewsID"));
item.setNewsShortTitle(feedObj.getString("NewsShortTitle"));
item.setNewsStartDate(feedObj.getString("NewsStartDate"));
item.setNewsTitle(feedObj.getString("NewsTitle"));
// item.setNewsType(feedObj.getInt("NewsType"));
item.setTitleSourceUrl(feedObj.getString("TitleSourceUrl"));
// item.setTitleType(feedObj.getInt("TitleType"));
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
FeedListAdapter.java
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<News> feedItems;
ImageLoader imageLoader;
public FeedListAdapter(Activity activity, List<News> feedItems) {
this.feedItems = feedItems;
this.activity=activity;
imageLoader = AppController.getInstance().getImageLoader();
}
@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;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.news_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);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
News item = feedItems.get(position);
name.setText(item.getNewsShortTitle());
String date=item.getNewsStartDate();
date=date.substring(0,10);
timestamp.setText(date);
// Feed image
if (item.getTitleSourceUrl() != null) {
feedImageView.setImageUrl(item.getTitleSourceUrl(), 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;
}
}
堆栈跟踪
04-15 13:34:01.133 1921-1921/com.uygulama.stajevi E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.uygulama.stajevi.NewsFragment.onCreateView(NewsFragment.java:105)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
fragment_register.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.uygulama.stajevi.RegisterFragment">
<!-- TODO: Update blank fragment layout -->
<include
android:id="@+id/tool_bar"
layout="@layout/tool_bar"
/>
<EditText android:textSize="20sp"
android:textColorHint="@color/smoothGray"
android:id="@+id/nameEditText"
android:focusableInTouchMode="true"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:hint="@string/name"
android:singleLine="true"
android:layout_marginTop="25dp"
android:background="@drawable/rounded_edittext"
android:layout_below="@+id/tool_bar"
android:layout_marginLeft="@dimen/margin_left_text_box"
android:layout_marginRight="@dimen/margin_right_text_box"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText android:textSize="20sp"
android:textColorHint="@color/smoothGray"
android:id="@+id/emailEditText"
android:focusableInTouchMode="true"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:inputType="text"
android:hint="@string/email"
android:singleLine="true"
android:layout_marginTop="25dp"
android:background="@drawable/rounded_edittext"
android:layout_below="@+id/nameEditText"
android:layout_marginLeft="@dimen/margin_left_text_box"
android:layout_marginRight="@dimen/margin_right_text_box"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText android:textSize="18sp"
android:textColorHint="@color/smoothGray"
android:id="@+id/passwEditText"
android:focusableInTouchMode="true"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:hint="@string/password"
android:singleLine="true"
android:inputType="textPassword"
android:layout_marginTop="25dp"
android:background="@drawable/rounded_edittext"
android:layout_below="@+id/emailEditText"
android:layout_marginLeft="@dimen/margin_left_text_box"
android:layout_marginRight="@dimen/margin_right_text_box"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText android:textSize="18sp"
android:textColorHint="@color/smoothGray"
android:id="@+id/repassEditText"
android:focusableInTouchMode="true"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:hint="@string/repeat_password"
android:singleLine="true"
android:inputType="textPassword"
android:layout_marginTop="25dp"
android:background="@drawable/rounded_edittext"
android:layout_below="@+id/passwEditText"
android:layout_marginLeft="@dimen/margin_left_text_box"
android:layout_marginRight="@dimen/margin_right_text_box"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_height="wrap_content"
android:text="Hemen Uye Ol"
android:textColor="@color/backcolor"
android:background="@drawable/turuncu_button_border"
android:id="@+id/btnGiris"
android:textAllCaps="false"
android:layout_marginTop="36dp"
android:layout_marginLeft="@dimen/margin_left_text_box"
android:layout_marginRight="@dimen/margin_right_text_box"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="@+id/repassEditText"
/>
答案 0 :(得分:0)
Your problem is that your listView
is null so basically check that R.id.list
is inside R.layout.fragment_register
, I guess that this R.id.list
id is in another layout, and the one that you need have another name.
Hope this helps!!