【发布时间】:2018-01-08 11:05:46
【问题描述】:
我正在使用 Volley 库来获取 JSON 数据。在我的第一个 Fragment 中,我收到了一些需要在第二个 Fragment 中发送的值。我正在使用Bundles 在Fragments 之间传递数据。
这是我的 JSON 请求。
private void getCount() {
String url="http://192.168.1.106:9500/api/restqueue/";
String json_req = "json_req";
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject object=new JSONObject(response.toString());
count=object.getString("name");
}
catch (JSONException e)
{
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
String credentials = name+":"+pass;
String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Content-type", "application/json");
headers.put("Authorization", auth);
return headers;
}
};
AppController.getInstance().addToRequestQueue(req, json_req);
}
这是MainAtivity 中的代码,用于从 FragmentOne 沙化数据
Bundle bundle=new Bundle();
bundle.putString("totcount",count);
ChooseTab choose=new ChooseTab();
choose.setArguments(bundle);
这是从 FragmentTwo 中的Bundle 获取数据的代码
Bundle bundle=this.getArguments();
count=bundle.getString("totcount","empty");
这是在Bundle中添加数据的代码
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v=inflater.inflate(R.layout.choose,container,false);
test=(TextView)v.findViewById(R.id.test);
queue=(Button)v.findViewById(R.id.queue);
waiter=(Button)v.findViewById(R.id.waiter);
linearLayout=(LinearLayout)v.findViewById(R.id.choose);
prefs=getActivity().getPreferences(Context.MODE_PRIVATE);
name=prefs.getString("name","empty");
pass=prefs.getString("pass","empty");
getCount();
fm=getFragmentManager();
name.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String tag="";
tx=fm.beginTransaction();
Bundle bundle=new Bundle();
bundle.putString("totcount",count);
ChooseTab choose=new ChooseTab();
choose.setArguments(bundle);
tx.replace(R.id.frame,choose,tag);
tx.addToBackStack(tag);
tx.commit();
}
});
fullname.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String tagg="";
tx=fm.beginTransaction();
tx.replace(R.id.frame,new Waiter());
tx.addToBackStack(tagg);
tx.commit();
}
});
return v;
}
我遇到错误
Attempt to invoke virtual method 'java.lang.String android.os.BaseBundle.getString(java.lang.String, java.lang.String)' on a null object reference
如何解决这个问题?
【问题讨论】:
-
分享您在
FragmentOne中添加捆绑包的整个代码 -
FragmentTwo 真的是 ChooseTab 的一个实例吗?
-
在您的主要活动中检查过“计数”为空吗?
-
@Satyam,
fm是什么? -
片段管理器实例好友\
标签: android json android-fragments android-volley