如何从android中的listview中选择一个特定的项目?

时间:2013-03-20 07:16:56

标签: android web-services listview

我有一个list-view。它包含来自web服务的一些数据,通过消费它。

我需要的是,如果我点击该列表视图中的任何项目,它希望显示来自Web服务的数据。 我要为此编写任何循环代码吗?如果是这样的话?请举例。 怎么做?

logcat的

03-20 13:09:07.187: W/KeyCharacterMap(275): No keyboard for id 0
03-20 13:09:07.187: W/KeyCharacterMap(275): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
03-20 13:09:13.116: I/System.out(275): Transparent  17170445
03-20 13:09:13.136: W/System.err(275): org.json.JSONException: Value Login of type java.lang.String cannot be converted to JSONArray
03-20 13:09:13.136: W/System.err(275):  at org.json.JSON.typeMismatch(JSON.java:107)
03-20 13:09:13.136: W/System.err(275):  at org.json.JSONArray.<init>(JSONArray.java:91)
03-20 13:09:13.136: W/System.err(275):  at org.json.JSONArray.<init>(JSONArray.java:103)
03-20 13:09:13.136: W/System.err(275):  at  com.example.png.StationsListActivity.callService(StationsListActivity.java:115)
03-20 13:09:13.136: W/System.err(275):  at com.example.png.StationsListActivity$4.run(StationsListActivity.java:103)
03-20 13:09:13.196: D/AndroidRuntime(275): Shutting down VM
03-20 13:09:13.196: W/dalvikvm(275): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
03-20 13:09:13.206: E/AndroidRuntime(275): FATAL EXCEPTION: main
03-2 0 13:09:13.206: E/AndroidRuntime(275): java.lang.NullPointerException
03-20 13:09:13.206: E/AndroidRuntime(275):  at com.example.png.StationsListActivity$1.handleMessage(StationsListActivity.java:43)
03-20 13:09:13.206: E/AndroidRuntime(275):  at android.os.Handler.dispatchMessage(Handler.java:99)
03-20 13:09:13.206: E/AndroidRuntime(275):  at android.os.Looper.loop(Looper.java:123)
03-20 13:09:13.206: E/AndroidRuntime(275):  at android.app.ActivityThread.main(ActivityThread.java:4627)
03-20 13:09:13.206: E/AndroidRuntime(275):  at java.lang.reflect.Method.invokeNative(Native Method)
03-20 13:09:13.206: E/AndroidRuntime(275):  at java.lang.reflect.Method.invoke(Method.java:521)
03-20 13:09:13.206: E/AndroidRuntime(275):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-20 13:09:13.206: E/AndroidRuntime(275):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-20 13:09:13.206: E/AndroidRuntime(275):  at dalvik.system.NativeStart.main(Native Method)

StationsListActivity.java

public class StationsListActivity extends Activity {

TextView txt;
String res_data;

Button btn_info;
ListView listView;

ProgressDialog progressDialog;
List<Stations> list;

Handler handler =new Handler()
{
    public void handleMessage(android.os.Message msg) 
    {
        if(progressDialog.isShowing())
        {
        progressDialog.cancel();
        if(list.size() > 0)
        {
        listView.setAdapter(new StationAdapter(StationsListActivity.this, android.R.id.text1,list));    
        }
        else
        {
        Toast.makeText(StationsListActivity.this, "List is Empty",Toast.LENGTH_LONG).show();    
        }
        }
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.stations_list_layout);

    listView = (ListView)findViewById(R.id.listView_stations);

    Bundle extras=getIntent().getExtras();

    if(extras!=null)
    {
        res_data =extras.getString("transfered_data");
    }

    System.out.println("Transparent  "+android.R.color.transparent);
    listView = (ListView) findViewById(R.id.listView_stations);

    btn_info = (Button)findViewById(R.id.btn_info);
    progressDialog = new ProgressDialog(StationsListActivity.this);
    progressDialog.setTitle("Loading");
    progressDialog.setMessage("Please Wait");
    btn_info.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        Intent intnt = new Intent(StationsListActivity.this , InformationsActivity.class);
        startActivity(intnt);           
        }
    });
    Thread thread =new Thread()
    {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            callService();
            handler.sendEmptyMessage(0);
        }
    };
    thread.start();
    progressDialog.show();
}


public void callService() {
    // TODO Auto-generated method stub
    try {
    JSONArray array = new JSONArray(String.valueOf(res_data).replace("verifyUserResponse{return=", "").replace("; }", ""));
    list = new ArrayList<Stations>();
    for (int i = 0; i < array.length(); i++) 
    {
        System.out.println(array.getJSONObject(i).get("1")+" == "+array.getJSONObject(i).get("0"));;
        Stations stations =new Stations();
        stations.station_code = (String) array.getJSONObject(i).get("0");
        stations.station_name = (String) array.getJSONObject(i).get("1");
        list.add(stations);
        stations = null;
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
    }
}

StationAdaper.java

public class StationAdapter extends ArrayAdapter<Stations> {

Context context;
List<Stations> list;

public StationAdapter(Context context, int textViewResourceId,
        List<Stations> objects) {
    super(context, textViewResourceId, objects);
    this.context = context ; 
    this.list = objects ;
    // TODO Auto-generated constructor stub
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.station_child, null);

    TextView name = (TextView) view.findViewById(R.id.textView_single_item);
    ImageView img = (ImageView)view.findViewById(R.id.imageView1);

    Stations stations =list.get(position);
    name.setText(stations.station_name);
    return view;

}}

Stations.java     公共类站     {

public String station_name ="";
public String station_code ="";


}

station_child.xml

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

<RelativeLayout

    android:layout_width="fill_parent"
    android:layout_height="55dp" >

    <TextView
        android:id="@+id/textView_single_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:inputType="text"
        android:textColor="#ffffff"
        android:textStyle="normal"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="10dp"
        android:background="@drawable/arrow"/>

</RelativeLayout></LinearLayout>
请提出建议 谢谢你宝贵的时间!..

2 个答案:

答案 0 :(得分:1)

在OnCreate中包含此代码

    // listening to single list item on click
    listview.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> parent, View view,
          int position, long id) {

          // selected item
          String nameOfStation = ((TextView)view.findViewById(R.id.textView_single_item)).getText().toString();



      }
    });

LogCat

后更新

你得到的是JSONException与你的听众无关。请更改

 JSONArray array = new JSONArray(String.valueOf(res_data).replace("verifyUserResponse{return=", "").replace("; }", ""));

为:

 JSONArray array = new JSONArray(res_data);

这将解决异常。

答案 1 :(得分:0)

如果您对如何从所选项目获取文本感到困惑,那么您应该使用listview.setOnItemClickListener

如果你以前没有,你应该通过这个例子。

http://developer.android.com/resources/tutorials/views/hello-listview.html