2014-11-23 113 views
0

即時創建一個nfc閱讀器。
我跟着教程,它工作得很好。
結果將顯示nfc標記中的值,例如;文本框中的123456。
我該如何改變放置在Editview中的結果?
我已經嘗試,但仍然,不幸。
MainActivity.java
把Texview價值放入Editext

package net.vrallev.android.nfc.demo; 

import java.io.UnsupportedEncodingException; 
import java.util.Arrays; 

import android.app.Activity; 
import android.app.PendingIntent; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.content.IntentFilter.MalformedMimeTypeException; 
import android.nfc.NdefMessage; 
import android.nfc.NdefRecord; 
import android.nfc.NfcAdapter; 
import android.nfc.Tag; 
import android.nfc.tech.Ndef; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.TextView; 
import android.widget.Toast; 

/** 
* Activity for reading data from an NDEF Tag. 
* 
* @author Ralf Wondratschek 
* 
*/ 
public class MainActivity extends Activity { 

public static final String MIME_TEXT_PLAIN = "text/plain"; 
public static final String TAG = "NfcDemo"; 

private TextView mTextView; 
private NfcAdapter mNfcAdapter; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    mTextView = (TextView) findViewById(R.id.textView_explanation); 

    mNfcAdapter = NfcAdapter.getDefaultAdapter(this); 

    if (mNfcAdapter == null) { 
     // Stop here, we definitely need NFC 
     Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show(); 
     finish(); 
     return; 

    } 

    if (!mNfcAdapter.isEnabled()) { 
     mTextView.setText("NFC is disabled."); 
    } else { 
     mTextView.setText(R.string.explanation); 
    } 

    handleIntent(getIntent()); 
} 

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

    /* 
    * It's important, that the activity is in the foreground (resumed). Otherwise 
    * an IllegalStateException is thrown. 
    */ 
    setupForegroundDispatch(this, mNfcAdapter); 
} 

@Override 
protected void onPause() { 
    /* 
    * Call this before onPause, otherwise an IllegalArgumentException is thrown as well. 
    */ 
    stopForegroundDispatch(this, mNfcAdapter); 

    super.onPause(); 
} 

@Override 
protected void onNewIntent(Intent intent) { 
    /* 
    * This method gets called, when a new Intent gets associated with the current activity  instance. 
    * Instead of creating a new activity, onNewIntent will be called. For more information have a look 
    * at the documentation. 
    * 
    * In our case this method gets called, when the user attaches a Tag to the device. 
    */ 
    handleIntent(intent); 
} 

private void handleIntent(Intent intent) { 
    String action = intent.getAction(); 
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { 

     String type = intent.getType(); 
     if (MIME_TEXT_PLAIN.equals(type)) { 

      Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); 
      new NdefReaderTask().execute(tag); 

     } else { 
      Log.d(TAG, "Wrong mime type: " + type); 
     } 
    } else if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) { 

     // In case we would still use the Tech Discovered Intent 
     Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); 
     String[] techList = tag.getTechList(); 
     String searchedTech = Ndef.class.getName(); 

     for (String tech : techList) { 
      if (searchedTech.equals(tech)) { 
       new NdefReaderTask().execute(tag); 
       break; 
      } 
     } 
    } 
} 

/** 
* @param activity The corresponding {@link Activity} requesting the foreground dispatch. 
* @param adapter The {@link NfcAdapter} used for the foreground dispatch. 
*/ 
public static void setupForegroundDispatch(final Activity activity, NfcAdapter adapter) { 
    final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass()); 
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); 

    final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0); 

    IntentFilter[] filters = new IntentFilter[1]; 
    String[][] techList = new String[][]{}; 

    // Notice that this is the same filter as in our manifest. 
    filters[0] = new IntentFilter(); 
    filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED); 
    filters[0].addCategory(Intent.CATEGORY_DEFAULT); 
    try { 
     filters[0].addDataType(MIME_TEXT_PLAIN); 
    } catch (MalformedMimeTypeException e) { 
     throw new RuntimeException("Check your mime type."); 
    } 

    adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList); 
} 

/** 
* @param activity The corresponding {@link BaseActivity} requesting to stop the foreground dispatch. 
* @param adapter The {@link NfcAdapter} used for the foreground dispatch. 
*/ 
public static void stopForegroundDispatch(final Activity activity, NfcAdapter adapter) { 
    adapter.disableForegroundDispatch(activity); 
} 

/** 
* Background task for reading the data. Do not block the UI thread while reading. 
* 
* @author Ralf Wondratschek 
* 
*/ 
private class NdefReaderTask extends AsyncTask<Tag, Void, String> { 

    @Override 
    protected String doInBackground(Tag... params) { 
     Tag tag = params[0]; 

     Ndef ndef = Ndef.get(tag); 
     if (ndef == null) { 
      // NDEF is not supported by this Tag. 
      return null; 
     } 

     NdefMessage ndefMessage = ndef.getCachedNdefMessage(); 

     NdefRecord[] records = ndefMessage.getRecords(); 
     for (NdefRecord ndefRecord : records) { 
      if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) { 
       try { 
        return readText(ndefRecord); 
       } catch (UnsupportedEncodingException e) { 
        Log.e(TAG, "Unsupported Encoding", e); 
       } 
      } 
     } 

     return null; 
    } 

    private String readText(NdefRecord record) throws UnsupportedEncodingException { 
     /* 
     * See NFC forum specification for "Text Record Type Definition" at 3.2.1 
     * 
     * http://www.nfc-forum.org/specs/ 
     * 
     * bit_7 defines encoding 
     * bit_6 reserved for future use, must be 0 
     * bit_5..0 length of IANA language code 
     */ 

     byte[] payload = record.getPayload(); 

     // Get the Text Encoding 
     String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; 

     // Get the Language Code 
     int languageCodeLength = payload[0] & 0063; 

     // String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII"); 
     // e.g. "en" 

     // Get the Text 
     return new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding); 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     if (result != null) { 
      mTextView.setText("Read content: " + result); 
     } 
    } 
} 
} 

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context=".MainActivity" > 

<TextView 
    android:id="@+id/textView_explanation" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/explanation" /> 

</RelativeLayout> 

AndroidManifest.xml中

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="net.vrallev.android.nfc.demo" 
android:versionCode="1" 
android:versionName="1.0" > 

<uses-permission android:name="android.permission.NFC" /> 

<uses-feature 
    android:name="android.hardware.nfc" 
    android:required="true" /> 

<uses-sdk 
    android:minSdkVersion="10" 
    android:targetSdkVersion="17" /> 

<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
     android:name="net.vrallev.android.nfc.demo.MainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
     <intent-filter> 
      <action android:name="android.nfc.action.NDEF_DISCOVERED" /> 

      <category android:name="android.intent.category.DEFAULT" /> 

      <data android:mimeType="text/plain" /> 
     </intent-filter> 
    </activity> 
</application> 

</manifest> 
+0

哪裏的EditText?你試圖把它放到edittext中嗎? – 2014-11-23 06:45:37

+0

創建一個字符串名稱str,併爲其分配textview.text並設置editText.setText(x) – Nepster 2014-11-23 07:05:39

+0

@Indra是的我知道在XML中沒有edittext,如果沒有可用的edittext,我會盡最大努力獲得幫助代碼,這樣我就可以獲得az教程。我嘗試把nfc的文字。 – 2014-11-26 17:42:47

回答

0

添加EditText到您的佈局:

<EditText 
    android:id="@+id/editText1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" /> 

現在這個代碼添加到MainActivity類:在你的XML

... 

public class MainActivity extends Activity { 

public static final String MIME_TEXT_PLAIN = "text/plain"; 
public static final String TAG = "NfcDemo"; 

private TextView mTextView; 
private NfcAdapter mNfcAdapter; 
private EditText mEditText; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    mTextView = (TextView) findViewById(R.id.textView_explanation); 
    mEditText = (EditText) findViewById(R.id.editText1); 

    //Set Text View value in Edit Text 
    mEditText.setText(mTextView.getText().toString()); 

    ... 
} 


... 
+0

我哭了,非常感謝你,工作! – 2014-11-26 17:46:08

0

唯一的變化,你應該需要聲明的解釋字段作爲一個EditText中你的XML:

<EditText 
    android:id="@+id/textView_explanation" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/explanation" /> 

由於EditText的子類TextView,你甚至不需要修改你的代碼,除非你想調用一個只在EditText中的函數。

這是你遇到的問題,還是我誤解了?

+0

謝謝你的回覆。是的,我想在edittext中調用一個函數。 – 2014-11-26 17:45:22