需要帮助捆绑附加功能

时间:2013-04-16 17:46:51

标签: java android nullpointerexception

在我的新Java类(Tap.java)中实现以下空检查:

Bundle extras = getIntent().getExtras();
        if (extras == null) {
            Log.e(TAG, "received no extras!");

结果:

ViewCountry(11637): received no extras!

因此我相信我需要将附加内容捆绑到我创建的新类(Tap.java)以及它当前从我的CountryList.java捆绑到(ViewCountry.java)的类中。

如何实现这一目标?

我想扩展以下包以包含相同的数据(ROW_ID,arg3):

Intent viewCon = new Intent(CountryList.this, ViewCountry.class);
          viewCon.putExtra(ROW_ID, arg3);
          startActivity(viewCon);

如何将其扩展为将数据发送到Tap.java?

public class Tap extends Enable {

    private static final String TAG = ViewCountry.class.getName();

    protected Message message;

    NfcAdapter mNfcAdapter;
    private static final int MESSAGE_SENT = 1;
    private long rowID;
    private TextView nameTv;
    private TextView capTv;
    private TextView codeTv;
    private TextView timeTv;
    private TextView ssidTv;
    private TextView combined;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_country);
        setDetecting(true);
        startPushing();
        setUpViews();
        Bundle extras = getIntent().getExtras();
        rowID = extras.getLong(CountryList.ROW_ID);
    }

    private void setUpViews() {
        nameTv = (TextView) findViewById(R.id.nameText);
        capTv = (TextView) findViewById(R.id.capText);
        timeTv = (TextView) findViewById(R.id.timeEdit);
        codeTv = (TextView) findViewById(R.id.codeText);
        ssidTv = (TextView) findViewById(R.id.wifiSSID);


    }

    @Override
    public NdefMessage createNdefMessage(NfcEvent event) {
        Log.d(TAG, "Create message to be beamed");
        String a = "";
        String b = "";
        String message1 = a + ssidTv.getText().toString() + ","
                + capTv.getText().toString() + b;

        // create message to be pushed, for example
        Message message = new Message();
        // add text record
        message.add(new TextRecord(message1));
        // add 'my' external type record
    //  message.add(new GenericExternalTypeRecord("com.wifi.demo", "atype",
        //      "My data".getBytes(Charset.forName("UTF-8"))));

        // encode to NdefMessage, will be pushed via beam (now!) (unless there
        // is a collision)
        return message.getNdefMessage();
    }

    /**
     * 
     * Implementation of {@link OnNdefPushCompleteCallback} interface.
     * 
     * This method is called after a successful transfer (push) of a message
     * from this device to another.
     */

    @Override
    protected void onNdefPushCompleteMessage() {
        // make toast
        toast(R.string.nfcBeamed);

        // vibrate
        Vibrator vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        vibe.vibrate(500);
    }

    public void toast(int id) {
        toast(getString(id));
    }

    public void toast(String message) {
        Toast toast = Toast.makeText(this, message, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL,
                0, 0);
        toast.show();
    }

    /**
     * 
     * NFC was found and enabled in settings, and push is enabled too.
     * 
     */

    @Override
    protected void onNfcPushStateEnabled() {
        toast(getString(R.string.nfcBeamAvailableEnabled));
    }

    /**
     * 
     * NFC was found and enabled in settings, but push is disabled
     * 
     */

    @Override
    protected void onNfcPushStateDisabled() {
        toast(getString(R.string.nfcBeamAvailableDisabled));
    }

    /**
     * 
     * NFC beam setting changed since last check. For example, the user enabled
     * beam in the wireless settings.
     * 
     */

    @Override
    protected void onNfcPushStateChange(boolean enabled) {
        if (enabled) {
            toast(getString(R.string.nfcBeamAvailableEnabled));
        } else {
            toast(getString(R.string.nfcBeamAvailableDisabled));
        }
    }

    /**
     * 
     * NFC feature was found and is currently enabled
     * 
     */

    @Override
    protected void onNfcStateEnabled() {
        toast(getString(R.string.nfcAvailableEnabled));
    }

    /**
     * 
     * NFC feature was found but is currently disabled
     * 
     */

    @Override
    protected void onNfcStateDisabled() {
        toast(getString(R.string.nfcAvailableDisabled));
    }

    /**
     * 
     * NFC setting changed since last check. For example, the user enabled NFC
     * in the wireless settings.
     * 
     */

    @Override
    protected void onNfcStateChange(boolean enabled) {
        if (enabled) {
            toast(getString(R.string.nfcAvailableEnabled));
        } else {
            toast(getString(R.string.nfcAvailableDisabled));
        }
    }

    /**
     * 
     * This device does not have NFC hardware
     * 
     */

    @Override
    protected void onNfcFeatureNotFound() {
        toast(getString(R.string.noNfcMessage));
    }

    /**
     * An NDEF message was read and parsed
     * 
     * @param message
     *            the message
     */

    @Override
    protected void readNdefMessage(Message message) {
        if (message.size() > 1) {
            toast(getString(R.string.readMultipleRecordNDEFMessage));
        } else {
            toast(getString(R.string.readSingleRecordNDEFMessage));
        }
    }

    /**
     * An empty NDEF message was read.
     * 
     */

    @Override
    protected void readEmptyNdefMessage() {
        toast(getString(R.string.readEmptyMessage));
    }

    /**
     * 
     * Something was read via NFC, but it was not an NDEF message.
     * 
     * Handling this situation is out of scope of this project.
     * 
     */

    @Override
    protected void readNonNdefMessage() {
        toast(getString(R.string.readNonNDEFMessage));
    }

    // mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
    // if (mNfcAdapter == null) {
    // / nameTv = (TextView) findViewById(R.id.nameText);
    // nameTv.setText("NFC is not available on this device.");
    // capTv = (TextView) findViewById(R.id.capText);
    // capTv.setText("NFC is not available on this device.");
    // codeTv = (TextView) findViewById(R.id.codeText);
    // codeTv.setText("NFC is not available on this device.");
    // timeTv = (TextView) findViewById(R.id.timeEdit);
    // timeTv.setText("NFC is not available on this device.");
    // } else {
    // mNfcAdapter.setNdefPushMessageCallback(this, this);
    // mNfcAdapter.setOnNdefPushCompleteCallback(this, this);
    // }
    // }

    // @Override
    // public NdefMessage createNdefMessage(NfcEvent event) {

    // String a="\"";
    // String b="\"";

    // String message1 = a + ssidTv.getText().toString() +"," +
    // capTv.getText().toString()+b;
    // String message2 = nameTv.getText().toString();
    // String message3 = codeTv.getText().toString();
    // String message4 = timeTv.getText().toString();
    // byte[] textBytes1 = message1.getBytes();
    // byte[] textBytes2 = message2.getBytes();
    // byte[] textBytes3 = message3.getBytes();
    // byte[] textBytes4 = message4.getBytes();
    // NdefRecord textRecord1 = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
    // message1.getBytes(), new byte[] {}, textBytes1);
    // NdefRecord textRecord2 = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
    // message2.getBytes(), new byte[] {}, textBytes2);
    // NdefRecord textRecord3 = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
    // message3.getBytes(), new byte[] {}, textBytes3);
    // NdefRecord textRecord4 = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
    // message4.getBytes(), new byte[] {}, textBytes4);

    // NdefMessage msg = new NdefMessage(new NdefRecord[] {textRecord1,
    // textRecord2, textRecord3, textRecord4,
    // NdefRecord.createApplicationRecord("com.nfc.linked") });
    // return msg;

    // /**
    // * Implementation for the OnNdefPushCompleteCallback interface
    // */
    // @Override
    // public void onNdefPushComplete(NfcEvent arg0) {
    // mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
    // }

    // /** This handler receives a message from onNdefPushComplete */
    // private final Handler mHandler = new Handler() {
    // @Override
    // public void handleMessage(Message msg) {
    // switch (msg.what) {
    // case MESSAGE_SENT:
    // Toast.makeText(getApplicationContext(),
    // "Core Device Rules Sent!", Toast.LENGTH_LONG).show();
    // break;
    // }
    // }
    // };

    // @Override
    // public void onNewIntent(Intent intent) {

    // setIntent(intent);
    // }

    // void processIntent(Intent intent) {
    // Parcelable[] rawMsgs = intent
    // .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    // NdefMessage msg = (NdefMessage) rawMsgs[0];
    // nameTv.setText(new String(msg.getRecords()[0].getPayload()));
    // }

    @Override
    protected void onResume() {
        super.onResume();
        new LoadContacts().execute(rowID);
    }

    private class LoadContacts extends AsyncTask<Long, Object, Cursor> {
        DatabaseConnector dbConnector = new DatabaseConnector(Tap.this);

        @Override
        protected Cursor doInBackground(Long... params) {
            dbConnector.open();
            return dbConnector.getOneContact(params[0]);
        }

        @Override
        protected void onPostExecute(Cursor result) {
            super.onPostExecute(result);

            result.moveToFirst();
            int nameIndex = result.getColumnIndex("name");
            int capIndex = result.getColumnIndex("cap");
            int codeIndex = result.getColumnIndex("code");
            int timeIndex = result.getColumnIndex("time");
            int ssidIndex = result.getColumnIndex("ssid");

            nameTv.setText(result.getString(nameIndex));
            capTv.setText(result.getString(capIndex));
            timeTv.setText(result.getString(timeIndex));
            codeTv.setText(result.getString(codeIndex));
            ssidTv.setText(result.getString(ssidIndex));

            result.close();
            dbConnector.close();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.view_country_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.editItem:
            Intent addEditContact = new Intent(this, AddEditDevice.class);

            // addEditContact.putExtra(CountryList.ROW_ID, rowID);
            // addEditContact.putExtra("name", nameTv.getText());
            // addEditContact.putExtra("cap", capTv.getText());
            // addEditContact.putExtra("code", codeTv.getText());
            startActivity(addEditContact);
            return true;

        case R.id.user1SettingsSave:
            Intent Tap = new Intent(this, ViewCountry.class);
            startActivity(Tap);
            return true;

        case R.id.deleteItem:
            deleteContact();
            return true;

        default:
            return super.onOptionsItemSelected(item);
        }
    }

    private void deleteContact() {

        AlertDialog.Builder alert = new AlertDialog.Builder(Tap.this);

        alert.setTitle(R.string.confirmTitle);
        alert.setMessage(R.string.confirmMessage);

        alert.setPositiveButton(R.string.delete_btn,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int button) {
                        final DatabaseConnector dbConnector = new DatabaseConnector(
                                Tap.this);

                        AsyncTask<Long, Object, Object> deleteTask = new AsyncTask<Long, Object, Object>() {
                            @Override
                            protected Object doInBackground(Long... params) {
                                dbConnector.deleteContact(params[0]);
                                return null;
                            }

                            @Override
                            protected void onPostExecute(Object result) {
                                finish();
                            }
                        };

                        deleteTask.execute(new Long[] { rowID });
                    }
                });

        alert.setNegativeButton(R.string.cancel_btn, null).show();
    }

}

CountryList.java

public class CountryList extends ListActivity {

     public static final String ROW_ID = "row_id";
     private ListView conListView;
     private CursorAdapter conAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        conListView=getListView();
        conListView.setOnItemClickListener(viewConListener);

        // map each name to a TextView
        String[] from = new String[] { "name" };
        int[] to = new int[] { R.id.countryTextView };
        conAdapter = new SimpleCursorAdapter(CountryList.this, R.layout.country_list, null, from, to);
        setListAdapter(conAdapter); // set adapter
    }


    @Override
    protected void onResume() 
    {
       super.onResume();  
       new GetContacts().execute((Object[]) null);
     } 


    @Override
    protected void onStop() 
    {
       Cursor cursor = conAdapter.getCursor();

       if (cursor != null) 
          cursor.deactivate();

       conAdapter.changeCursor(null);
       super.onStop();
    }    


    private class GetContacts extends AsyncTask<Object, Object, Cursor> 
    {
       DatabaseConnector dbConnector = new DatabaseConnector(CountryList.this);

       @Override
       protected Cursor doInBackground(Object... params)
       {
          dbConnector.open();
          return dbConnector.getAllContacts(); 
       } 

       @Override
       protected void onPostExecute(Cursor result)
       {
          conAdapter.changeCursor(result); // set the adapter's Cursor
          dbConnector.close();
       } 
    } 

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
       super.onCreateOptionsMenu(menu);
       MenuInflater inflater = getMenuInflater();
       inflater.inflate(R.menu.country_menu, menu);
       return true;
    }   

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
       Intent addContact = new Intent(CountryList.this, AddEditDevice.class);
       startActivity(addContact);
       return super.onOptionsItemSelected(item);
    }

    OnItemClickListener viewConListener = new OnItemClickListener() 
    {
       public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) 
       {         
          Intent viewCon = new Intent(CountryList.this, ViewCountry.class);
          viewCon.putExtra(ROW_ID, arg3);
          startActivity(viewCon);
       }
    };    

}

logcat的:

04-16 13:37:22.415: E/AndroidRuntime(10285): FATAL EXCEPTION: main
04-16 13:37:22.415: E/AndroidRuntime(10285): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.wifi.demo/com.wifi.demowifi.demo.Tap}: java.lang.NullPointerException
04-16 13:37:22.415: E/AndroidRuntime(10285):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
04-16 13:37:22.415: E/AndroidRuntime(10285):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-16 13:37:22.415: E/AndroidRuntime(10285):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-16 13:37:22.415: E/AndroidRuntime(10285):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-16 13:37:22.415: E/AndroidRuntime(10285):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-16 13:37:22.415: E/AndroidRuntime(10285):    at android.os.Looper.loop(Looper.java:137)
04-16 13:37:22.415: E/AndroidRuntime(10285):    at android.app.ActivityThread.main(ActivityThread.java:5041)
04-16 13:37:22.415: E/AndroidRuntime(10285):    at java.lang.reflect.Method.invokeNative(Native Method)
04-16 13:37:22.415: E/AndroidRuntime(10285):    at java.lang.reflect.Method.invoke(Method.java:511)
04-16 13:37:22.415: E/AndroidRuntime(10285):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-16 13:37:22.415: E/AndroidRuntime(10285):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-16 13:37:22.415: E/AndroidRuntime(10285):    at dalvik.system.NativeStart.main(Native Method)
04-16 13:37:22.415: E/AndroidRuntime(10285): Caused by: java.lang.NullPointerException
04-16 13:37:22.415: E/AndroidRuntime(10285):    at com.wifi.demo.Tap.onCreate(Tap.java:75)
04-16 13:37:22.415: E/AndroidRuntime(10285):    at android.app.Activity.performCreate(Activity.java:5104)
04-16 13:37:22.415: E/AndroidRuntime(10285):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-16 13:37:22.415: E/AndroidRuntime(10285):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
04-16 13:37:22.415: E/AndroidRuntime(10285):    ... 11 more
04-16 13:37:25.315: D/libEGL(10339): loaded /system/lib/egl/libEGL_tegra.so
04-16 13:37:25.345: D/libEGL(10339): loaded /system/lib/egl/libGLESv1_CM_tegra.so
04-16 13:37:25.355: D/libEGL(10339): loaded /system/lib/egl/libGLESv2_tegra.so
04-16 13:37:25.385: D/OpenGLRenderer(10339): Enabling debug mode 0

1 个答案:

答案 0 :(得分:0)

似乎当你开始第二项活动时,你没有通过你的意图传递任何数据

为了使其更清晰,您必须执行与调用“ViewCountry”时相同的操作

  Intent viewCon = new Intent(CountryList.this, ViewCountry.class);
  viewCon.putExtra(ROW_ID, arg3);
  startActivity(viewCon);