Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

web services - How to select a particular item from the listview in android?

I have one list-view.It contains some data from the web-service by consuming it.

Here my need is, if i click any item from that list-view, it wants to show data from the web service. have i to write any loop code for this?if so how?examples please. How to do this?

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 class Stations {

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>

suggestions please Thanks for your precious time!..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Include this code in your 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();



      }
    });

Update after LogCat

What you're getting is a JSONException which has got nothing to do with your listener. Please change

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

to:

 JSONArray array = new JSONArray(res_data);

That's going to solve the exception.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...