我在下面的代码工作,但我不知道如何在onCreateView方法上使用以下对象( responseCurrentConditionsClassObject )而不会出现空点异常错误?
public class PlaceCurrentFragment extends Fragment {
private static final String ARG_CITYID = "cityid";
private String mCityId;
// String used to indicate the title on a ViewPager
public final String PAGERTABTITLE = "Now";
private OnFragmentInteractionListener mListener;
// Tag for logging possible errors onto the Log
private static String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
public static final String DOMAIN = "http://api.openweathermap.org";
public static final String ENDPOINT = "/data/2.5/weather?";
public static final String CITYIDPARAMETER = "id=";
public static final String APPIDPARAMETER = "&appid=someapinumber";
Gson gson;
ResponseCurrentConditions responseCurrentConditionsClassObject;
public PlaceCurrentFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param cityid Parameter 1.
* @return A new instance of fragment PlaceCurrentFragment.
*/
public static PlaceCurrentFragment newInstance(String cityid) {
PlaceCurrentFragment fragment = new PlaceCurrentFragment();
Bundle args = new Bundle();
args.putString(ARG_CITYID, cityid);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mCityId = getArguments().getString(ARG_CITYID);
}
// Shows message to user while makeJsonObjectRequest() is still running.
pDialog = new ProgressDialog(getContext());
pDialog.setMessage("Getting weather forecast...");
pDialog.setCancelable(false);
// Make JSON request
makeJsonObjectRequest(mCityId);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_place_current, container, false);
TextView mCityIdTextView = (TextView) view.findViewById(R.id.city_id);
// NULL POINT EXCEPTION HERE!!
mCityIdTextView.setText(responseCurrentConditionsClassObject.getName());
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
/**
* Method to make json object request
*/
private void makeJsonObjectRequest(final String cityId) {
// Show dialog while the request is made
showpDialog();
String URL = DOMAIN + ENDPOINT + CITYIDPARAMETER + cityId + APPIDPARAMETER;
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
URL, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// Log response
Log.d(TAG, response.toString());
String responseString = new String(String.valueOf(response));
gson = new Gson();
// **PROBLEM WITH THIS OBJECT BEING ACCESSIBLE ON onCreateView() METHOD**
responseCurrentConditionsClassObject = gson.fromJson(responseString, ResponseCurrentConditions.class);
hidepDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Warn user
Toast.makeText(getContext(),
"No internet connection", Toast.LENGTH_LONG).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
/**
* Method for showing dialog
*/
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
/**
* Method for hiding dialog
*/
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
如果我尝试访问onCreateView()方法上的对象,如下所示,我得到一个空异常错误。
responseCurrentConditionsClassObject.getName();
我做错了什么?这与makeJsonObjectRequest中的volley请求的异步方面有关,在该方面,对象可能没有准备好,或者在被调用的时候为null,或者它是否更简单,我错过了什么?任何详细的反馈将不胜感激。
答案 0 :(得分:1)
这是因为当你点击这一行时:
mCityIdTextView.setText(responseCurrentConditionsClassObject.getName());
截击请求尚未返回响应。
您可以做的是将该行代码放入截击请求的onResponse
。
首先使mCityIdTextView
成为成员变量。
public class PlaceCurrentFragment extends Fragment {
private TextView mCityIdTextView;
// etc
然后在onCreateView
中找到它:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_place_current, container, false);
mCityIdTextView = (TextView) view.findViewById(R.id.city_id);
return view;
}
最后在onResponse
:
@Override
public void onResponse(JSONObject response) {
// Log response
Log.d(TAG, response.toString());
String responseString = new String(String.valueOf(response));
gson = new Gson();
responseCurrentConditionsClassObject = gson.fromJson(responseString, ResponseCurrentConditions.class);
mCityIdTextView.setText(responseCurrentConditionsClassObject.getName());
hidepDialog();
}
答案 1 :(得分:0)
我们需要查看更多信息,例如responseString和ResponseCurrentConditions类..
但我们可以发出诊断+建议......
您的应用程序有onCreate
和onCreateView
,生命周期中的调用顺序正常,因此在makeJsonObjectRequest(mCityId);
之前调用方法onCreateView
,很好。
问题是NullPointer异常,原因是因为你有对象ResponseCurrentConditions,它是null或者它包含空字段(例如名字字段)
调试您的应用程序并验证是否
responseString
中的json字符串正确映射到该类的所有必要成员。