簡體   English   中英

NFC 僅在活動是啟動器時才有效。否則它根本不會檢測到意圖

[英]NFC only works when the activity is launcher.Else it does not detect the intent at all

但是,我只嘗試在我的應用程序具有啟動器屬性時,活動才會檢測到 NFC 意圖。 即使我在另一個應用程序中有一個意圖過濾器。 這是我的清單和兩個活動。 我什至管理了前台調度。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.melin.vustudentattendence">

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".AddStudentsActivity"></activity>
        <activity android:name=".AddClassesActivity" />
        <activity android:name=".AddTeachersActivity" />
        <activity android:name=".TestActivity">
            
                 <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>
            <intent-filter>
                <action android:name="android.nfc.action.TECH_DISCOVERED" />
            </intent-filter>

            <meta-data
                android:name="android.nfc.action.TECH_DISCOVERED"
                android:resource="@xml/nfc_tech_filter" />
        </activity>
        <activity android:name=".ClassAttendenceActivity">



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

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

                <data android:mimeType="text/plain" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.nfc.action.TECH_DISCOVERED" />
            </intent-filter>

            <meta-data
                android:name="android.nfc.action.TECH_DISCOVERED"
                android:resource="@xml/nfc_tech_filter" />
        </activity>
        <activity
            android:name=".LecutererClassesListActivity"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity android:name=".InstituteDashboardActivity" />
        <activity android:name=".TodaysClassesActivity" />
        <activity
            android:name=".LecturerDashboardActivity"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".LoginActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

這是我的 TestActivity.java

package com.melin.vustudentattendence;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.ClipDescription;
import android.content.Intent;
import android.content.IntentFilter;
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;

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

public class TestActivity extends AppCompatActivity {

    public static final String TAG="NFCDemo";

    private TextView mTextView;
    private NfcAdapter mNfcAdapter;


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



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

        mTextView=(TextView)findViewById(R.id.textView_explanation);
        mNfcAdapter= NfcAdapter.getDefaultAdapter(this);
        if(mNfcAdapter==null){
            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();
        setupForegroundDispatch(this, mNfcAdapter);
    }

    @Override
    protected void onPause() {
        stopForegroundDispatch(this,mNfcAdapter);
        super.onPause();
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
    }

    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(ClipDescription.MIMETYPE_TEXT_PLAIN);
        } catch (IntentFilter.MalformedMimeTypeException e) {
            throw new RuntimeException("Check your mime type.");
        }

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

    public static void stopForegroundDispatch(final Activity activity, NfcAdapter adapter) {
        adapter.disableForegroundDispatch(activity);
    }


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

            String type = intent.getType();
            if (ClipDescription.MIMETYPE_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;
                }
            }
        }
    }


}

這是我的 ClassesAttendenceActivity

package com.melin.vustudentattendence;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.ClipDescription;
import android.content.Intent;
import android.content.IntentFilter;
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.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class ClassAttendenceActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private  ClassAttendenceRowAdapter adapter;
    private List<Student> students=new ArrayList<>();
    private FirebaseFirestore fs;
    private String incomingIntentData;
    private NfcAdapter mNfcAdapter;
    private static String TAG="Attendence Activity";

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


        //check nfc first
        mNfcAdapter=NfcAdapter.getDefaultAdapter(this);
        if(mNfcAdapter==null){
            Toast.makeText(this,"This device doesn't support NFC",Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        if(!mNfcAdapter.isEnabled()){
            Toast.makeText(this,"NFC is disabled.Please enable it",Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(this, "NFC is in reader mode", Toast.LENGTH_SHORT).show();
        }
        //incomingIntentData=getIntent().getExtras().getString("document");
        //fs=FirebaseFirestore.getInstance();
        //Toast.makeText(this,incomingIntentData,Toast.LENGTH_LONG).show();
        //recyclerView=(RecyclerView)findViewById(R.id.attendenceListRecyclerView);
//        LinearLayoutManager layoutManager=new LinearLayoutManager(ClassAttendenceActivity.this);
//        recyclerView.setLayoutManager(layoutManager);
//        populateStudentList(incomingIntentData);
        handleIntent(getIntent());
    }

    private void populateStudentList(String url){
        fs.collection(url+"/students")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                Map<String,Object> data=document.getData();
                                Student student=new Student();
                                student.setStatus("ABSENT");
                                for (Map.Entry<String,Object> entry : data.entrySet()){
                                    if(entry.getKey().equals("name")){
                                        student.setName(entry.getValue().toString());
                                    }
                                    if(entry.getKey().equals("student_id")){
                                        student.setStudent_id(entry.getValue().toString());
                                    }
                                }
                                students.add(student);
                                Log.d("List", document.getId() + " => " + document.getData());
                            }
                        } else {
                            Log.d("List", "Error getting documents: ", task.getException());
                        }

                        adapter=new ClassAttendenceRowAdapter(students);
                        recyclerView.setAdapter(adapter);

                    }


                });

    }

    public void simulatingAnIntent(){
        String student_id="101";
        for(Student student:students){
            if(student.getStudent_id().equals(student_id)){
                student.setStatus("PRESENT");
                Toast.makeText(ClassAttendenceActivity.this,"Student ID"+student.getStudent_id()+"Detected",Toast.LENGTH_LONG).show();
            }
        }

        adapter=new ClassAttendenceRowAdapter(students);
        recyclerView.setAdapter(adapter);
    }


    @Override
    protected void onResume() {
        super.onResume();
        setupForegroundDispatch(this, mNfcAdapter);
    }

    @Override
    protected void onPause() {
        stopForegroundDispatch(this,mNfcAdapter);
        super.onPause();
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
    }

    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(ClipDescription.MIMETYPE_TEXT_PLAIN);
        } catch (IntentFilter.MalformedMimeTypeException e) {
            throw new RuntimeException("Check your mime type.");
        }

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

    public static void stopForegroundDispatch(final Activity activity, NfcAdapter adapter) {
        adapter.disableForegroundDispatch(activity);
    }


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

            String type = intent.getType();
            if (ClipDescription.MIMETYPE_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;
                }
            }
        }
    }


    public 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) {

                Toast.makeText(ClassAttendenceActivity.this,"Student ID"+result+"Detected",Toast.LENGTH_LONG).show();

//                for(Student student:students){
//                    if(student.getStudent_id().equals(result)){
//                        student.setStatus("PRESENT");
//                        Toast.makeText(ClassAttendenceActivity.this,"Student ID"+student.getStudent_id()+"Detected",Toast.LENGTH_LONG).show();
//                    }
//                }
//
//                adapter=new ClassAttendenceRowAdapter(students);
//                recyclerView.setAdapter(adapter);
            }
        }
    }
}

正如您所看到的,這兩個活動幾乎相同,而一個讀取數據,另一個則不讀取

事實證明,使用模擬 nfc 標簽是錯誤的。使用真正的 nfc 標簽效果很好。雖然沒有人回答這個問題,但我正在回答我自己的問題,以便當有人遇到這個問題時,他們可以看到這個答案。謝謝。

Activity 沒有收到 List<object> 用 Intent 發送時<div id="text_translate"><p>我目前正在努力發送一個包含一個列表的 Object 的意圖。 基本上我可以將正確的數據發送到另一個活動,但我無法在數據中獲取列表。 對不起,我真的不知道怎么形容。</p><p> 問題是,我可以通過調用例如recipes.get(0).getIngredients()來獲取 RecipeActivity 中的成分,但在 RecipeDetailsActivity 中由於列表為空而出現錯誤。 (而且我也不知道如何在 DetailsActivity 中獲得 object 的正確索引)</p><p> 提前致謝!</p><p> <strong>配方.java</strong></p><pre> public class Recipe implements Parcelable { @SerializedName("id") @Expose private Integer mId; @SerializedName("name") @Expose private String mName; @SerializedName("ingredients") @Expose private List &lt; Ingredient &gt; mIngredients = null; @SerializedName("steps") @Expose private List &lt; Step &gt; mSteps = null; @SerializedName("servings") @Expose private Integer mServings; @SerializedName("image") @Expose private String mImage; protected Recipe(Parcel in ) { if ( in.readByte() == 0) { mId = null; } else { mId = in.readInt(); } mName = in.readString(); if ( in.readByte() == 0) { mServings = null; } else { mServings = in.readInt(); } mImage = in.readString(); } public static final Creator &lt; Recipe &gt; CREATOR = new Creator &lt; Recipe &gt; () { @Override public Recipe createFromParcel(Parcel in ) { return new Recipe( in ); } @Override public Recipe[] newArray(int size) { return new Recipe[size]; } }; public Integer getId() { return mId; } public void setId(Integer id) { mId = id; } public String getName() { return mName; } public void setName(String name) { mName = name; } public List &lt; Ingredient &gt; getIngredients() { return mIngredients; } public void setIngredients(List &lt; Ingredient &gt; ingredients) { mIngredients = ingredients; } public List &lt; Step &gt; getSteps() { return mSteps; } public void setSteps(List &lt; Step &gt; steps) { mSteps = steps; } public Integer getServings() { return mServings; } public void setServings(Integer servings) { mServings = servings; } public String getImage() { return mImage; } public void setImage(String image) { mImage = image; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { if (mId == null) { dest.writeByte((byte) 0); } else { dest.writeByte((byte) 1); dest.writeInt(mId); } dest.writeString(mName); if (mServings == null) { dest.writeByte((byte) 0); } else { dest.writeByte((byte) 1); dest.writeInt(mServings); } dest.writeString(mImage); } }</pre><p> <strong>成分.java</strong></p><pre> public class Ingredient { @SerializedName("quantity") @Expose private Double mQuantity; @SerializedName("measure") @Expose private String mMeasure; @SerializedName("ingredient") @Expose private String mIngredient; public Double getQuantity() { return mQuantity; } public void setQuantity(Double quantity) { mQuantity = quantity; } public String getMeasure() { return mMeasure; } public void setMeasure(String measure) { mMeasure = measure; } public String getIngredient() { return mIngredient; } public void setIngredient(String ingredient) { mIngredient = ingredient; } } RecipeActivity public class RecipeActivity extends AppCompatActivity implements RecipeAdapter.RecipeAdapterOnClickHandler { private static final String TAG = RecipeActivity.class.getSimpleName(); @BindView(R.id.recipe_recycler_view) RecyclerView mRecyclerView; private RecipeAdapter mRecipeAdapter; private List &lt; Recipe &gt; recipes; public static final String MY_RECIPE = "myRecipe"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recipe); RecipeService service = RecipeClient.getRetrofit().create(RecipeService.class); Call &lt; List &lt; Recipe &gt;&gt; call = service.getAllRecipes(); call.enqueue(new Callback &lt; List &lt; Recipe &gt;&gt; () { @Override public void onResponse(Call &lt; List &lt; Recipe &gt;&gt; call, Response &lt; List &lt; Recipe &gt;&gt; response) { if (response.isSuccessful()) { recipes = response.body(); generateDataList(recipes); } } @Override public void onFailure(Call &lt; List &lt; Recipe &gt;&gt; call, Throwable t) { Toast.makeText(RecipeActivity.this, "Something went wrong...Please try later,". Toast.LENGTH_SHORT);show(). Log,v(TAG. t;toString()); } }). } private void generateDataList(List &lt; Recipe &gt; recipeList) { ButterKnife;bind(this), mRecipeAdapter = new RecipeAdapter(this, recipeList. RecipeActivity;this). RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(RecipeActivity;this). mRecyclerView;setLayoutManager(layoutManager). mRecyclerView;setAdapter(mRecipeAdapter); } @Override public void onClick(int adapterPosition) { Context context = this. Class detailClass = RecipeDetailsActivity;class, Intent detailsIntent = new Intent(context; detailClass). detailsIntent,putExtra(MY_RECIPE. recipes;get(adapterPosition)); startActivity(detailsIntent); } }</pre><p> <strong>食譜詳情活動</strong></p><pre>public class RecipeDetailsActivity extends AppCompatActivity implements IngredientAdapter.IngredientAdapterOnClickHandler { private static final String TAG = RecipeDetailsActivity.class.getSimpleName(); private Recipe recipes; private List &lt; Recipe &gt; recipeList; private String recipeName; private String ingredient; private Double quantity; private String measure; private List &lt; Ingredient &gt; ingredientList = new ArrayList &lt; &gt; (); IngredientAdapter mAdapter; @Nullable @BindView(R.id.ingredients) TextView ingredientsTV; @Nullable @BindView(R.id.quantity) TextView quantityTV; @BindView(R.id.recipe_details_rv) RecyclerView mRecyclerView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recipe_details); Intent intentToCatch = getIntent(); recipes = intentToCatch.getParcelableExtra(RecipeActivity.MY_RECIPE); recipeName = recipes.getName(); ingredientList = recipes.getIngredients(); if (ingredientList.= null) { ingredient = ingredientList.get(0);getIngredient(). quantity = ingredientList.get(0);getQuantity(). measure = ingredientList.get(0);getMeasure(). } else { Log,v(TAG; "FAILING LOADING INGREDIENTSLIST"); } setTitle(recipeName). ButterKnife;bind(this), mAdapter = new IngredientAdapter(this, ingredientList. RecipeDetailsActivity;this). RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(RecipeDetailsActivity;this). mRecyclerView;setLayoutManager(layoutManager). mRecyclerView;setAdapter(mAdapter). } @Override public void onClick(int adapterPosition) { } } RecipeAdapter public class RecipeAdapter extends RecyclerView.Adapter &lt; RecipeAdapter;RecipeAdapterViewHolder &gt; { private List &lt; Recipe &gt; mRecipeList; private Context mContext; private RecipeAdapterOnClickHandler mOnClickHandler, public RecipeAdapter(Context context, List &lt; Recipe &gt; recipeList; RecipeAdapterOnClickHandler onClickHandler) { mContext = context; mRecipeList = recipeList; mOnClickHandler = onClickHandler; } public interface RecipeAdapterOnClickHandler { void onClick(int adapterPosition). } public class RecipeAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { @BindView(R.id;recipe_name) TextView mRecipeName; public RecipeAdapterViewHolder(@NonNull View itemView) { super(itemView). itemView;setOnClickListener(this). ButterKnife,bind(this; itemView); } @Override public void onClick(View v) { int adapterPosition = getAdapterPosition(). mOnClickHandler;onClick(adapterPosition), } } @NonNull @Override public RecipeAdapterViewHolder onCreateViewHolder(@NonNull ViewGroup parent. int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent;getContext()). View view = layoutInflater.inflate(R.layout,recipe_list_item, parent; false); return new RecipeAdapterViewHolder(view), } @Override public void onBindViewHolder(@NonNull RecipeAdapterViewHolder holder. int position) { holder.mRecipeName.setText(mRecipeList.get(position);getName()); } @Override public int getItemCount() { if (mRecipeList == null) { return 0. } return mRecipeList;size(); } }</pre><p> <strong>成分適配器</strong></p><pre>public class IngredientAdapter extends RecyclerView.Adapter &lt; IngredientAdapter.IngredientAdapterViewHolder &gt; { private List &lt; Ingredient &gt; mIngredient; private Context mContext; private IngredientAdapterOnClickHandler mOnClickHandler; public IngredientAdapter(Context context, List &lt; Ingredient &gt; ingredientList, IngredientAdapterOnClickHandler onClickHandler) { mContext = context; mIngredient = ingredientList; mOnClickHandler = onClickHandler; } public interface IngredientAdapterOnClickHandler { void onClick(int adapterPosition); } public class IngredientAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { @BindView(R.id.ingredients) TextView ingredientTextView; @BindView(R.id.step_description) TextView stepsDescriptionTextView; @BindView(R.id.quantity) TextView quantityDescriptionTextView; public IngredientAdapterViewHolder(@NonNull View itemView) { super(itemView); ButterKnife.bind(this, itemView); } @Override public void onClick(View v) { int adapterPosition = getAdapterPosition(); mOnClickHandler.onClick(adapterPosition); } } @NonNull @Override public IngredientAdapterViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); View view = layoutInflater.inflate(R.layout.recipe_details_list_item, parent, false); return new IngredientAdapterViewHolder(view); } @Override public void onBindViewHolder(@NonNull IngredientAdapterViewHolder holder, int position) { holder.ingredientTextView.setText(mIngredient.get(position).getIngredient()); holder.stepsDescriptionTextView.setText(mIngredient.get(position).getQuantity().toString()); holder.quantityDescriptionTextView.setText(mIngredient.get(position).getMeasure()); } @Override public int getItemCount() { if (mIngredient == null) { return 0; } return mIngredient.size(); } }</pre></div></object>

[英]Activity does not receive List<Object> when sending it with Intent

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

相關問題 啟動器活動的默認意圖 Android活動僅在被聲明為主活動和啟動器活動時才有效 NFC 標簽讀取活動未收到意圖 用於非啟動活動的Android意向過濾器 只檢測nfc對某一個position的代碼 來自不同程序包的啟動器的活動意圖過濾器操作名稱 這是什么意思“找不到啟動器活動! 並且啟動只會同步設備上的應用程序包!“ 在其他情況下,意圖不起作用 Activity 沒有收到 List<object> 用 Intent 發送時<div id="text_translate"><p>我目前正在努力發送一個包含一個列表的 Object 的意圖。 基本上我可以將正確的數據發送到另一個活動,但我無法在數據中獲取列表。 對不起,我真的不知道怎么形容。</p><p> 問題是,我可以通過調用例如recipes.get(0).getIngredients()來獲取 RecipeActivity 中的成分,但在 RecipeDetailsActivity 中由於列表為空而出現錯誤。 (而且我也不知道如何在 DetailsActivity 中獲得 object 的正確索引)</p><p> 提前致謝!</p><p> <strong>配方.java</strong></p><pre> public class Recipe implements Parcelable { @SerializedName("id") @Expose private Integer mId; @SerializedName("name") @Expose private String mName; @SerializedName("ingredients") @Expose private List &lt; Ingredient &gt; mIngredients = null; @SerializedName("steps") @Expose private List &lt; Step &gt; mSteps = null; @SerializedName("servings") @Expose private Integer mServings; @SerializedName("image") @Expose private String mImage; protected Recipe(Parcel in ) { if ( in.readByte() == 0) { mId = null; } else { mId = in.readInt(); } mName = in.readString(); if ( in.readByte() == 0) { mServings = null; } else { mServings = in.readInt(); } mImage = in.readString(); } public static final Creator &lt; Recipe &gt; CREATOR = new Creator &lt; Recipe &gt; () { @Override public Recipe createFromParcel(Parcel in ) { return new Recipe( in ); } @Override public Recipe[] newArray(int size) { return new Recipe[size]; } }; public Integer getId() { return mId; } public void setId(Integer id) { mId = id; } public String getName() { return mName; } public void setName(String name) { mName = name; } public List &lt; Ingredient &gt; getIngredients() { return mIngredients; } public void setIngredients(List &lt; Ingredient &gt; ingredients) { mIngredients = ingredients; } public List &lt; Step &gt; getSteps() { return mSteps; } public void setSteps(List &lt; Step &gt; steps) { mSteps = steps; } public Integer getServings() { return mServings; } public void setServings(Integer servings) { mServings = servings; } public String getImage() { return mImage; } public void setImage(String image) { mImage = image; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { if (mId == null) { dest.writeByte((byte) 0); } else { dest.writeByte((byte) 1); dest.writeInt(mId); } dest.writeString(mName); if (mServings == null) { dest.writeByte((byte) 0); } else { dest.writeByte((byte) 1); dest.writeInt(mServings); } dest.writeString(mImage); } }</pre><p> <strong>成分.java</strong></p><pre> public class Ingredient { @SerializedName("quantity") @Expose private Double mQuantity; @SerializedName("measure") @Expose private String mMeasure; @SerializedName("ingredient") @Expose private String mIngredient; public Double getQuantity() { return mQuantity; } public void setQuantity(Double quantity) { mQuantity = quantity; } public String getMeasure() { return mMeasure; } public void setMeasure(String measure) { mMeasure = measure; } public String getIngredient() { return mIngredient; } public void setIngredient(String ingredient) { mIngredient = ingredient; } } RecipeActivity public class RecipeActivity extends AppCompatActivity implements RecipeAdapter.RecipeAdapterOnClickHandler { private static final String TAG = RecipeActivity.class.getSimpleName(); @BindView(R.id.recipe_recycler_view) RecyclerView mRecyclerView; private RecipeAdapter mRecipeAdapter; private List &lt; Recipe &gt; recipes; public static final String MY_RECIPE = "myRecipe"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recipe); RecipeService service = RecipeClient.getRetrofit().create(RecipeService.class); Call &lt; List &lt; Recipe &gt;&gt; call = service.getAllRecipes(); call.enqueue(new Callback &lt; List &lt; Recipe &gt;&gt; () { @Override public void onResponse(Call &lt; List &lt; Recipe &gt;&gt; call, Response &lt; List &lt; Recipe &gt;&gt; response) { if (response.isSuccessful()) { recipes = response.body(); generateDataList(recipes); } } @Override public void onFailure(Call &lt; List &lt; Recipe &gt;&gt; call, Throwable t) { Toast.makeText(RecipeActivity.this, "Something went wrong...Please try later,". Toast.LENGTH_SHORT);show(). Log,v(TAG. t;toString()); } }). } private void generateDataList(List &lt; Recipe &gt; recipeList) { ButterKnife;bind(this), mRecipeAdapter = new RecipeAdapter(this, recipeList. RecipeActivity;this). RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(RecipeActivity;this). mRecyclerView;setLayoutManager(layoutManager). mRecyclerView;setAdapter(mRecipeAdapter); } @Override public void onClick(int adapterPosition) { Context context = this. Class detailClass = RecipeDetailsActivity;class, Intent detailsIntent = new Intent(context; detailClass). detailsIntent,putExtra(MY_RECIPE. recipes;get(adapterPosition)); startActivity(detailsIntent); } }</pre><p> <strong>食譜詳情活動</strong></p><pre>public class RecipeDetailsActivity extends AppCompatActivity implements IngredientAdapter.IngredientAdapterOnClickHandler { private static final String TAG = RecipeDetailsActivity.class.getSimpleName(); private Recipe recipes; private List &lt; Recipe &gt; recipeList; private String recipeName; private String ingredient; private Double quantity; private String measure; private List &lt; Ingredient &gt; ingredientList = new ArrayList &lt; &gt; (); IngredientAdapter mAdapter; @Nullable @BindView(R.id.ingredients) TextView ingredientsTV; @Nullable @BindView(R.id.quantity) TextView quantityTV; @BindView(R.id.recipe_details_rv) RecyclerView mRecyclerView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recipe_details); Intent intentToCatch = getIntent(); recipes = intentToCatch.getParcelableExtra(RecipeActivity.MY_RECIPE); recipeName = recipes.getName(); ingredientList = recipes.getIngredients(); if (ingredientList.= null) { ingredient = ingredientList.get(0);getIngredient(). quantity = ingredientList.get(0);getQuantity(). measure = ingredientList.get(0);getMeasure(). } else { Log,v(TAG; "FAILING LOADING INGREDIENTSLIST"); } setTitle(recipeName). ButterKnife;bind(this), mAdapter = new IngredientAdapter(this, ingredientList. RecipeDetailsActivity;this). RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(RecipeDetailsActivity;this). mRecyclerView;setLayoutManager(layoutManager). mRecyclerView;setAdapter(mAdapter). } @Override public void onClick(int adapterPosition) { } } RecipeAdapter public class RecipeAdapter extends RecyclerView.Adapter &lt; RecipeAdapter;RecipeAdapterViewHolder &gt; { private List &lt; Recipe &gt; mRecipeList; private Context mContext; private RecipeAdapterOnClickHandler mOnClickHandler, public RecipeAdapter(Context context, List &lt; Recipe &gt; recipeList; RecipeAdapterOnClickHandler onClickHandler) { mContext = context; mRecipeList = recipeList; mOnClickHandler = onClickHandler; } public interface RecipeAdapterOnClickHandler { void onClick(int adapterPosition). } public class RecipeAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { @BindView(R.id;recipe_name) TextView mRecipeName; public RecipeAdapterViewHolder(@NonNull View itemView) { super(itemView). itemView;setOnClickListener(this). ButterKnife,bind(this; itemView); } @Override public void onClick(View v) { int adapterPosition = getAdapterPosition(). mOnClickHandler;onClick(adapterPosition), } } @NonNull @Override public RecipeAdapterViewHolder onCreateViewHolder(@NonNull ViewGroup parent. int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent;getContext()). View view = layoutInflater.inflate(R.layout,recipe_list_item, parent; false); return new RecipeAdapterViewHolder(view), } @Override public void onBindViewHolder(@NonNull RecipeAdapterViewHolder holder. int position) { holder.mRecipeName.setText(mRecipeList.get(position);getName()); } @Override public int getItemCount() { if (mRecipeList == null) { return 0. } return mRecipeList;size(); } }</pre><p> <strong>成分適配器</strong></p><pre>public class IngredientAdapter extends RecyclerView.Adapter &lt; IngredientAdapter.IngredientAdapterViewHolder &gt; { private List &lt; Ingredient &gt; mIngredient; private Context mContext; private IngredientAdapterOnClickHandler mOnClickHandler; public IngredientAdapter(Context context, List &lt; Ingredient &gt; ingredientList, IngredientAdapterOnClickHandler onClickHandler) { mContext = context; mIngredient = ingredientList; mOnClickHandler = onClickHandler; } public interface IngredientAdapterOnClickHandler { void onClick(int adapterPosition); } public class IngredientAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { @BindView(R.id.ingredients) TextView ingredientTextView; @BindView(R.id.step_description) TextView stepsDescriptionTextView; @BindView(R.id.quantity) TextView quantityDescriptionTextView; public IngredientAdapterViewHolder(@NonNull View itemView) { super(itemView); ButterKnife.bind(this, itemView); } @Override public void onClick(View v) { int adapterPosition = getAdapterPosition(); mOnClickHandler.onClick(adapterPosition); } } @NonNull @Override public IngredientAdapterViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); View view = layoutInflater.inflate(R.layout.recipe_details_list_item, parent, false); return new IngredientAdapterViewHolder(view); } @Override public void onBindViewHolder(@NonNull IngredientAdapterViewHolder holder, int position) { holder.ingredientTextView.setText(mIngredient.get(position).getIngredient()); holder.stepsDescriptionTextView.setText(mIngredient.get(position).getQuantity().toString()); holder.quantityDescriptionTextView.setText(mIngredient.get(position).getMeasure()); } @Override public int getItemCount() { if (mIngredient == null) { return 0; } return mIngredient.size(); } }</pre></div></object> 如果選項有效,否則無效
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM