6

There are a list of students.each row shows an Image,Name and number. I created a Room database and only managed to populate "name" and "number" columns into the list using this guide.

When user opens the AddNewStudentActivity, He/She needs to choose a photo from gallery and fill two editTexts for the name and number and click "save" and save to student to the studentDatabase.

the image should be displayed in the list alongside those two texts(name and number).

I have NO IDEA how to do this i only think the process should be like "setting up an intent that opens the gallery and we can choose an image and get it's path stored on the database and display it from database to the list"but don't know how to code it.there are tutorials about this but they were all using SQLITE and not Room and I'm new to the whole database topic.

-Thanks

NewStudentActivity.java

public class NewStudentActivity extends AppCompatActivity {

    public static final String EXTRA_REPLY = "com.example.android.studentlistsql.REPLY";

    private EditText mNameWordView;
    private EditText mNumWordView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_student);
        mNameWordView = findViewById(R.id.name_word);
        mNumWordView = findViewById(R.id.num_word);

        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(mNameWordView.getText())) {
                    setResult(RESULT_CANCELED, replyIntent);
                } else {
                    String word = mNameWordView.getText().toString();
                    replyIntent.putExtra(EXTRA_REPLY, word);
                    setResult(RESULT_OK, replyIntent);
                }
                if (TextUtils.isEmpty(mNumWordView.getText())) {
                    setResult(RESULT_CANCELED, replyIntent);
                } else {
                    String word = mNumWordView.getText().toString();
                    replyIntent.putExtra(EXTRA_REPLY, word);
                    setResult(RESULT_OK, replyIntent);
                }
                finish();
            }
        });

    }
}

StudentListAdapter.java

public class StudentListAdapter extends RecyclerView.Adapter<StudentListAdapter.WordViewHolder> {

    class WordViewHolder extends RecyclerView.ViewHolder {
        private final TextView nameItemView;
        private final TextView numberItemView;

        private WordViewHolder(View itemView) {
            super(itemView);
            nameItemView = itemView.findViewById(R.id.nameTextView);
            numberItemView = itemView.findViewById(R.id.numberTextView);
        }
    }

    private final LayoutInflater mInflater;
    private List<Student> mStudents; // Cached copy of words

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

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

    @Override
    public void onBindViewHolder(WordViewHolder holder, int position) {
        if (mStudents != null) {
            Student current = mStudents.get(position);
            holder.nameItemView.setText(current.getStudentName());
            holder.numberItemView.setText(current.getStudentNumber());
        } else {
            // Covers the case of data not being ready yet.
            holder.nameItemView.setText("No Word");
        }
    }

    void setStudents(List<Student> words){
        mStudents = words;
        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 (mStudents != null)
            return mStudents.size();
        else return 0;
    }
}
1
  • I realized that I answered the question but didn't talk about Room, what exactly was your question about Room, how to insert or query? Or something else.
    – Suleyman
    May 30, 2018 at 17:26

2 Answers 2

5

To be honest the process isn't that much different with Room. As you said, to pick the photo from the Gallery you use an intent:

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "select a picture"), YOUR_IMAGE_CODE);

Then you handle this case in onActivityResult:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == YOUR_IMAGE_CODE) {
        if(resultCode == RESULT_OK)
            Uri selectedImageUri = data.getData();
    }
}

So selectedImageUri is the piece of information that you save in your database. In your Entity class Student.java you can change mStudentPic to String so when you insert your Uri you can use a method:

selectedImageUri.toString();

and when you want to convert it back to Uri:

Uri uri = Uri.parse(yourUriAsString);

I assumed that you know how to insert and query values from the database.

And then in your onBindViewHolder you can use Glide or Picasso, or any other library to load the image, for example with Glide:

Glide.with(context)
.load(new File(uri.getPath()))
.into(imageView);
21
  • So YOUR_IMAGE_CODE is any number you can define it like that public static final int YOUR_IMAGE_CODE = 192;, and onActivityResult goes in your Activity. Try that, the Uri should not be null after that.
    – Suleyman
    May 30, 2018 at 17:56
  • Hi,Thx a lot,I managed to add do the things you said ,now the pictures uri gets added to the database but in the Adapter it still doesnt show the image on the list Jun 1, 2018 at 9:25
  • "holder.studImage.setImageURI(Uri.parse(current.getStudentPic()));" it this: "resolveUri failed on bad bitmap uri: content://com.android.providers.media.documents/document/image%3A42 W/ImageView: Unable to open content: content://com.android.providers.downloads.documents/document/raw%3A java.lang.SecurityException: Permission Denial: opening provider com.android.providers.downloads.DownloadStorageProvider from ProcessRecord ... requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs" Jun 1, 2018 at 9:26
  • @HessamEmami no problem :) I really think you should try using Picasso or Glide to show the image, it's much easier, instead of setImageUri. Judging from the error it seems that you are trying to access files in Downloads folder. Are you using ACTION_GET_CONTENT? I'm not sure, but try using ACTION_OPEN_DOCUMENT instead, refer to this question regarding that matter.
    – Suleyman
    Jun 1, 2018 at 14:32
  • Thanks!I just rewrote my project and according to your help everything works find and the image loads without using picasso or glide. Jun 2, 2018 at 16:35
2

Also, I am using the same function with SQLite I am the storing just image path and get from SQLite and load image using image URI

holder.imgUserPhoto.setImageURI(Uri.parse(new File(contactModel.getContactPhoto()).toString()));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.