Getting error : cannot resolve method getResource()

Getting error : cannot resolve method getResource()

我正在尝试与 Intent.ACTION_SEND 共享图像,但出现此错误:

cannot resolve method getResource()

这是我尝试与以下人共享图像的代码:

            File root = android.os.Environment.getExternalStorageDirectory();
            File dir = new File (root.getAbsolutePath() + "/myFolder");
            dir.mkdirs(); // build directory
            Random generator = new Random();
            int n = 10000;
            n = generator.nextInt(n);
            String fileName = "Image-"+ n +".jpg";
            File file = new File(dir, fileName);
            if (file.exists ()) file.delete ();

            try {
                FileOutputStream outStream = new FileOutputStream(file);
                InputStream is;
                Bitmap bitmap;
                is = this.getResources().openRawResource(R.drawable.image1);
                bitmap = BitmapFactory.decodeStream(is);
                try {
                    is.close();
                    is = null;
                } catch (IOException e) {
                }
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
                outStream.flush();
                outStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Uri outputFileUri = Uri.fromFile(file);
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setType("image/jpeg");
            intent.putExtra(Intent.EXTRA_STREAM, outputFileUri);
            startActivity(Intent.createChooser(intent, "Share this image via"));

如果您在片段中,请使用:

getActivity().getResources();

或尝试:

getApplicationContext().getResources();

如果您在 Activity 中但在内部 class 中编辑此行中的单词 this

is = this.getResources().openRawResource(R.drawable.image1);

收件人:

is = Your_Activity_Class_Name.this.getResources().openRawResource(R.drawable.image1);

首先调用方法getResources(), with an 's'. It is a method of the base Contextclass。因此,您必须从您的 Activity 或服务访问它。如果您的函数属于一个单独的(非上下文)class,您应该保留对上下文的引用(不良做法)或在您的函数完成后使用 getResources(),例如,在回调中,在上下文中。

如果它是一个片段,这就是为我解决问题的方法:

getActivity.getString(R.string.string_name);

但是如果它是 activity 你可以使用:

this.getString(R.string.string_name);

最后,您可以在适配器中执行以下操作:

getContext().getResources().getString(R.string.string_name);