简体   繁体   English

Android:无法将变量从BaseAdapter传递到Activity

[英]Android: Cannot Pass Variable from BaseAdapter to Activity

I'm really new to android and I search a lot but still haven't managed to solve this.As the title says I'm trying to pass a variable from a baseadapter class to another activity I get a null exception error the moment I try to retrieve the string value. 我对android真的很陌生,我搜索了很多东西,但仍然没有设法解决这个问题。正如标题所述,我试图将变量从baseadapter类传递给另一个活动,当我收到异常错误尝试检索字符串值。 Here's my code: 这是我的代码:

final String macaddress = holder.addressTv.getText().toString();

    holder.sendBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, SendString.class);

            intent.putExtra("macaddress", macaddress);
            context.startActivity(intent);
        }
    });

And I receive it at the SendString activity like this: 我在SendString活动中收到了这样的消息:

String address = getIntent().getStringExtra("macaddress");

Logcat : Logcat:

03-07 14:12:28.654  11047-11047/com.example.alexis.dikomoytest W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x2c040ce0)
03-07 14:12:28.654  11047-11047/com.example.alexis.dikomoytest E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.alexis.dikomoytest, PID: 11047
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.alexis.dikomoytest/com.example.alexis.dikomoytest.SendString}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2143)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2283)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5158)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at com.example.alexis.dikomoytest.SendString.<init>(SendString.java:41)
        at java.lang.Class.newInstanceImpl(Native Method)
        at java.lang.Class.newInstance(Class.java:1208)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2134) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2283) at android.app.ActivityThread.access$800(ActivityThread.java:144) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5158) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566) at dalvik.system.NativeStart.main(Native Method)

SendString.java SendString.java

public class SendString extends ActionBarActivity {

TextView out;
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;

private static final UUID MY_UUID =
        UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");


//private static String address = "0C:13:09:01:06:15";


String address = getIntent().getStringExtra("macaddress");



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

    out = (TextView) findViewById(R.id.out);

    out.append("\n...In onCreate()...");

    btAdapter = BluetoothAdapter.getDefaultAdapter();
    CheckBTState();
}

@Override
public void onStart() {
    super.onStart();
    out.append("\n...In onStart()...");
}

@Override
public void onResume() {
    super.onResume();

    out.append("\n...In onResume...\n...Attempting client connect...");


    BluetoothDevice device = btAdapter.getRemoteDevice(address);


    try {
        btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
    } catch (IOException e) {
        AlertBox("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
    }


    btAdapter.cancelDiscovery();


    try {
        btSocket.connect();
        out.append("\n...Connection established and data link opened...");
    } catch (IOException e) {
        try {
            btSocket.close();
        } catch (IOException e2) {
            AlertBox("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
        }
    }


    out.append("\n...Sending message to server...");

    try {
        outStream = btSocket.getOutputStream();
    } catch (IOException e) {
        AlertBox("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
    }

    String message = "Test.\n";
    byte[] msgBuffer = message.getBytes();
    try {
        outStream.write(msgBuffer);
    } catch (IOException e) {
        String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
        if (address.equals("00:00:00:00:00:00") || address.equals("NULL"))
            msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
        msg = msg +  ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";

        AlertBox("Fatal Error", msg);
    }
}

@Override
public void onPause() {
    super.onPause();

    out.append("\n...In onPause()...");

    if (outStream != null) {
        try {
            outStream.flush();
        } catch (IOException e) {
            AlertBox("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
        }
    }

    try     {
        btSocket.close();
    } catch (IOException e2) {
        AlertBox("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
    }
}

@Override
public void onStop() {
    super.onStop();
    out.append("\n...In onStop()...");
}

@Override
public void onDestroy() {
    super.onDestroy();
    out.append("\n...In onDestroy()...");
}

private void CheckBTState() {

    if(btAdapter==null) {
        AlertBox("Fatal Error", "Bluetooth Not supported. Aborting.");
    } else {
        if (btAdapter.isEnabled()) {
            out.append("\n...Bluetooth is enabled...");
        } else {
            //Prompt user to turn on Bluetooth
            Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }
}

public void AlertBox( String title, String message ){
    new AlertDialog.Builder(this)
            .setTitle( title )
            .setMessage( message + " Press OK to exit." )
            .setPositiveButton("OK", new OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    finish();
                }
            }).show();
}

} }

i think : 我认为 :

String address = getIntent().getStringExtra("macaddress");

return null . 返回null。 because you have error NullPointerException . 因为您有错误NullPointerException。

getIntent() is null out of onCreate callback and some others. 在onCreate回调和其他一些回调中, getIntent()为null。 Move String assignment to onCreate: 将字符串分配移动到onCreate:

address = getIntent().getStringExtra("macaddress");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM