コードの冗長性を減らすために、JSON 文字列から取得した Int 値を渡そうとしています。
JSON ファイル内の " resFile " に文字列値があります。この文字列をTAG_RES_FILEに保存し、バンドルに Int として渡します。
私のコードを見ると、//TRY #1//というコメントが表示されます。これは期待どおりに機能しますが、 TAG_RES_FILEを格納する変数からIntを取得する必要があります。コメント//TRY #2// は、私が機能したいものの単なる例です-明らかにそうではありません。次の行で、タグ文字列をIntに変換しようとしましたが、これにより次のランタイム エラーが発生します。
java.lang.NumberFormatException: 無効な int: "resFile"
0x7f060000 (R.java から) を JSON 文字列に入れてみました。
だから私の質問は:どうすればこれを達成できますか?私は正しい道を進んでいますか、それともまったく別の方法で進むべきですか?
ご協力とご意見をありがとうございます - 回答にコード例を示してください。
JSON 文字列スニピット:
[
{
"_id": "1",
"label": "A Lable",
"title": "Some Title",
"description": "Bla, bla, bla",
"containerID": "Some container id",
"isRawRes": "boolean value here",
"resFile": "R.raw.advisory_circulators_sort_list"
}, {. . .
]
私のHashMapで:
// Parse the string to a JSON object
for (int i = 0; i < json.length(); i++) {
JSONObject json_data = json.getJSONObject(i);
// Storing each json item in variable
String id = json_data.getString(TAG_ID);
String label = json_data.getString(TAG_LABEL);
String title = json_data.getString(TAG_TITLE);
String description = json_data.getString(TAG_DISCR);
String containerID = json_data.getString(TAG_FRAG_ID);
String isRawRes = json_data.getString(TAG_IS_RAW_RES);
String resFile = json_data.getString(TAG_RES_FILE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_LABEL, label);
map.put(TAG_TITLE, title);
map.put(TAG_DISCR, description);
map.put(TAG_FRAG_ID, containerID);
map.put(TAG_IS_RAW_RES, isRawRes);
map.put(TAG_RES_FILE, resFile);
// adding HashList to ArrayList
mList.add(map);
}
私のListViews setOnItemClickListenerで:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
. . .
final Bundle args = new Bundle();
//TRY #1//int rawRes = R.raw.advisory_circulators_sort_list; <--I NEED TO GET THIS IN FROM MY TAG!!
//TRY #2//int rawRes = TAG_RES_FILE; <-- TO SOMETHING LIKE THIS!!
int passResFile = Integer.parseInt(TAG_RES_FILE);//<--THIS GIVES A NPE!!
args.putInt("KEY_RES_FILE", passResFile);
bolean isRawRes = true;
args.putBoolean("KEY_IS_RAW_RES", isRawRes);
// Delayed to improve animations
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
ListViewFragment lvf = new ListViewFragment();
lcFT.replace(R.id.listContainer, lvf).commit();
lvf.setArguments(args);
}
}, 300);
}