简体   繁体   English

将数据发送到其他活动后,Intent对象显示为null

[英]Intent Object show null After sending data to other activity

I am facing problem while sending data through Intent . 通过Intent发送数据时遇到问题。

Let's say I have two Activities : 假设我有两个活动:

  1. Personal Information 个人信息

  2. Documentational Information. 文档信息。

What I am doing: When user fills all the given edit text fields and clicks save I send all the data through intent to the 3rd activity and now user is in the documentational activity, enters data and hits save, and data is transferred to the 3rd Activity. 我正在做什么:当用户填写所有给定的编辑文本字段并单击“保存”时,我会通过意图将所有数据发送到第三个活动,现在用户处于文档活动中,输入数据并点击保存,然后将数据传输到第三个活动活动。

The problem is in the 3rd Activity : I only get data based on the latest activity - I mean if user first enters personal info and then documentational info, I only get data of doucumentational activity and vice versa. 问题出在第三活动中 :我仅基于最新活动获取数据-我的意思是,如果用户首先输入个人信息,然后输入文档信息,则我只会获取重复活动的数据,反之亦然。

I am building an app that can get data from the user and show it in a pdf file 我正在构建一个可以从用户那里获取数据并将其显示为pdf文件的应用程序

personal info activity : 个人信息活动:

public void getting_data_from_fields_and_sending_on_click_listner () {

        radio_Group_Martial_Status.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {

                RadioButton radioButton = (RadioButton) findViewById(checkedId);
                martial_status = radioButton.getText().toString() ;

            }
        });

        Intent sendingData = new Intent (Personal_Information_Activity.this , Selecting_Activity.class);
        sendingData.putExtra("FirstName" , fullName.getText().toString() );
        sendingData.putExtra("Born" , born.getText().toString() );
        sendingData.putExtra("Nationality" , nationality.getText().toString() );
        sendingData.putExtra("CurrentPlace" , currentPlace.getText().toString() );
        sendingData.putExtra("Address" , address.getText().toString() );
        sendingData.putExtra("PhoneNumber" , phoneNumber.getText().toString() );
        sendingData.putExtra("EmailAddress" , emailAddress.getText().toString() );
        sendingData.putExtra("SelfIntro" , selfIntro.getText().toString() );
        sendingData.putExtra("Day" ,  day.getSelectedItem().toString());
        sendingData.putExtra("Month" , month.getSelectedItem().toString() );
        sendingData.putExtra("Year" , year.getSelectedItem().toString() );
        sendingData.putExtra("MartialStatus" , martial_status);

        startActivity(sendingData);
}

doc info activity 文档信息活动

private void getting_data_from_fields_and_sending_on_click_listner() {

        Intent sendingData = new Intent (Documentation_Activity.this , Selecting_Activity.class);

        String passportIssueDate = passportIssueM.getSelectedItem().toString()+"-"+passportIssueY.getSelectedItem().toString();
        String idCardIssueDate = idIssueM.getSelectedItem().toString()+"-"+idIssueY.getSelectedItem().toString();
        String licenceIssueDate = licenceIssueM.getSelectedItem().toString()+"-"+licenceIssueY.getSelectedItem().toString();
        String passportExpiryDate =  passportExpiryM.getSelectedItem().toString()+"-"+passportExpiryY.getSelectedItem().toString();
        String idCardExpiryDate =  idExpiryM.getSelectedItem().toString()+"-"+idExpiryY.getSelectedItem().toString();
        String licenceExpiryDate =  licenceExpiryM.getSelectedItem().toString()+"-"+licenceExpiryY.getSelectedItem().toString();

        sendingData.putExtra("PassportNumeber" , passportNumber.getText().toString());
        sendingData.putExtra("IdCard" , idCardNumber.getText().toString());
        sendingData.putExtra("Licence" , licenceNumebr.getText().toString());

        sendingData.putExtra("PID"  , passportIssueDate);
        sendingData.putExtra("PED"  , passportExpiryDate);
        sendingData.putExtra("IID"  , idCardIssueDate);
        sendingData.putExtra("IED"  , idCardExpiryDate);
        sendingData.putExtra("LID"  , licenceIssueDate);
        sendingData.putExtra("LED"  , licenceExpiryDate);

        startActivity(sendingData);
    }

3rd activity 第三活动

    public void gettingInfoFromTheDocumentationalInformationActivity() {    

        passportNumber =  getInformation.getStringExtra("PassportNumeber");
        passportIssue =  getInformation.getStringExtra("PID");
        passportExpiry =  getInformation.getStringExtra("PED");
        idNumebr =  getInformation.getStringExtra("IdCard");
        idIssue =  getInformation.getStringExtra("IID");
        idExpiry =  getInformation.getStringExtra("IED");
        licenceNumebr =  getInformation.getStringExtra("Licence");
        licenceIssue =  getInformation.getStringExtra("LID");
        licenceExpiry =  getInformation.getStringExtra("LED");
    }

    public void gettingInfoFromThePersonalInformationActivity() {

        fullName = getInformation.getStringExtra("FirstName");
        born = getInformation.getStringExtra("Born");
        nationality = getInformation.getStringExtra("Nationality");
        currentLocation = getInformation.getStringExtra("CurrentPlace");
        address = getInformation.getStringExtra("Address");
        emailAddress = getInformation.getStringExtra("EmailAddress");
        selfInfo = getInformation.getStringExtra("SelfIntro");
        phoneNumber = getInformation.getStringExtra("PhoneNumber");
        day = getInformation.getStringExtra("Day");
        month = getInformation.getStringExtra("Month");
        year = getInformation.getStringExtra("Year");
        martialStatus = getInformation.getStringExtra("MartialStatus");
    }

    private void createPdf() throws FileNotFoundException, DocumentException 
    {
        Document document = new Document(PageSize.A4);

        String output = Environment.getExternalStorageDirectory()+"/mypdf.pdf";

        PdfWriter.getInstance(document, new FileOutputStream(output));

        document.open();

        document.add(new Paragraph("Name : " +fullName));
        document.add(new Paragraph("Date of Birth : "+ day+"-"+month+"-"+year));
        document.add(new Paragraph("Birth Place : " +born));
        document.add(new Paragraph("Nationality : " + nationality));
        document.add(new Paragraph("Current Place : " +currentLocation));
        document.add(new Paragraph("Martial Status : " + martialStatus));
        document.add(new Paragraph("Address : " + address));
        document.add(new Paragraph("Phone Number : " +phoneNumber));
        document.add(new Paragraph("Email : " + emailAddress));
        document.add(new Paragraph("Self Introduction : " + selfInfo));
        document.add(new Paragraph("__________________________________"));

        document.add(new Paragraph("Passport Number : " + passportNumber));
        document.add(new Paragraph("Issue Date : " +passportIssue));
        document.add(new Paragraph("Expiry Date : " + passportExpiry));
        document.add(new Paragraph("ID Card Number  : " + idNumebr));
        document.add(new Paragraph("Issue Date : " +idIssue));
        document.add(new Paragraph("Expiry Date : " + idExpiry));
        document.add(new Paragraph("Licence Number  : " + licenceNumebr));
        document.add(new Paragraph("Issue Date : " +licenceIssue));
        document.add(new Paragraph("Expiry Date : " + licenceExpiry));

        document.close();
}

You can't send data to FirstActivity to ThirdActivity by using intent , You can send data to FirstActivity to SecondActivity by intent again you have to get the data on SecondActivity and again have to send data to ThirdActivity otherwise you will get null data . 你无法将数据发送到FirstActivityThirdActivity使用intent ,您可以将数据发送到FirstActivitySecondActivity的意图再次你已经得到的数据SecondActivity ,并再次有数据发送到ThirdActivity否则你将得到空数据。

Solution 1: Either you can create a Constant class and store data on constant class and get data from Constant class or, Create a POJO class and set Data to POJO and make it Serializable send POJO class to Next of your Activity. 解决方案1:您可以创建一个Constant类并将其存储在constant类上并从Constant类获取数据, 或者创建一个POJO类并将Data设置为POJO并使其可序列化,然后将POJO类发送给Activity的Next。

Reference Code : 参考代码 :

public class Constants {

    public static ArrayList<LoadDataResult> data = new ArrayList<LoadDataResult>();

  }

When you will get data from User by Edittext get and set to POJO which in Constant class and where do you want to get create reference and get data. 当您通过Edittext从User获取数据时,获取并设置为POJO,这在Constant类中,以及您想在哪里获取创建引用并获取数据。

Solution 2 : You have 8 Activities and you want to save all information and create PDF file from MainActivity.java 解决方案2:您有8个活动,并且想要保存所有信息并从MainActivity.java创建PDF文件。

Here is the solution : Use SharedPreference to save Data , Save data from all of your different activities, and in Your MainActivity when you want just getData from SharePreference , by using this also there is not chance of lost of Data. 这是解决方案:使用SharedPreference保存数据,保存所有不同活动的数据,并且在MainActivity中,当您只希望从SharePreference getData时,使用此方法也不会丢失数据。

FirstActivity.java : FirstActivity.java:

 SharedPreferences pref;
        SharedPreferences.Editor editor;

     pref = (this.getApplicationContext()).getSharedPreferences("USER_DATA", MODE_PRIVATE);

     editor = pref.edit();
                                            editor.putBoolean("login_status", true);
                                            editor.putString("CODE", "" + String.valueOf(obj.get("code")));
                                            editor.putString("NAME", "" + String.valueOf(obj.get("message")));
                                            editor.putString("USER_ID", "" + String.valueOf(obj.get("user id")));
                                            editor.commit();

SecondActivity.java : SecondActivity.java:

     SharedPreferences pref;
            SharedPreferences.Editor editor;

         pref = (this.getApplicationContext()).getSharedPreferences("USER_DATA", MODE_PRIVATE);



                                                editor.putString("ADDRESS", "" + String.valueOf(obj.get("message")));
                                                editor.putString("PHONE", "" + String.valueOf(obj.get("user id")));
                                                editor.commit();

MainActivity.java : When you want to get All Data MainActivity.java:要获取所有数据时

SharedPreferences pref;
            SharedPreferences.Editor editor;

         pref = (this.getApplicationContext()).getSharedPreferences("USER_DATA", MODE_PRIVATE);

String name = pref.getString("NAME", "");
String userId = pref.getString("USER_ID", "");
String address = pref.getString("ADDRESS", "");
String phone= pref.getString("PHONE", "");

You can solve the problem by simply send the pojo which contains all of the data in each activity. 您可以通过简单地发送包含每个活动中所有数据的pojo来解决问题。 You only need to pass to pojo from one activity to another activity. 您只需要将pojo从一个活动传递到另一个活动。

You need to create pojo to something like this: 您需要为以下内容创建pojo:

public class Info implements Serializable {

  private String firstName;
  private String born;
  private String nationality;
  //etc ...

  // Data from another activity:
  private String passportNumber;
  private String idCard;
  private String license;
  //etc ...

  // Data from another activity:
  // etc ...

  // Constructor

  // Setter and Getter
}

Then you can send the data intent with: 然后,您可以通过以下方式发送数据意图:

public void getting_data_from_fields_and_sending_on_click_listner () {
  Intent sendingData = new Intent (Personal_Information_Activity.this , Selecting_Activity.class);
  Info info = new Info();
  info.setFirstName(fullName.getText().toString());
  info.setBorn(born.getText().toString());
  info.setNationality(nationality.getText().toString());
  // etc

  // Then attach the data to intent.
  sendingData.putExtra("info" , info);

  startActivity(sendingData);
}

Then you get the data info in another activity with: 然后,您可以通过以下另一活动获得数据信息:

private Info mInfo;

@Override
public void onCreate(Bundle savedInstanceState) {
  ...
  Intent intent = getIntent();
  mInfo = (Info) intent.getSerializableExtra("info");
  ...
}

And set the data to the Info pojo again: 并再次将数据设置到Info pojo:

private void getting_data_from_fields_and_sending_on_click_listner() {

  Intent sendingData = new Intent (Documentation_Activity.this , Selecting_Activity.class);

  mInfo.setPassportNumber(passportNumber.getText().toString());
  mInfo.setIdCard(idCardNumber.getText().toString());
  mInfo.setLicense(licenceNumebr.getText().toString());
  // etc ...

  sendingData.putExtra("info" , mInfo);
  startActivity(sendingData);
}

With the all the above codes, you can safe yourself from headache for remembering all of the extra keys. 有了上述所有代码,您就可以记住所有额外的键,从而避免头痛。 You also only need to maintain one object, which is the Info object, for all of your activity. 您还只需为所有活动维护一个对象,即Info对象。

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.

相关问题 启动新活动后,先前的活动是否有可能继续通过意图将数据发送到新活动? - Is it possible that after launching new activity the previous activity keeps sending data to new activity via intent? 子活动返回NULL意图对象 - Sub activity Returning NULL intent object 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 Android服务将数据包数据发送到活动为NULL - Android Service sending bundle data to activity is NULL 将数据发送到 Android Studio 中的其他活动时出现问题 - Problem sending data to other activity in Android Studio 如何在使用Intent集调用Activity后使getIntent()返回null - How to get getIntent() to return null after Activity called with an Intent set 通过意图将对象传递给新活动时为空指针 - Null Pointer When Passing object to new activity through intent 是否可以将MainActivity中创建的片段对象作为意图额外地传递给其他活动? - Can a fragment object created in MainActivity be passed as intent extra to other activity? Parcelable 对象在接收活动时为 Null,在其他情况下为好 - Parcelable object is Null on receiving activity and good in other 在从适配器向活动传递意图的数据时获取空值 - Getting Null Values while passing data with intent from adapter to activity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM