从具有JSON的listView启动新活动

时间:2013-08-04 06:18:00

标签: java android json listview listadapter

下面的代码是一个工作代码,它提供了listview

中获取的JSON的输出

Functionality i am trying to achive is ::

  • 如何制作,如果单击列表中的某一行,则会显示一个新行 活动?

Item.java

package com.example.testjson;

public class Item{
    private int age;
    private String name;
    private String city;
    private String gender;
    private String birthdate;        

    public Item(int age, String name, String city, String gender, String birthdate){
        this.age = age;
        this.name = name;
        this.city = city;
        this.gender = gender;
        this.birthdate = birthdate;
    }

    public int getAge(){
        return this.age;
    }

    public String getName(){
        return this.name;
    }

    public String getCity(){
        return this.city;
    }

    public String getGender(){
        return this.gender;
    }

    public String getBirthdate(){
        return this.birthdate;
    }
}

JSONParser.java

package com.example.testjson;

import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;

public class JSONParser {

    static InputStream is = null;
    static JSONArray jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONArray getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(url);

            Log.i("test", "hello1");
            HttpResponse httpResponse = httpClient.execute(httpPost);
            Log.i("test", "hello");
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

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

        try {
            Log.i("test", "4");
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            Log.i("test", "3");
            StringBuilder sb = new StringBuilder();
            Log.i("test", "2");
            String line = null;
            Log.i("test", "1");
            while ((line = reader.readLine()) != null) {
                Log.i("test", "line");
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        Log.i("test", "afterline");
        // try parse the string to a JSON object
        try {
            JSONObject jsonObject = new JSONObject(json);
            Log.i("parsing..", ""+jsonObject.get("student").toString());
            jObj = new JSONArray(jsonObject.get("student").toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

ListAdapter.java

package com.example.testjson;



import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;

public class ListAdapter extends ArrayAdapter<Item> {


    private List<Item> items;

    public ListAdapter(Context context, int resource, List<Item> items) {
        super(context, resource, items);
        this.items = items;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;

        TextView tt = null;
        TextView tt1 = null;
        TextView tt2 = null;
        TextView tt3 = null;
        TextView tt4 = null;

        if (v == null) {

            LayoutInflater vi;
            vi = LayoutInflater.from(getContext());
            v = vi.inflate(R.layout.itemlistrow, null);

            tt = (TextView) v.findViewById(R.id.age);
            tt1 = (TextView) v.findViewById(R.id.name);
            tt2 = (TextView) v.findViewById(R.id.city);
            tt3 = (TextView) v.findViewById(R.id.gender);
            tt4 = (TextView) v.findViewById(R.id.birthdate);
        }

        Item p = items.get(position);

        if (p != null) {

            if (tt != null) {
                tt.setText(""+p.getAge());
            }
            if (tt1 != null) {

                tt1.setText(""+p.getName());
            }
            if (tt2 != null) {

                tt2.setText(""+p.getCity());
            }

            if (tt3 != null) {

                tt3.setText(""+p.getGender());
            }

            if (tt4 != null) {

                tt4.setText(""+p.getBirthdate());
            }
        }



        return v;

    }
}

MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {

    private static String url="https://dl.dropboxusercontent.com/s/rhk01nqlyj5gixl/jsonparsing.txt?token_hash=AAHpfauVxJaC9Rkx_5abNtJnPFG04os7TZky1AhOuC5jEw";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Create a JSON parser Instance ----- Used JSON parser from Android
        JSONParser jParser=new JSONParser();

        //Getting JSON string from URL ------ Used JSON Array from Android
        JSONArray json=jParser.getJSONFromUrl(url);

        List<Item> yourData = new ArrayList<Item>();

        try {
            for(int i=0;i<json.length();i++)
            {
                JSONObject c=json.getJSONObject(i);// Used JSON Object from Android

                //Storing each Json in a string variable
                int AGE=c.getInt("age");
                String NAME=c.getString("name");
                String CITY=c.getString("city");
                String GENDER=c.getString("Gender");
                String BIRTHDATE=c.getString("birthdate");


                yourData.add(new Item(AGE, NAME, CITY, GENDER, BIRTHDATE));

            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        ListView yourListView = (ListView) findViewById(R.id.listViewID);

        ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, yourData);

        yourListView.setAdapter(customAdapter);

    }


}

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ListView
        android:id="@+id/listViewID"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" 
        android:layout_gravity="center">
    </ListView>

</LinearLayout>

itemlistrow.xml

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_height="wrap_content" android:orientation="vertical"
             android:layout_width="fill_parent">

    <TableRow android:layout_width="fill_parent"
              android:id="@+id/TableRow01"
              android:layout_height="wrap_content">

        <TextView
                android:id="@+id/age"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="age" android:textStyle="bold"
                android:gravity="left"
                android:layout_weight="1"
                android:typeface="monospace"
                android:height="40sp"/>
    </TableRow>

    <TableRow android:layout_height="wrap_content"
              android:layout_width="fill_parent">

        <TextView
                android:id="@+id/name"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="name"
                android:layout_weight="1"
                android:height="20sp"/>
    </TableRow>

    <TableRow android:layout_height="wrap_content"
              android:layout_width="fill_parent">

        <TextView
                android:id="@+id/city"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="city"
                android:layout_weight="1"
                android:height="20sp"/>
    </TableRow>

    <TableRow android:layout_height="wrap_content"
              android:layout_width="fill_parent">

        <TextView
                android:id="@+id/gender"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="city"
                android:layout_weight="1"
                android:height="20sp"/>
    </TableRow>

    <TableRow android:layout_height="wrap_content"
              android:layout_width="fill_parent">

        <TextView
                android:id="@+id/birthdate"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="city"
                android:layout_weight="1"
                android:height="20sp"/>
    </TableRow>

</TableLayout>

谢谢,

2 个答案:

答案 0 :(得分:0)

在您的项目列表行中:

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:id="@+id/row" // Please set id for each row. :)
             android:layout_height="wrap_content" android:orientation="vertical"
             android:layout_width="fill_parent">

之后

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View v = convertView;

    //.... Your code
    TableLayout mTableLayout = v.findViewById(R.id.itemrow); // Id which you set in layout
    mTableLayout.setOnClickListener() {
        @Override
        public void run() {
            Intent mItent = new Intent(YourActivity.class, DesActivity.class);
            mIntent.putExtra(); // Put what you want. [options]
            context.startActivity(mItent); // Start Activity
        }
    }

    return v;

}

答案 1 :(得分:0)

只需将onitemclick监听器附加到listview

即可

并覆盖onitem clik,如下所示..

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id)
{
    Intent HomeScreenIntent=new Intent(this, NewActivity.class);
    startActivity(HomeScreenIntent);        
}