简体   繁体   中英

How do I get my values into the recycle view?

I have a question about Room in Android and its POST and GET mechanic. I have made an app with a recycle view with the help of this site: https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#0 as a tutorial but the difference between this guy's code and my code is that he uses a class with one string and I use a class with 4 strings.

These strings values should be the values of a couple of Edit text views text. Though they should get the data live from room as you can see in this tutorial. I have finished the tutorial until the last two sliders and have not understood what I should change in the code below to make it possible for me to fill my Room database class.

So I can post from my Create_Customer Activity to room and then in my main activity get the database and fill the recycleview with data. Below follows the code that I have trouble with.

Create_Customer:

Customer customer = new  Customer(data.getStringExtra(NewWordActivity.EXTRA_REPLY));

public void onClick(View view) {
   Intent replyIntent = new Intent();
   if (TextUtils.isEmpty(mEditWordView.getText())) {
      setResult(RESULT_CANCELED, replyIntent);
   } else {
     String word = mEditWordView.getText().toString();
     replyIntent.putExtra(EXTRA_REPLY, word);
     setResult(RESULT_OK, replyIntent);
   }
  finish();
}

Main Activity:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);

   if (requestCode == NEW_WORD_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
     Customer customer = new Customer(data.getStringExtra(NewWordActivity.EXTRA_REPLY));
       mWordViewModel.insert(word);
   } else {
       Toast.makeText(
               getApplicationContext(),
               R.string.empty_not_saved,
               Toast.LENGTH_LONG).show();
   }

}

I need help with the code above and here is my Adapter:

package com.example.jenso.paperseller;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

public class PapperRecyclerAdapter extends RecyclerView.Adapter<PapperRecyclerAdapter.CustomerViewHolder> {



    class CustomerViewHolder extends  RecyclerView.ViewHolder{
        private TextView textViewName;
        private TextView textViewAddress;
        private TextView textViewPhoneNumber;
        private TextView textViewEmail;

        private CustomerViewHolder(View itemView){
            super(itemView);
            textViewName = itemView.findViewById(R.id.nameTxt);
            textViewAddress = itemView.findViewById(R.id.addressTxt);
            textViewPhoneNumber = itemView.findViewById(R.id.PhoneNumberTxt);
            textViewEmail = itemView.findViewById(R.id.emailTxt);


        }


    }
    private List<Customer> mCustomers;
    private Context context;

    private final LayoutInflater mInflater;




    public PapperRecyclerAdapter(Context context) {
          mInflater = LayoutInflater.from(context);

    }


    @Override
    public CustomerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = mInflater.inflate(R.layout.list_item, parent, false);

        return new CustomerViewHolder(itemView);
    }
    @Override
    public void onBindViewHolder(CustomerViewHolder holder, int position) {
        if(mCustomers != null){
            Customer current = mCustomers.get(position);
            holder.textViewName.setText(current.getFullName());
            holder.textViewAddress.setText(current.getAddress());
            holder.textViewPhoneNumber.setText(current.getPhonenumber());
            holder.textViewEmail.setText(current.getEmail());

        }else{
            holder.textViewName.setText("Full name");
            holder.textViewAddress.setText("Address");
            holder.textViewPhoneNumber.setText("PhoneNumber");
            holder.textViewEmail.setText("Email");


        }
    }
    void setCustomer(List<Customer> customers){
        mCustomers = customers;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        if(mCustomers != null){
            return mCustomers.size();
        }else{
            return 0;
        }

    }

    public class ViewHolder extends RecyclerView.ViewHolder{




        public ViewHolder(View itemView) {
            super(itemView);


        }
    }
}

Where does he get the data from and how am I supposed to use it so I can fill all my strings with the data I get?

Change your constructor

   public PapperRecyclerAdapter(Context context) {
      mInflater = LayoutInflater.from(context);

}

to

 public PapperRecyclerAdapter(Context context, ArrayList<Customer> myList) {
      mInflater = LayoutInflater.from(context);
      mCustomer = myList;
}

Here you store your list inside your global variable. You can now use it for fill your value, inside the onBindViewHolder you have the position of the item in the list. The Customer current = mCustomers.get(position); give you your customer

EDIT : you can see this line if(mCustomers != null){ you can't pass inside because you never initialize your mCustomers variable

You need to create your recylcler view and bind it to it's id

RecyclerView recyclerView = (RecyclerView) findViewbyId(R.id.yourrecyclerid)

Then you need to create your adapter and add it to the recycler

PapperRecyclerAdapter adapter = new PapperRecyclerAdapter(getContext(), yourArrayListOfCustomer);
recyclerview.setAdapter(adapter); 

I have been facing the same issue my self where I wanted to get another text from another editText and display it on the RecyclerView and I just solved it. I do not know if there is a better solution, if there is kindly share it with us.

Below is my code:

ListAdapter:

public class MaterialListAdapter extends RecyclerView.Adapter<MaterialListAdapter.ViewHolder> {

    class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView firstWordItemView;
        private final TextView secondWordItemView;
        private ViewHolder(View itemView) {
            super(itemView);
            firstWordItemView = itemView.findViewById(R.id.textView);
            secondWordItemView = itemView.findViewById(R.id.textView2);
        }
    }

    private final LayoutInflater mInflater;
    private List<MaterialEntity> mMaterial; // Cached copy of words

    public MaterialListAdapter(Context context) {
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = mInflater.inflate(R.layout.recyclerview_material_item, parent, false);
        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        if (mMaterial != null) {
            MaterialEntity current = mMaterial.get(position);
            holder.firstWordItemView.setText(current.getMaterialName());
            holder.secondWordItemView.setText(current.getMaterialBrand());
        } else {
            // Covers the case of data not being ready yet.
            holder.firstWordItemView.setText("No Word");
            holder.secondWordItemView.setText("No Word");
        }
    }

    public void setMaterial(List<MaterialEntity> materials){
        mMaterial = materials;
        notifyDataSetChanged();
    }

    // getItemCount() is called many times, and when it is first called,
    // mWords has not been updated (means initially, it's null, and we can't return null).
    @Override
    public int getItemCount() {
        if (mMaterial != null)
            return mMaterial.size();
        else return 0;
    }
}

NewMaterialActivity (aka NewWordActivity):

public class NewMaterialActivity extends AppCompatActivity {

    public static final String EXTRA_REPLY = "com.example.android.materiallistsql.REPLY";
    public static final String EXTRA_REPLY2 = "com.example.android.materiallistsql.REPLY2";

    private EditText mEditWordView;
    private EditText mEditWordView2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_material);
        mEditWordView = findViewById(R.id.edit_word);
        mEditWordView2 = findViewById(R.id.edit_word2);

        final Button button = findViewById(R.id.button_save);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent replyIntent = new Intent();
                if (TextUtils.isEmpty(mEditWordView.getText())||
                        TextUtils.isEmpty(mEditWordView2.getText())) {
                    setResult(RESULT_CANCELED, replyIntent);
                } else {
                    String word = mEditWordView.getText().toString();
                    String word2 = mEditWordView2.getText().toString();
                    replyIntent.putExtra(EXTRA_REPLY, word);
                    replyIntent.putExtra(EXTRA_REPLY2, word2);
                    setResult(RESULT_OK, replyIntent);
                }
                finish();
            }
        });
    }
}

MainActivity:

public class MainActivity extends AppCompatActivity {

    private MaterialViewModel mMaterialViewModel;
    public static final int NEW_MATERIAL_ACTIVITY_REQUEST_CODE = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, NewMaterialActivity.class);
                startActivityForResult(intent, NEW_MATERIAL_ACTIVITY_REQUEST_CODE);
            }
        });

        RecyclerView recyclerView = findViewById(R.id.recyclerview);
        final MaterialListAdapter adapter = new MaterialListAdapter(this);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mMaterialViewModel = ViewModelProviders.of(this).get(MaterialViewModel.class);
        mMaterialViewModel.getAllMaterials().observe(this, new Observer<List<MaterialEntity>>() {
            @Override
            public void onChanged(@Nullable final List<MaterialEntity> materials) {
                // Update the cached copy of the words in the adapter.
                adapter.setMaterial(materials);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == NEW_MATERIAL_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
            MaterialEntity material = new MaterialEntity(data
                    .getStringExtra(NewMaterialActivity.EXTRA_REPLY),
                    data.getStringExtra(NewMaterialActivity.EXTRA_REPLY2));
            mMaterialViewModel.insertMaterial(material);
        } else {
            Toast.makeText(
                    getApplicationContext(),
                    R.string.empty_not_saved,
                    Toast.LENGTH_LONG).show();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM