从ListView获取一个明确的字符串

时间:2014-05-16 13:15:44

标签: android string listview

如果按下按钮,我有一个ListView搜索蓝牙设备。 这很好。 它在一行中显示名称,在另一行中显示地址。 现在我想将地址保存在字符串中。 但是我怎样才能从ListView中读取这个地址呢? 希望你能理解我的问题。 对不起我的英语我不是一个天真的演讲者=)

这是我的代码:

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;


public class Suchen extends Activity {

        private static final int REQUEST_ENABLE_BT = 1;

     Bluetooth connection;
     ListView listDevicesFound;
     Button btnScanDevice;
     TextView stateBluetooth;
     BluetoothAdapter bluetoothAdapter;

     ArrayAdapter<String> btArrayAdapter;

     /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_suchen);

            btnScanDevice = (Button)findViewById(R.id.scandevice);

            stateBluetooth = (TextView)findViewById(R.id.bluetoothstate);
            bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

            listDevicesFound = (ListView)findViewById(R.id.devicesfound);
            btArrayAdapter = new ArrayAdapter<String>(Suchen.this, android.R.layout.simple_list_item_1);
            listDevicesFound.setAdapter(btArrayAdapter);

            CheckBlueToothState();

            btnScanDevice.setOnClickListener(btnScanDeviceOnClickListener);

            registerReceiver(ActionFoundReceiver, 
              new IntentFilter(BluetoothDevice.ACTION_FOUND));


              listDevicesFound.setOnItemClickListener(new OnItemClickListener() {
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                      // When clicked, show a toast with the TextView text
                      Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
                          Toast.LENGTH_SHORT).show();
                    }
                  });
             }




        @Override
     protected void onDestroy() {
      // TODO Auto-generated method stub
      super.onDestroy();
      unregisterReceiver(ActionFoundReceiver);
     }

     private void CheckBlueToothState(){
         if (bluetoothAdapter == null){
             stateBluetooth.setText("Bluetooth wird NICHT unterstützt");
            }else{
             if (bluetoothAdapter.isEnabled()){
              if(bluetoothAdapter.isDiscovering()){
               stateBluetooth.setText("Geräte werden gesucht.");
              }else{
               stateBluetooth.setText("Bluetooth ist eingeschaltet.");
               btnScanDevice.setEnabled(true);
              }
             }else{
              stateBluetooth.setText("Bluetooth is NICHT eingeschaltet!");
              Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                 startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
             }
            }
        }

        private Button.OnClickListener btnScanDeviceOnClickListener
        = new Button.OnClickListener(){

      @Override
      public void onClick(View arg0) {
       // TODO Auto-generated method stub
       btArrayAdapter.clear();
       bluetoothAdapter.startDiscovery();
      }};

     @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      // TODO Auto-generated method stub
      if(requestCode == REQUEST_ENABLE_BT){
       CheckBlueToothState();
      }
     }       

     //String definieren, der die MAC-Adresse speichert
     public static String a;


     private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){

      @Override
      public void onReceive(Context context, Intent intent) {
       // TODO Auto-generated method stub
       String action = intent.getAction();
       if(BluetoothDevice.ACTION_FOUND.equals(action)) {
                 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                 btArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                 btArrayAdapter.notifyDataSetChanged();
                 a = device.getAddress();
       }
      }

     };
      public void verbinden_01 (View view) {


                Intent intent = new Intent(this, Bluetooth.class);
                System.out.println(a);
                intent.putExtra("ADRESSE", a);
                startActivity(intent);
            }
     }

目前我想将地址保存在字符串a。

愿它有所帮助。所以这是我的logcat

05-16 16:54:37.261: W/ActivityThread(24898): Application com.example.obdii is waiting for the debugger on port 8100...
05-16 16:54:37.266: I/System.out(24898): Sending WAIT chunk
05-16 16:54:37.356: I/dalvikvm(24898): Debugger is active
  05-16 16:54:37.466: I/System.out(24898): Debugger has connected
05-16 16:54:37.466: I/System.out(24898): waiting for debugger to settle...
05-16 16:54:37.666: I/System.out(24898): waiting for debugger to settle...
05-16 16:54:37.866: I/System.out(24898): waiting for debugger to settle...
05-16 16:54:38.071: I/System.out(24898): waiting for debugger to settle...
    05-16 16:54:38.271: I/System.out(24898): waiting for debugger to settle...
05-16 16:54:38.471: I/System.out(24898): waiting for debugger to settle...
05-16 16:54:38.671: I/System.out(24898): waiting for debugger to settle...
05-16 16:54:38.871: I/System.out(24898): waiting for debugger to settle...
05-16 16:54:39.071: I/System.out(24898): debugger has settled (1409)
05-16 16:54:39.251: D/dalvikvm(24898): GC_FOR_ALLOC freed 54K, 11% free 7139K/7939K,   paused 15ms, total 15ms
05-16 16:54:39.256: I/dalvikvm-heap(24898): Grow heap (frag case) to 8.596MB for 1046688-byte allocation
05-16 16:54:39.276: D/dalvikvm(24898): GC_CONCURRENT freed 1K, 10% free 8160K/8967K, paused 12ms+1ms, total 23ms
05-16 16:54:39.381: D/libEGL(24898): loaded /system/lib/egl/libEGL_mali.so
05-16 16:54:39.381: D/libEGL(24898): loaded /system/lib/egl/libGLESv1_CM_mali.so
05-16 16:54:39.386: D/libEGL(24898): loaded /system/lib/egl/libGLESv2_mali.so
05-16 16:54:39.386: D/(24898): Device driver API match
05-16 16:54:39.386: D/(24898): Device driver API version: 10
05-16 16:54:39.386: D/(24898): User space API version: 10 
05-16 16:54:39.386: D/(24898): mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Tue Oct 16 15:37:13 KST 2012 
05-16 16:54:39.421: D/OpenGLRenderer(24898): Enabling debug mode 0
05-16 16:54:41.341: D/AbsListView(24898): Get MotionRecognitionManager
05-16 16:54:41.731: E/SpannableStringBuilder(24898): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
05-16 16:54:41.731: E/SpannableStringBuilder(24898): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
05-16 16:54:50.156: E/SpannableStringBuilder(24898): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
05-16 16:54:50.161: E/SpannableStringBuilder(24898): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
05-16 16:54:58.786: D/AndroidRuntime(24898): Shutting down VM
05-16 16:54:58.786: W/dalvikvm(24898): threadid=1: thread exiting with uncaught exception (group=0x41e5a2a0)
05-16 16:54:58.841: E/AndroidRuntime(24898): java.lang.IllegalStateException: Could  not execute method of the activity
05-16 16:54:58.841: E/AndroidRuntime(24898):    at android.view.View$1.onClick(View.java:3704)
05-16 16:54:58.841: E/AndroidRuntime(24898):    at android.view.View.performClick(View.java:4232)
05-16 16:54:58.841: E/AndroidRuntime(24898):    at android.view.View$PerformClick.run(View.java:17318)
05-16 16:54:58.841: E/AndroidRuntime(24898):    at android.os.Handler.handleCallback(Handler.java:615)
05-16 16:54:58.841: E/AndroidRuntime(24898):    at android.os.Handler.dispatchMessage(Handler.java:92)
05-16 16:54:58.841: E/AndroidRuntime(24898):    at android.os.Looper.loop(Looper.java:137)
05-16 16:54:58.841: E/AndroidRuntime(24898):    at android.app.ActivityThread.main(ActivityThread.java:4921)
05-16 16:54:58.841: E/AndroidRuntime(24898):    at java.lang.reflect.Method.invokeNative(Native Method)
05-16 16:54:58.841: E/AndroidRuntime(24898):    at java.lang.reflect.Method.invoke(Method.java:511)
05-16 16:54:58.841: E/AndroidRuntime(24898):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
05-16 16:54:58.841: E/AndroidRuntime(24898):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
 05-16 16:54:58.841: E/AndroidRuntime(24898):   at dalvik.system.NativeStart.main(Native Method)
 05-16 16:54:58.841: E/AndroidRuntime(24898): Caused by: java.lang.reflect.InvocationTargetException
05-16 16:54:58.841: E/AndroidRuntime(24898):    at java.lang.reflect.Method.invokeNative(Native Method)
05-16 16:54:58.841: E/AndroidRuntime(24898):    at java.lang.reflect.Method.invoke(Method.java:511)
05-16 16:54:58.841: E/AndroidRuntime(24898):    at android.view.View$1.onClick(View.java:3699)
05-16 16:54:58.841: E/AndroidRuntime(24898):    ... 11 more
05-16 16:54:58.841: E/AndroidRuntime(24898): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
05-16 16:54:58.841: E/AndroidRuntime(24898):    at com.example.obdii.Suchen.verbinden_01(Suchen.java:133)
05-16 16:54:58.841: E/AndroidRuntime(24898):    ... 14 more

1 个答案:

答案 0 :(得分:1)

到目前为止,正如我所看到的,您可以在以下行将文本推送到适配器:

btArrayAdapter.add(device.getName() + "\n" + device.getAddress());

因此,您的ListItem内部只有一个TextView,文字为device.getName() + "\n" + device.getAddress()

稍后,您通过以下调用检索它,以便在Toast显示onItemClickListener

((TextView) view).getText()

如果您知道,该分隔符只是\n,您可以拆分指定此分隔符的行:

String myText = ((TextView) view).getText();
String address = myText.split("\n")[1];

a是一个类成员,所以它在任何内部类中都可见。