4

I am trying to use onActivityResult in my RecyclerViewAdapter. But I get the error that the 'The method does not override from its superclass'. I tried implementing the interface but onActivityResult never gets called. I have already searched enough on the StackOverflow questions like this one but couldn't find anything helpful.

RecyclerViewAdapter.java

package com.example.waheed.telegramchat;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {
    //String arrays to store user data
    static String[] contact_name, Phone_no, user_id;
    Context context;

    public RecyclerAdapter(String[] contact_name, String[] Phone_no, String[] user_id, Context context) {

        //Getting the data from MainActivity.java
        this.context = context;
        this.user_id = user_id;
        this.contact_name = contact_name;
        this.Phone_no = Phone_no;
    }

    @NonNull
    @Override
    public RecyclerAdapter.RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        //Setting the row layout for Recyclerview
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout, parent, false);
        RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view, this.context);

        return recyclerViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {


        holder.tx_contact.setText(contact_name[position]);
        holder.tx_phone.setText(Phone_no[position]);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return contact_name.length;

    }

    public static class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {


        Context context;
        TextView tx_contact, tx_phone;
        ImageButton message_btn;
        static ImageView img_profile;

        public RecyclerViewHolder(View itemView, Context context) {
            super(itemView);
            tx_contact = (TextView) itemView.findViewById(R.id.txt_contactname);
            tx_phone = (TextView) itemView.findViewById(R.id.phonenumber);
            message_btn = (ImageButton) itemView.findViewById(R.id.chat_icon);
            img_profile = (ImageView) itemView.findViewById(R.id.profile_pic);
            this.context = context;
            //Calling onclick function
            message_btn.setOnClickListener(this);
            img_profile.setOnClickListener(this);

        }

        public void makeCall(String ID, String name, String packageName, String className) {

            //
            String data = "content://com.android.contacts/data/" + ID;
            // Build the intent
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            // the _ids you save goes here at the end of /data/id
            intent.setData(Uri.parse("content://com.android.contacts/data/" + ID));
            intent.setDataAndType(Uri.parse(data), className);
            intent.setPackage(packageName);
            // Verify it resolves
            PackageManager packageManager = context.getPackageManager();
            List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
            boolean isIntentSafe = activities.size() > 0;
            Log.d("See this " + ID, activities.size() + "");
            // Start an activity if it's safe
            if (isIntentSafe) {
                try {
                    //Toast to show which user is being called
                    context.startActivity(intent);
                    Toast.makeText(context, "Opening chat with " + name + " on Telegram", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    Toast.makeText(context, "OOPS!,Something went wrong\nPlease grant app permissions in setting or send feedback.", Toast.LENGTH_LONG).show();
                }
            }

        }

        @Override
        public void onClick(View v) {

            //Getting the position of the item clicked
            int i = getAdapterPosition();
            //Storing the selected items in Strings
            String name = RecyclerAdapter.contact_name[i];
            String phone = RecyclerAdapter.Phone_no[i];
            String ID = RecyclerAdapter.user_id[i];
            String mimeType = "vnd.android.cursor.item/vnd.org.telegram.messenger.android.profile";


            String packageName = "org.telegram.messenger";

            switch (v.getId()) {
                case R.id.chat_icon:
                    makeCall(ID, name, packageName, mimeType);
                    break;
                case R.id.profile_pic:
                    Intent intent = new Intent(this.context, showImages.class);
                    ((Activity) context).startActivityForResult(intent, 1);
                    break;

            }
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            Bitmap bitmap;
            if (requestCode == 1) {
                if (resultCode == showImages.RESULT_OK) {
                    String result = data.getStringExtra("result");
                    Toast.makeText(this.context, "Clicked item is " + result, Toast.LENGTH_SHORT).show();
                    bitmap = BitmapFactory.decodeFile(result);
                    RecyclerViewHolder.img_profile.setImageBitmap(bitmap);
                }
                if (resultCode == showImages.RESULT_CANCELED) {
                    //Write your code if there's no result
                }
            }
        }

    }
}

showImages.java

package com.example.waheed.telegramchat;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import com.ImageAdapter;

import java.io.File;
import java.util.ArrayList;

public class showImages extends AppCompatActivity {

    ImageAdapter myImageAdapter;
    GridView gridView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_images);
        gridView = (GridView) findViewById(R.id.gridview);
        myImageAdapter = new ImageAdapter(this);
        gridView.setAdapter(myImageAdapter);

        String ExternalStorageDirectoryPath = Environment
                .getExternalStorageDirectory()
                .getAbsolutePath();

        String targetPath = ExternalStorageDirectoryPath + "/Android/data/org.telegram.messenger/cache/";

        File targetDirector = new File(targetPath);

        final ArrayList<String> imagePaths = new ArrayList<String>();
        final File[] files = targetDirector.listFiles();
        for (File file : files) {
            if (file.getName().toLowerCase().endsWith(".jpg") ||
                    file.getName().toLowerCase().endsWith(".png")) {
                imagePaths.add(file.getAbsolutePath());
                myImageAdapter.add(file.getAbsolutePath());
            }
        }

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String result = imagePaths.get(position);
                Intent returnIntent = new Intent();
                returnIntent.putExtra("result", result);
                setResult(showImages.RESULT_OK, returnIntent);
                finish();
            }
        });
    }
}
Zain Aftab
  • 703
  • 7
  • 21
Waheed Abbas
  • 187
  • 1
  • 4
  • 18
  • create a public method in `ImageAdapter` class and pass data using `myImageAdapter` object. – Jaydeep Devda Jul 07 '18 at 13:42
  • write `onActivityResult` override method in `showImages` Activity and inside result ok pass data to adapter using `myImageAdapter.onActivityResult(requestCode, resultCode, data)`, rest of the things are fine. – Jaydeep Devda Jul 07 '18 at 13:54

4 Answers4

2

The RecyclerView.ViewHolder class does not contain a definition of an onActivityResult method that it can override.

onActivityResult, as far as I understand, only appears as a method of the Activity & Fragment classes.

Move the code

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Bitmap bitmap;
    if (requestCode == 1) {
        if (resultCode == showImages.RESULT_OK) {
            String result = data.getStringExtra("result");
            Toast.makeText(this.context, "Clicked item is " + result, Toast.LENGTH_SHORT).show();
            bitmap = BitmapFactory.decodeFile(result);
            RecyclerViewHolder.img_profile.setImageBitmap(bitmap);
        }
        if (resultCode == showImages.RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}

to the class that initiated the call to showImages. I noticed that showImages closes when item is clicked.

gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String result = imagePaths.get(position);
        Intent returnIntent = new Intent();
        returnIntent.putExtra("result", result);
        setResult(showImages.RESULT_OK, returnIntent);
        finish();
    }
});
cavpollo
  • 4,071
  • 2
  • 40
  • 64
hjchin
  • 864
  • 2
  • 8
  • 25
  • `RecyclerViewHolder.img_profile.setImageBitmap(bitmap);` this is not guaranteed to exist at this time – EpicPandaForce Jul 07 '18 at 14:17
  • @EpicPandaForce can you elaborate more? Does this has anything to do with OP question? – hjchin Jul 07 '18 at 14:47
  • I mean if you're coming back from the other app and your app was killed by low memory condition. You get the intent but you probably don't have your data loaded yet which is async so the adapter won't have this view and so that can crash – EpicPandaForce Jul 07 '18 at 15:12
  • I look at the code for the 3rd time, didn't really pay attention to that part. When return from `showImages`, the adapter of the recyclerView should update the item based on the position, passing the imagepath in. Let the onBindViewHolder() function update the image there. The RecyclerView will be saved and restored whenever the app goes to background and return to foreground, the view will stay intact, so there is no need to worry this part. OP should also upload the layout file as he/she uses static variable for imageView, which is confusing to me. – hjchin Jul 07 '18 at 15:37
0

You have to override onActivityResult in your activity wich contains the recyclerview not in viewholder class

SiSa
  • 2,594
  • 1
  • 15
  • 33
0

You must implement onActivityResult in your activity class not in RecyclerViewAdapter. This method is used from your activity to retrieve data from other intents/activities that have started from your activity and normally it has no place inside RecyclerViewAdapter.

0

you should use onActivityForResult in activity ,and create interface to handle action ,logic - adapter only display view.

TieuNhi
  • 29
  • 4