java - TextView 类型未定义方法 getBytes()

标签 java android eclipse nfc

我正在尝试使用以下示例将多个记录添加到一个 NDefMessage 但是当我尝试这样做时 - 我收到一条错误消息,指出“方法 getBytes() 未定义类型 TextView"

例子: example

来源:

public class ViewCountry extends Activity implements CreateNdefMessageCallback,
            OnNdefPushCompleteCallback {
    NfcAdapter mNfcAdapter;
   // TextView timeTv;
       private static final int MESSAGE_SENT = 1;
       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);

          nameTv = (TextView) findViewById(R.id.nameText);
            // Check for available NFC Adapter
            mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
            if (mNfcAdapter == null) {
                nameTv = (TextView) findViewById(R.id.nameText);
                nameTv.setText("NFC is not available on this device.");
                timeTv = (TextView) findViewById(R.id.timeEdit);
                timeTv.setText("NFC is not available on this device.");
            } else {
                // Register callback to set NDEF message
                mNfcAdapter.setNdefPushMessageCallback(this, this);
                // Register callback to listen for message-sent success
                mNfcAdapter.setOnNdefPushCompleteCallback(this, this);
            }
        }


       @Override
        public NdefMessage createNdefMessage(NfcEvent event) {
           String message1 = nameTv.getText().toString();
            String message2 = timeTv.getText().toString();
            byte[] textBytes1 = nameTv.getBytes();
            byte[] textBytes2 = timeTv.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);


           //   String text = ("SSID");

            NdefMessage msg = new NdefMessage(
                    new NdefRecord[]{
                            textRecord1,
                            textRecord2,                
                            NdefRecord.createApplicationRecord("com.nfc.linked")


                    }
                     */
                     //,NdefRecord.createApplicationRecord("com.nfc.linked")
                   );
                   return msg;
               }


        /**
         * Implementation for the OnNdefPushCompleteCallback interface
         */
        @Override
        public void onNdefPushComplete(NfcEvent arg0) {
            // A handler is needed to send messages to the activity when this
            // callback occurs, because it happens from a binder thread
            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) {
            // onResume gets called after this to handle the intent
            setIntent(intent);
        }



        /**
         * Parses the NDEF Message from the intent and prints to the TextView
         */
        void processIntent(Intent intent) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
                    NfcAdapter.EXTRA_NDEF_MESSAGES);
            // only one message sent during the beam
            NdefMessage msg = (NdefMessage) rawMsgs[0];
            // record 0 contains the MIME type, record 1 is the AAR, if present
            nameTv.setText(new String(msg.getRecords()[0].getPayload()));
        }




        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // If NFC is not available, we won't be needing this menu
            if (mNfcAdapter == null) {
                return super.onCreateOptionsMenu(menu);
            }
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.options, menu);
            return true;
        }



        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.menu_settings:
                    Intent intent = new Intent(Settings.ACTION_NFCSHARING_SETTINGS);
                    startActivity(intent);
                    return true;
                default:
                    return super.onOptionsItemSelected(item);
            }



        }




       @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.getString(timeIndex)); 
             codeTv.setText(result.getString(codeIndex));

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


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

    }

最佳答案

The method getBytes() is undefined for the type TextView

Simply TextView(as object) 不提供getBytes() 方法。但是如果你想将 TextView 的内容转换为字节数组,你需要先获取 TextView 的内容,然后你可以使用 getBytes()

byte[] arr = nameTv.getText().toString().getBytes();

注意:如果要将整个对象转换为字节数组,可以使用

示例:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream writter = new ObjectOutputStream(baos);
writter.writeObject(<yourObject>);
byte[] arr = baos.toByteArray();

关于java - TextView 类型未定义方法 getBytes(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15742956/

相关文章:

android - 检查权限并重新加载 Activity

java - 当调试器完成应用程序时,如何使 Eclipse 自动跳回开发视角?

java - Egit : Set gitignore to ignore all eclipse project files

java餐厅地址显示不正确

java - 从字符串中删除日期后从文件名中提取字符串

java - 处理程序的 `handleMessage` 返回主线程的线程 ID 而不是工作线程的线程 ID

android - 从android中的html5视频标签运行视频

android - 用于 Eclipse 和 Android 开发的 Mercurial 忽略文件

java - 在没有 HotSpotDiagnosticMXBean 的情况下从应用程序内部创建堆转储

java - ProgressMonitorInputStream - 进度条不显示真实进度