查找JSON数组的列表项索引

时间:2012-11-16 13:36:46

标签: android arrays android-activity

我正在编写一个Android应用程序,该应用程序显示动态填充的文本视图,其中包含两行JSON文件。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="7dp"
    >
<TextView  
    android:id="@+id/item_name"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:padding="2dp"
    android:textSize="20dp" />
    <TextView  
    android:id="@+id/item_type"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:padding="2dp"
    android:textSize="13dp" />
</LinearLayout>

当点击任何列表项时,我需要获取该索引的其余JSON数组内容,并将其作为要显示的数组传递给下一个活动。

这是First Activity Java:

public class TutListActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String sJSON = "";

    if(sJSON == ""){

        InputStream is = this.getResources().openRawResource(R.raw.data);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String readLine = null;
        StringBuilder sb = new StringBuilder();

        try {

            while ((readLine = br.readLine()) != null) {

            sb.append(readLine);
        }
        sJSON = sb.toString();

        is.close();
        br.close();

        } catch (IOException e) {
            e.printStackTrace();
        }       
    }

    String name = "";
    String type = "";
    String material = "";
    String welding = "";
    String primarybase = "";
    String tipmaterial = "";
    String shape = "";
    String shellcoating = "";

    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

    try{
        JSONObject jObject = new JSONObject(sJSON);
        JSONArray  pluginfo = jObject.getJSONArray("parts");

        for(int i=0; i < pluginfo.length(); i++) {
            JSONObject array = pluginfo.getJSONObject(i);

            name = array.getString("name");
            type = array.getString("type");
            material = array.getString("material");
            welding = array.getString("welding");
            primarybase = array.getString("primarybase");
            tipmaterial = array.getString("tipmaterial");
            shape = array.getString("shape");
            shellcoating = array.getString("shellcoating");

            HashMap<String, String> list = new HashMap<String, String>();
            JSONObject e = pluginfo.getJSONObject(i);

            list.put("id",  String.valueOf(i));
            list.put("name", "Plug name: " + e.getString("name"));
            list.put("type", "Type: " +  e.getString("type"));
            mylist.add(list);

            }
        }

    catch(JSONException e){
         Log.e("log_tag", "Error parsing data "+e.toString());
    }

    ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.list_item,
            new String[] { "name", "type" },
            new int[] { R.id.item_name, R.id.item_type });

    setListAdapter(adapter);

    final Intent intent1 = new Intent(getApplicationContext(), TutViewerActivity.class);

    intent1.putExtra("name", name);
    intent1.putExtra("type", type);
    intent1.putExtra("material", material);
    intent1.putExtra("welding", welding);
    intent1.putExtra("primarybase", primarybase);
    intent1.putExtra("tipmaterial", tipmaterial);
    intent1.putExtra("shape", shape);
    intent1.putExtra("shellcoating", shellcoating);

    final ListView lv = getListView();
    lv.setTextFilterEnabled(true);
    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            startActivity(intent1);
        }
    });
}

}

第二个活动Java:

public class TutViewerActivity extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

        Bundle extras = getIntent().getExtras();

        String name = extras.getString("name");
        String type = extras.getString("type");
        String material = extras.getString("material");
        String welding = extras.getString("welding");
        String primarybase = extras.getString("primarybase");
        String tipmaterial = extras.getString("tipmaterial");
        String shape = extras.getString("shape");
        String shellcoating = extras.getString("shellcoating");

        TextView itemName = (TextView)findViewById(R.id.item_name);
        TextView itemType = (TextView)findViewById(R.id.item_type);
        TextView itemMaterial = (TextView)findViewById(R.id.item_material);
        TextView itemWelding = (TextView)findViewById(R.id.item_welding);
        TextView itemPrimarybase = (TextView)findViewById(R.id.item_primarybase);
        TextView itemTipmaterial = (TextView)findViewById(R.id.item_tipmaterial);
        TextView itemShape = (TextView)findViewById(R.id.item_shape);
        TextView itemShellcoating = (TextView)findViewById(R.id.item_shellcoating);

        itemName.setText(name);
        itemType.setText(type);
        itemMaterial.setText(material);
        itemWelding.setText(welding);
        itemPrimarybase.setText(primarybase);
        itemTipmaterial.setText(tipmaterial);
        itemShape.setText(shape);
        itemShellcoating.setText(shellcoating);

    }
}

名称和类型字段都填入第一页。我需要获取剩余的信息“material” - “shellcoating”传递给我点击的项目并将其作为数组传递给下一个Activity。

logcat错误:

11-06 00:42:07.585: E/AndroidRuntime(3122): FATAL EXCEPTION: main
11-06 00:42:07.585: E/AndroidRuntime(3122): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mamlambo.tutorial.tutlist/com.mamlambo.tutorial.tutlist.TutViewerActivity}: java.lang.NullPointerException
11-06 00:42:07.585: E/AndroidRuntime(3122):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
11-06 00:42:07.585: E/AndroidRuntime(3122):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-06 00:42:07.585: E/AndroidRuntime(3122):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-06 00:42:07.585: E/AndroidRuntime(3122):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-06 00:42:07.585: E/AndroidRuntime(3122):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-06 00:42:07.585: E/AndroidRuntime(3122):     at android.os.Looper.loop(Looper.java:137)
11-06 00:42:07.585: E/AndroidRuntime(3122):     at android.app.ActivityThread.main(ActivityThread.java:4745)
11-06 00:42:07.585: E/AndroidRuntime(3122):     at java.lang.reflect.Method.invokeNative(Native Method)
11-06 00:42:07.585: E/AndroidRuntime(3122):     at java.lang.reflect.Method.invoke(Method.java:511)
11-06 00:42:07.585: E/AndroidRuntime(3122):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-06 00:42:07.585: E/AndroidRuntime(3122):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-06 00:42:07.585: E/AndroidRuntime(3122):     at dalvik.system.NativeStart.main(Native Method)
11-06 00:42:07.585: E/AndroidRuntime(3122): Caused by: java.lang.NullPointerException
11-06 00:42:07.585: E/AndroidRuntime(3122):     at com.mamlambo.tutorial.tutlist.TutViewerActivity.onCreate(TutViewerActivity.java:62)
11-06 00:42:07.585: E/AndroidRuntime(3122):     at android.app.Activity.performCreate(Activity.java:5008)
11-06 00:42:07.585: E/AndroidRuntime(3122):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
11-06 00:42:07.585: E/AndroidRuntime(3122):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
11-06 00:42:07.585: E/AndroidRuntime(3122):         ... 11 more

有关如何轻松完成此操作的任何想法?感谢。

2 个答案:

答案 0 :(得分:2)

在任何方法之外实例化变量,只要它们不会在您现有的Activity中更改值而不需要它们。这允许您将Variable值从方法传递给方法。

String material;

以下是解析JSONArray的简化版本:

for(i=0; i < jArray.length(); i++) {
    JSONObject jObject = jArray.getJSONObject(i);
    material = jObject.getString("material");
}

使用Intent,将上面显示的“material”字符串传递给您的下一个活动:

Intent passJSONIntent = new Intent(CurrentActivity.this, NextActivity.class);
passJSONIntent.putExtra("material", material);
startActivity(passJSONIntent);

Intent的{​​{1}} NextActivity onCreate()中检索额外内容:

Bundle extras = getIntent().getExtras();
String material = extras.getString("material");
TextView itemType = (TextView)findViewById(R.id.item_type);
itemType.setText(material);

修改

好的,现在你所缺少的只是setContentView(R.layout.yourLayout);

public class TutViewerActivity extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yourLayout);

        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

        Bundle extras = getIntent().getExtras();

        //etc...

答案 1 :(得分:-1)

你能用伪代码来解释你想要什么吗?

我不知道你是否在寻找:

myList.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> a, View v, int position, long id) {


                Intent intent = new Intent(MYCLASS.this, NEXTACTIVITYCLASS.class);
                Bundle b = new Bundle();
                //TRY TO DECODE JSON
                String myJsonString = decodeMYJSON(MYJSON);

                b.putString("JSON",myJsonString);
                intent.putExtras(b); 
                startActivity(intent);

                                          }});