使用字符串/资源而不是静态/不可更改的文本

时间:2013-03-31 18:31:06

标签: java android nfc ndef

我正在尝试使用我在应用中常用的字符串而不是文本来编写NDef消息。

示例:

@Override
    public NdefMessage createNdefMessage(NfcEvent event) {
        Time time = new Time();
        time.setToNow();
        String text = ("Beam me up!\n\n" +
                "Beam Time: " + time.format("%H:%M:%S"));
        NdefMessage msg = new NdefMessage(NdefRecord.createMime(
                "application/com.nfc.linkingmanager.beam", text.getBytes())
         /**

我想写下:

的值
android:id="@+id/timeEdit

而不是:

Beam me up!\n\n" +
                "Beam Time: " + time.format("%H:%M:%S"

VIEWCOUNTRY.JAVA(另一个能够引用我正在寻找的值的Java类:timeEdit)

public class ViewCountry extends Activity {

       private long rowID;
       private TextView nameTv;
       private TextView capTv;
       private TextView codeTv; 
       private TextView timeTv; 

       @Override
       public void onCreate(Bundle savedInstanceState) 
       {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.view_country);

          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);
       }

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

       private class LoadContacts extends AsyncTask<Long, Object, Cursor> 
       {
          DatabaseConnector dbConnector = new DatabaseConnector(ViewCountry.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();
             // get the column index for each data item
             int nameIndex = result.getColumnIndex("name");
             int capIndex = result.getColumnIndex("cap");
             int codeIndex = result.getColumnIndex("code");
             int timeIndex = result.getColumnIndex("time");

             nameTv.setText(result.getString(nameIndex));
             capTv.setText(result.getString(capIndex));
//           timeTv.setText(result.getInt(timeIndex)); // <--- HERE WAS AN ERROR
             timeTv.setText(result.getString(timeIndex)); // time was stored as Sting all the time
             codeTv.setText(result.getString(codeIndex));

             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.deleteItem:
                deleteContact();
                return true;

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

       private void deleteContact()
       {

          AlertDialog.Builder alert = new AlertDialog.Builder(ViewCountry.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(ViewCountry.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();
       }
    }

1 个答案:

答案 0 :(得分:0)

您没有在代码中显示使用此方法的位置,因此它可能比这更复杂,但一般来说:

public MyActivity extends Activity{

    ...
    private final TextView tvTimeStamp;   //  <--- declare it, it's class level so is available to all methods of this class
    ...

    @Override
    public void onCreate(Bundle savedInstance){

        super.onCreate(savedInstance);

        ...

        setContentView(R.layout.my_activity_layout);

        tvTimeStamp = (TextView)findViewById(R.id.timeEdit);  // <---- get a reference to it

        ...

    }

    @Override
    public NdefMessage createNdefMessage(NfcEvent event) {
        Time time = new Time();
        time.setToNow();
        String text = ("Beam me up!\n\n" +
                "Beam Time: " + time.format("%H:%M:%S"));
        NdefMessage msg = new NdefMessage(NdefRecord.createMime(
                tvTimeStamp.getText(), text.getBytes())  // <----- use it here!


   }

}

要在另一个类中获取TextView的值,您可以使用以下技术:

一个:通过添加构造函数,将TextView的值传递给构建NFC消息的类,例如

public class MyNfcClass{

    private String timeStamp;

    public void MyNfcClass(String timeStamp){
        this.timeStamp = timeStamp;
    }
}

这样做的缺点是,如果TextView发生变化,您的NFC类将无法知道。

两个:定义一个接口。请参阅本教程http://www.tutorialspoint.com/java/java_interfaces.htm

:当且仅当NFC类的生命周期等于或小于Activity的生命周期时,才将对TextView的引用传递给类。只有这样才能真正了解生命周期,并且您可以保证不会泄漏参考。如果你不明白这一点,那就认为它是verboten;)

:如果Nfc类在另一个Activity中实例化,从另一个Activity(或活动链中的某个地方)开始,则传递用于启动Activity的Intent extras中的值。与选项1相同的缺点。

总之,选项2是首选。这是Java和Android的“方式”。

祝你好运。