在Android Studio中的onRequestPermission / onActivityResult中出现错误。

huangapple go评论112阅读模式
英文:

Error with onRequestPermission / onActivityResult Android Studio

问题

我在Android Studio中的应用程序中遇到了错误请检查我的代码btnChoose不起作用...
当我按下按钮时会询问访问手机图库的权限但不会进入手机图库选择图像请帮忙谢谢

主要的Java代码 - MainFragment

package com.example.licenta23;

// 导入其他需要的库

public class MainFragment extends Fragment {

    // 其他代码...

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);

        // 初始化其他视图和组件

        // 请求读取外部存储的权限
        btnChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
                    return;

                for (String permission : permissions) {
                    if (ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED) {
                        requestPermissions(permissions, REQUEST_CODE_GALLERY); // 在每次授予权限时触发onRequestPermissionsResult()
                    } else {
                        Toast.makeText(getActivity(), "权限已经被授予", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        // 其他代码...

        return view;
    }

    // 其他方法...
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == REQUEST_CODE_GALLERY) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_CODE_GALLERY);
        } else {
            Toast.makeText(getActivity().getApplicationContext(), "您没有访问文件位置的权限!", Toast.LENGTH_SHORT).show();
        }
        return;
    }

    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE_GALLERY && resultCode == getActivity().RESULT_OK && data != null) {
        Uri uri = data.getData();

        try {
            InputStream inputStream = getActivity().getApplicationContext().getContentResolver().openInputStream(uri);

            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            imageView3.setImageBitmap(bitmap);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    super.onActivityResult(requestCode, resultCode, data);
}

更新部分已添加到代码中,以确保在请求权限后触发onRequestPermissionsResult并在权限被授予后执行相应的操作。希望这能帮助你解决问题。如果你还有其他问题,请随时问我。

英文:

I have a error at my application in Android Studio. Please check my code! btnChoose doesn't work...
When I press the button, ask for permission to access the phone gallery, but don t enter the phone gallery to choose the image. Please help me! Thanks!

Main java code - MainFragment:

package com.example.licenta23;
import android.Manifest;
import android.app.AppComponentFactory;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class MainFragment extends Fragment {
private static final String[] CAROSERIE = new String[] {
&quot;Cabrio&quot;, &quot;Berlina&quot;, &quot;Coupe&quot;, &quot;Pick-up&quot;, &quot;Hatchback&quot;, &quot;Break&quot;, &quot;Off-road&quot;, &quot;Minibus&quot;, &quot;Monovolum&quot;, &quot;SUV&quot;
};
private static final String[] COMBUSTIBIL = new String[] {
&quot;Benzina&quot;, &quot;Diesel&quot;, &quot;GPL&quot;, &quot;Electric&quot;, &quot;Hibrid&quot;
};
private static final String[] CULOARE = new String[] {
&quot;Alb&quot;, &quot;Negru&quot;, &quot;Gri&quot;, &quot;Argintiu&quot;, &quot;Albastru&quot;, &quot;Rosu&quot;, &quot;Verde&quot;, &quot;Auriu&quot;, &quot;Galben&quot;, &quot;Portocaliu&quot;, &quot;Maro&quot;, &quot;Bej&quot;, &quot;Alta culoare&quot;
};
private List&lt;MarcaItem&gt; marcaList;
EditText actv1, edtModel, actv2, actv3, actv4, edtFabricatie, edtPret;
Button btnChoose, btnAdd, btnList;
ImageView imageView3;
final int REQUEST_CODE_GALLERY = 999;
public static SQLiteHelper sqLiteHelper;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
fillMarcaList();
AutoCompleteTextView editText = view.findViewById(R.id.actv1);
AutoCompleteMarcaAdapter adapter = new AutoCompleteMarcaAdapter(getActivity(), marcaList);
editText.setAdapter(adapter);
AutoCompleteTextView editText2 = view.findViewById(R.id.actv2);
ArrayAdapter&lt;String&gt; adapter2 = new ArrayAdapter&lt;String&gt;(getActivity(),
android.R.layout.simple_list_item_1, CAROSERIE);
editText2.setAdapter(adapter2);
AutoCompleteTextView editText3 = view.findViewById(R.id.actv3);
ArrayAdapter&lt;String&gt; adapter3 = new ArrayAdapter&lt;String&gt;(getActivity(),
android.R.layout.simple_list_item_1, COMBUSTIBIL);
editText3.setAdapter(adapter3);
AutoCompleteTextView editText4 = view.findViewById(R.id.actv4);
ArrayAdapter&lt;String&gt; adapter4 = new ArrayAdapter&lt;String&gt;(getActivity(),
android.R.layout.simple_list_item_1, CULOARE);
editText4.setAdapter(adapter4);
init(view);
sqLiteHelper = new SQLiteHelper(getActivity(),&quot;CarDB.sqlite&quot;, null, 1);
sqLiteHelper.queryData(&quot;CREATE TABLE IF NOT EXISTS CAR (Id INTEGER PRIMARY KEY AUTOINCREMENT, alegemarca VARCHAR, model VARCHAR, caroserie VARCHAR, combustibil VARCHAR, culoare VARCHAR, fabricatie VARCHAR, pret VARCHAR, image BLOG)&quot;);
btnChoose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ActivityCompat.requestPermissions(
getActivity(),
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_GALLERY
);
}
});
return view;
}
private void fillMarcaList() {
marcaList = new ArrayList&lt;&gt;();
marcaList.add(new MarcaItem(&quot;Alfa Romeo&quot;, R.drawable.alfa_romeo));
marcaList.add(new MarcaItem(&quot;Audi&quot;, R.drawable.audi));
marcaList.add(new MarcaItem(&quot;Bmw&quot;, R.drawable.bmw));
marcaList.add(new MarcaItem(&quot;Chevrolet&quot;, R.drawable.chevrole));
marcaList.add(new MarcaItem(&quot;Citroen&quot;, R.drawable.citroen));
marcaList.add(new MarcaItem(&quot;Dacia&quot;, R.drawable.dacia));
marcaList.add(new MarcaItem(&quot;Dodge&quot;, R.drawable.dodge));
marcaList.add(new MarcaItem(&quot;Fiat&quot;, R.drawable.fiat));
marcaList.add(new MarcaItem(&quot;Ford&quot;, R.drawable.ford));
marcaList.add(new MarcaItem(&quot;Honda&quot;, R.drawable.honda));
marcaList.add(new MarcaItem(&quot;Hyundai&quot;, R.drawable.hyundai));
marcaList.add(new MarcaItem(&quot;Jaguar&quot;, R.drawable.jaguar));
marcaList.add(new MarcaItem(&quot;Jeep&quot;, R.drawable.jeep));
marcaList.add(new MarcaItem(&quot;Kia&quot;, R.drawable.kia));
marcaList.add(new MarcaItem(&quot;Land Rover&quot;, R.drawable.landrover));
marcaList.add(new MarcaItem(&quot;Lexus&quot;, R.drawable.lexus));
marcaList.add(new MarcaItem(&quot;Mazda&quot;, R.drawable.mazda));
marcaList.add(new MarcaItem(&quot;Mercedes-Benz&quot;, R.drawable.mercedes));
marcaList.add(new MarcaItem(&quot;Mini Cooper&quot;, R.drawable.minicooper));
marcaList.add(new MarcaItem(&quot;Mitsubishi&quot;, R.drawable.mitsubishi));
marcaList.add(new MarcaItem(&quot;Nissan&quot;, R.drawable.nissan));
marcaList.add(new MarcaItem(&quot;Opel&quot;, R.drawable.opel));
marcaList.add(new MarcaItem(&quot;Peugeot&quot;, R.drawable.peugeot));
marcaList.add(new MarcaItem(&quot;Pontiac&quot;, R.drawable.pontiac));
marcaList.add(new MarcaItem(&quot;Porche&quot;, R.drawable.porche));
marcaList.add(new MarcaItem(&quot;Renault&quot;, R.drawable.renault));
marcaList.add(new MarcaItem(&quot;Rover&quot;, R.drawable.rover));
marcaList.add(new MarcaItem(&quot;Seat&quot;, R.drawable.seat));
marcaList.add(new MarcaItem(&quot;Skoda&quot;, R.drawable.skoda));
marcaList.add(new MarcaItem(&quot;Smart&quot;, R.drawable.smart));
marcaList.add(new MarcaItem(&quot;Subaru&quot;, R.drawable.subaru));
marcaList.add(new MarcaItem(&quot;Suzuki&quot;, R.drawable.suzuki));
marcaList.add(new MarcaItem(&quot;Toyota&quot;, R.drawable.toyota));
marcaList.add(new MarcaItem(&quot;Voltwagen&quot;, R.drawable.voltwagen));
marcaList.add(new MarcaItem(&quot;Volvo&quot;, R.drawable.volvo));
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if(requestCode == REQUEST_CODE_GALLERY){
if(grantResults.length &gt;0 &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(&quot;image/*&quot;);
startActivityForResult(intent, REQUEST_CODE_GALLERY);
}
else {
Toast.makeText(getActivity().getApplicationContext(), &quot;You don&#39;t have permission to access file location!&quot;, Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE_GALLERY &amp;&amp; resultCode == getActivity().RESULT_OK &amp;&amp; data != null){
Uri uri = data.getData();
try {
InputStream inputStream = getActivity().getApplicationContext().getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageView3.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void init(View view) {
actv1 = view.findViewById(R.id.actv1);
edtModel = view.findViewById(R.id.edtModel);
actv2 = view.findViewById(R.id.actv2);
actv3 = view.findViewById(R.id.actv3);
actv4 = view.findViewById(R.id.actv4);
edtFabricatie = view.findViewById(R.id.edtFabricatie);
edtPret = view.findViewById(R.id.edtPret);
btnChoose = view.findViewById(R.id.btnChoose);
btnAdd = view.findViewById(R.id.btnAdd);
btnList = view.findViewById(R.id.btnList);
imageView3 = view.findViewById(R.id.imageView3);
}

}

Debugger doeesn t give me any error...

UPDATE FOR ZAIN

btnChoose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String[] permissions =  new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT &lt; Build.VERSION_CODES.M)
return;
for (String permission : permissions) {
if (ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(permissions, REQUEST_CODE_GALLERY); // triggers onRequestPermissionsResult() each time a permission is granted in &#39;permissions&#39;
} else {
Toast.makeText(getActivity(), &quot;Permission Already Granted&quot;, Toast.LENGTH_SHORT).show();
}
}
}
});

My code it s ok ?

答案1

得分: 0

我浏览了您的代码,似乎没有问题,而且由于没有引发异常,所以在编程方式获得所需的权限时没有问题;因此,请尝试从清单文件中请求权限,仅仅在编程方式提供权限是不够的。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

更新:

尝试用以下代码片段手动请求权限。

所以移除以下部分:

btnChoose.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        ActivityCompat.requestPermissions(
                getActivity(),
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                REQUEST_CODE_GALLERY
        );
    }
});

并替换为:

btnChoose.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        String[] permissions =  new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
            return;

        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(permissions, code); // 每次在 'permissions' 中授予权限时都会触发 onRequestPermissionsResult()
            } else {
                Toast.makeText(this, "Permission Already Granted", Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, REQUEST_CODE_GALLERY);
            }
        }
    }
});

这是更新后的代码片段,用于手动请求权限。

英文:

I navigated through your code, seems nothing wrong, and as there are no raised exceptions, then no problem getting the needed permission programmatically; So, please try to request the permission from the manifest file as well, it won't work for just providing it programmatically alone

&lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot; /&gt;

Update:

Try to replace below snippet to manually request permission.

So remove below:

    btnChoose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ActivityCompat.requestPermissions(
getActivity(),
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_GALLERY
);
}
});

and Replace it With:

    btnChoose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String[] permissions =  new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT &lt; Build.VERSION_CODES.M)
return;
for (String permission : permissions) {
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(permissions, code); // triggers onRequestPermissionsResult() each time a permission is granted in &#39;permissions&#39;
} else {
Toast.makeText(this, &quot;Permission Already Granted&quot;, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(&quot;image/*&quot;);
startActivityForResult(intent, REQUEST_CODE_GALLERY);
}
}
}
});

答案2

得分: 0

除了你正在从片段中请求权限并在片段中声明回调之外,一切都看起来很好。

但是当用户提示权限并允许/拒绝该权限时,回调首先会进入您的活动上下文,而不是片段上下文。

因此,首先您必须在活动中声明 onRequestPermissionsResult(),然后从活动中将其传递给您的片段,然后在片段的 onRequestPermissionsResult() 将排队等待工作。

对于 onActivityResult() 也要遵循相同的流程。

英文:

everything seems fine except you are requesting permission from fragment and declare call back also in fragment.

But when user prompt for permission and allow/deny that permission, callback first goes to your activity context not your fragment context.

So first of all you have to declare onRequestPermissionsResult() in your activity and from activity you have to pass it to you fragment, and then after your fragment's onRequestPermissionsResult() will be on queue for work.

Follow the same process for onActivityResult() also.

huangapple
  • 本文由 发表于 2020年4月8日 21:12:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/61101559.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定