我正在尝试将“id”从我的 fragment Activity 发送到一个 Activity ,并根据这个“id”字段解析 json 数据。
我成功地将数据从 fragment 发送到 TourDetail Activity ,但它没有根据相同的“id”解析 json。代码没有到达第二个 try block ,因为我使用 toasts 检查了它。
尽管当我从其他一些 Activity 中传递“id”时,相同的 Activity (TourDetailActivity.java) 工作正常。比如说,如果我从 jsonuseactivity.java 传递了“id”,它会被 TourDetailActivity.java 成功接收并生成相应的 json 结果并显示相应的结果。
但是,如果从 fragment Activity 中传递了相同的“id”,它虽然收到了“id”但没有生成 json,并且没有生成基于 json 的所需结果。
TourDetailActivity.java
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tour_detail);
Intent intent = getIntent();
String rcvid = intent.getStringExtra("id");
Toast.makeText(getApplicationContext(), rcvid, Toast.LENGTH_LONG).show();
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("tourid", rcvid));
String response = null;
// call executeHttpPost method passing necessary parameters
try {
Toast.makeText(getApplicationContext(), "in try block", Toast.LENGTH_LONG).show();
response = CustomHttpClient.executeHttpPost(
//"http://129.107.187.135/CSE5324/jsonscript.php", // your ip address if using localhost server
"http://www.futurolicht.com/jsontour.php", // in case of a remote server
postParameters);
String result = response.toString();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
//parse json data
try {
Toast.makeText(getApplicationContext(), "in 2nd try block", Toast.LENGTH_LONG).show();
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
tname = (TextView) findViewById(R.id.txt_tourtitle);
td = (TextView) findViewById(R.id.txt_day);
tn = (TextView) findViewById(R.id.txt_night);
tdest = (TextView) findViewById(R.id.txt_tourdetail_dest);
btn = (Button) findViewById(R.id.btn_tourdetail);
btn.setOnClickListener(this);
tname.setText(json_data.getString("tour_name"));
tn.setText(json_data.getString("nights"));
td.setText(json_data.getString("days"));
name = json_data.getString("tour_name");
n = json_data.getString("nights");
d = json_data.getString("days");
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
这是我的 Fragmentone.java 的 onCreate()
方法代码:
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_one, null);
String fontPath = "fonts/ox.ttf";
b1 = (Button)root.findViewById(R.id.featured_btn1);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String id = "34";
Intent intent = new Intent(getActivity(), TourDetailActivity.class);
intent.putExtra("id", id);
getActivity().startActivity(intent);
}
});
最佳答案
我不知道实际发生了什么,因为上面的代码对我来说似乎没问题。您可以将变量设置为 Static
并在其他类(如 Fragmentone.id
)中访问该变量,而不是发送数据。这绝对有效。
您是否还尝试在 onStart()
而不是 onCreate()
中捕获 id
?在启动时检查是否有参数传递给 fragment 很方便
关于java - 将数据从 fragment 发送到 Activity 并解析 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18659870/