Как исправить ошибку открытия: EACCES (в доступе отказано)Android

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 Как исправить ошибку открытия: EACCES (в доступе отказано)

Сообщение Anonymous »

я получаю сообщение W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Pictures/JayTN24/mens_shirt_0.jpg: ошибка открытия: EACCES (отказано в доступе) public voidshareWallpaper не делиться
изображение Whatsapp не делится данными, как исправить это разрешение
Как я могу решить эту проблему?
EACCES (В разрешении отказано)
package com.jaytn24.shopping.activities;

import static com.jaytn24.shopping.config.AppConfig.RTL_MODE;
import static com.jaytn24.shopping.utils.Constant.BANNER_RECIPE_DETAIL;
import static com.jaytn24.shopping.utils.Constant.BASE_IMAGE_URL;
import static com.jaytn24.shopping.utils.Constant.DELAY_SET;
import static com.jaytn24.shopping.utils.Constant.INTERSTITIAL_ON_RECIPES_LIST;
import static com.jaytn24.shopping.utils.Constant.NATIVE_AD_RECIPES_DETAIL;
import static com.jaytn24.shopping.utils.Constant.SHARE;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.jaytn24.shopping.R;
import com.jaytn24.shopping.adapters.AdapterImage;
import com.jaytn24.shopping.adapters.AdapterSuggested;
import com.jaytn24.shopping.callbacks.CallbackRecipeDetail;
import com.jaytn24.shopping.callbacks.CallbackUser;
import com.jaytn24.shopping.config.AppConfig;
import com.jaytn24.shopping.databases.prefs.AdsPref;
import com.jaytn24.shopping.databases.prefs.SharedPref;
import com.jaytn24.shopping.databases.sqlite.DbHandler;
import com.jaytn24.shopping.models.Images;
import com.jaytn24.shopping.models.Recipe;
import com.jaytn24.shopping.models.User;
import com.jaytn24.shopping.models.Value;
import com.jaytn24.shopping.rests.ApiInterface;
import com.jaytn24.shopping.rests.RestAdapter;
import com.jaytn24.shopping.utils.AdsManager;
import com.jaytn24.shopping.utils.AppBarLayoutBehavior;
import com.jaytn24.shopping.utils.Constant;
import com.jaytn24.shopping.utils.Tools;
import com.facebook.shimmer.ShimmerFrameLayout;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;
import com.jaytn24.shopping.utils.wallpaperHelper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ActivityRecipeDetail1 extends AppCompatActivity {
ProgressDialog progressDialog;
private long recipe_id;
private Call callbackCall = null;
private LinearLayout lyt_main_content;
private Recipe post;

MyApplication myApplication;
private static final String TAG = "ActivityRecipeDetail1";
Button button8;
TextView txt_recipe_title, txt_category, txt_recipe_time, txt_total_views,txtCommentText,txtCommentCount,price,discountprice;
LinearLayout lyt_view,btnView,btnComment;
ImageView thumbnail_video;
private WebView recipe_description;
DbHandler databaseHandler;
CoordinatorLayout parent_view;
private ShimmerFrameLayout lyt_shimmer;
RelativeLayout lyt_suggested;
private SwipeRefreshLayout swipe_refresh;
SharedPref sharedPref;
ImageButton image_favorite;

public Button btn_share;
ViewPager viewPager;
AdsPref adsPref;
AdsManager adsManager;
Call callbackCall2 = null;
User user;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Tools.getTheme(this);
setContentView(R.layout.activity_recipe_detail1);
Tools.getLayoutDirections(this, RTL_MODE);
myApplication = MyApplication.getInstance();
progressDialog = new ProgressDialog(this);

price = findViewById(R.id.price);
discountprice = findViewById(R.id.discountprice);

button8 = (Button) findViewById(R.id.button8);
sharedPref = new SharedPref(this);
adsPref = new AdsPref(this);
databaseHandler = new DbHandler(this);

AppBarLayout appBarLayout = findViewById(R.id.appbar);
((CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams()).setBehavior(new AppBarLayoutBehavior());

adsManager = new AdsManager(this);
adsManager.loadBannerAd(BANNER_RECIPE_DETAIL);
adsManager.loadInterstitialAd(INTERSTITIAL_ON_RECIPES_LIST, adsPref.getInterstitialAdInterval());
adsManager.loadNativeAd(NATIVE_AD_RECIPES_DETAIL);

swipe_refresh = findViewById(R.id.swipe_refresh_layout);
swipe_refresh.setColorSchemeResources(R.color.colorPrimary);
swipe_refresh.setRefreshing(false);
txtCommentText = findViewById(R.id.txt_comment_text);

lyt_main_content = findViewById(R.id.lyt_main_content);
lyt_shimmer = findViewById(R.id.shimmer_view_container);
parent_view = findViewById(R.id.lyt_content);

thumbnail_video = findViewById(R.id.thumbnail_video);
txt_recipe_title = findViewById(R.id.recipe_title);
txt_category = findViewById(R.id.category_name);
txt_recipe_time = findViewById(R.id.recipe_time);
recipe_description = findViewById(R.id.recipe_description);
txt_total_views = findViewById(R.id.total_views);
lyt_view = findViewById(R.id.lyt_view_count);
btnView = findViewById(R.id.btn_view);
image_favorite = findViewById(R.id.img_favorite);
btn_share = findViewById(R.id.Order);
btnComment = findViewById(R.id.btn_comment);

lyt_suggested = findViewById(R.id.lyt_suggested);

post = (Recipe) getIntent().getSerializableExtra(Constant.EXTRA_OBJC);
txtCommentCount = findViewById(R.id.txt_comment_count);

requestAction();

// requestmenu();
requestPostApi2();

btnComment.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), ActivityComments3.class);
intent.putExtra("recipe_id", post.recipe_id);
intent.putExtra("count", post.comments_count);
intent.putExtra("post_title", post.recipe_title);
startActivity(intent);

});

if (!sharedPref.getLoginFeature().equals("yes")) {
btnComment.setVisibility(View.GONE);
txtCommentText.setVisibility(View.GONE);
} else {
btnComment.setVisibility(View.VISIBLE);
txtCommentText.setVisibility(View.VISIBLE);
}

swipe_refresh.setOnRefreshListener(() -> {
lyt_shimmer.setVisibility(View.VISIBLE);
lyt_shimmer.startShimmer();
lyt_main_content.setVisibility(View.GONE);
requestAction();
});

initToolbar();
initFavorite();
loadViewed();

}

private void requestAction() {
showFailedView(false, "");
swipeProgress(true);
new Handler().postDelayed(this::requestPostData, 200);
}

public void displayData(final Recipe post) {
new Handler().postDelayed(() -> {
if (post.comments_count == 0) {
txtCommentText.setText(R.string.txt_no_comment);
}
if (post.comments_count == 1) {
txtCommentText.setText(getResources().getString(R.string.txt_read) + " " + post.comments_count + " " + getResources().getString(R.string.txt_comment));
} else if (post.comments_count > 1) {
txtCommentText.setText(getResources().getString(R.string.txt_read) + " " + post.comments_count + " " + getResources().getString(R.string.txt_comments));
}
}, 1500);
txtCommentCount.setText("" + post.comments_count);

price.setText("₹" +post.price);
discountprice.setText("₹" +post.discountprice);
price.setPaintFlags(price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
button8.setText(post.recipe_time);
txt_recipe_title.setText(post.recipe_title);
txt_recipe_time.setText(post.recipe_time);

if (AppConfig.ENABLE_RECIPES_VIEW_COUNT) {
txt_total_views.setText(Tools.withSuffix(post.total_views) + " " + getResources().getString(R.string.views_count));
} else {
lyt_view.setVisibility(View.GONE);
}

if (post.content_type != null && post.content_type.equals("Post")) {
thumbnail_video.setVisibility(View.GONE);
} else {
thumbnail_video.setVisibility(View.VISIBLE);
}

if (AppConfig.ENABLE_VIEW_COUNT) {
btnView.setVisibility(View.VISIBLE);
txt_total_views.setText("" + Tools.withSuffix(post.total_views));
} else {
btnView.setVisibility(View.GONE);
}

recipe_description.setBackgroundColor(Color.TRANSPARENT);
recipe_description.setFocusableInTouchMode(false);
recipe_description.setFocusable(false);
recipe_description.getSettings().setDefaultTextEncodingName("UTF-8");

WebSettings webSettings = recipe_description.getSettings();
Resources res = getResources();
int fontSize = res.getInteger(R.integer.font_size);
webSettings.setDefaultFontSize(fontSize);

String mimeType = "text/html; charset=UTF-8";
String encoding = "utf-8";
String htmlText = post.recipe_description;

String bg_paragraph;
if (sharedPref.getIsDarkTheme()) {
bg_paragraph = "body{color: #eeeeee;}";
} else {
bg_paragraph = "body{color: #000000;}";
}

String font_style_default = "@font-face {font-family: MyFont;src: url(\"file:///android_asset/font/custom_font.ttf\")}body {font-family: MyFont; font-size: medium; text-align: left;}";

String text = ""
+ font_style_default
+ "img{max-width:100%;height:auto;} figure{max-width:100%;height:auto;} iframe{width:100%;} "
+ bg_paragraph
+ ""
+ ""
+ htmlText
+ "";

String text_rtl = ""
+ font_style_default
+ "img{max-width:100%;height:auto;} figure{max-width:100%;height:auto;} iframe{width:100%;} "
+ bg_paragraph
+ ""
+ ""
+ htmlText
+ "";

if (RTL_MODE) {
recipe_description.loadDataWithBaseURL(null, text_rtl, mimeType, encoding, null);
} else {
recipe_description.loadDataWithBaseURL(null, text, mimeType, encoding, null);
}
addToFavorite();
new Handler().postDelayed(() -> lyt_suggested.setVisibility(View.VISIBLE), 1000);

}

private void displaySuggested(List list) {

RecyclerView recyclerView = findViewById(R.id.recycler_view_suggested);

recyclerView.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));

AdapterSuggested adapterSuggested = new AdapterSuggested(ActivityRecipeDetail1.this, recyclerView, list);
recyclerView.setAdapter(adapterSuggested);
recyclerView.setNestedScrollingEnabled(false);
adapterSuggested.setOnItemClickListener((view, obj, position) -> {
Intent intent = new Intent(getApplicationContext(), ActivityRecipeDetail1.class);
intent.putExtra(Constant.EXTRA_OBJC, obj);
startActivity(intent);
adsManager.showInterstitialAd();
});

TextView txt_suggested = findViewById(R.id.txt_suggested);
if (list.size() > 0) {
txt_suggested.setText(getResources().getString(R.string.txt_suggested));
} else {
txt_suggested.setText("");
}

}

private void initToolbar() {
final Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

if (sharedPref.getIsDarkTheme()) {
toolbar.setBackgroundColor(getResources().getColor(R.color.colorToolbarDark));
} else {
toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
}

final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle("");
}

txt_category.setText(post.category_name);

}

@Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

public void initFavorite() {
List data = databaseHandler.getFavRow(post.recipe_id);
if (data.size() == 0) {
image_favorite.setImageResource(R.drawable.ic_fav_outline);
} else {
if (data.get(0).getRecipe_id() == recipe_id) {
image_favorite.setImageResource(R.drawable.ic_fav);
}
}
}

public void addToFavorite() {

image_favorite.setOnClickListener(view -> {
List data1 = databaseHandler.getFavRow(post.recipe_id);
if (data1.size() == 0) {
databaseHandler.AddtoFavorite(new Recipe(
post.category_name,
post.recipe_id,
post.recipe_title,
post.recipe_time,
post.price,
post.discountprice,
post.recipe_image,
post.recipe_description,
post.video_url,
post.video_id,
post.content_type,
post.featured,
post.tags,
post.total_views
));
Snackbar.make(parent_view, R.string.favorite_added, Snackbar.LENGTH_SHORT).show();
image_favorite.setImageResource(R.drawable.ic_fav);
} else {
if (data1.get(0).getRecipe_id() == recipe_id) {

databaseHandler.RemoveFav(new Recipe(post.recipe_id));
Snackbar.make(parent_view, R.string.favorite_removed, Snackbar.LENGTH_SHORT).show();
image_favorite.setImageResource(R.drawable.ic_fav_outline);
}
}
});

}
private void updateView(long nid) {
ApiInterface apiInterface = RestAdapter.createAPI(sharedPref.getApiUrl());
Call call = apiInterface.updateView1(nid);
call.enqueue(new Callback() {
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) {
Value data = response.body();
if (data != null) {
Log.d(TAG, "View counter updated +" + data.value);
}
}

@Override
public void onFailure(@NonNull Call call, @NonNull Throwable t) {
Log.d(TAG, "error " + t.getMessage());
}
});
}

@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
break;

default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}

private void loadViewed() {
if (Tools.isConnect(this)) {
new MyTask().execute(sharedPref.getApiUrl() + "/api/api.php?get_total_views3&id=" + post.recipe_id);
}
}

@SuppressWarnings("deprecation")
private static class MyTask extends AsyncTask {

@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected String doInBackground(String... params) {
return Tools.getJSONString(params[0]);
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);

if (null == result || result.length() == 0) {
Log.d("TAG", "no data found!");
} else {

try {

JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray("result");
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
}

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

}
}

private void requestPostApi2() {
ApiInterface apiInterface = RestAdapter.createAPI(sharedPref.getApiUrl());
callbackCall2 = apiInterface.getUser(myApplication.getUserId());
callbackCall2.enqueue(new Callback() {
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) {
CallbackUser resp = response.body();
if (resp != null && resp.status.equals("ok")) {
user = resp.response;
sharebutton();
} else {
onFailRequest();
}
}

@Override
public void onFailure(@NonNull Call call, @NonNull Throwable t) {
}

});
}

public void onDestroy() {
if (!(callbackCall == null || callbackCall.isCanceled())) {
this.callbackCall.cancel();
}
lyt_shimmer.stopShimmer();
super.onDestroy();
}

@Override
protected void onResume() {
super.onResume();
}

@Override
protected void onPause() {
super.onPause();
}

private void sharebutton() {
String wallpaperUrl =BASE_IMAGE_URL + post.recipe_image;
String wallpaperName = post.recipe_title.toLowerCase().replace(" ", "_") + "_" + post.id;

btn_share.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick( View view ) {
if (!myApplication.getIsLogin()) {
startActivity(new Intent(getApplicationContext(), ActivityUserLogin.class));

} else {

if (!verifyPermissions()) {
return;
}

shareWallpaper(progressDialog, wallpaperName, wallpaperUrl);
}
}

});
}

public void shareWallpaper(ProgressDialog progressDialog, String imageName, String imageURL) {

progressDialog.setMessage(this.getString(R.string.msg_preparing_wallpaper));
progressDialog.setCancelable(false);
progressDialog.show();

new Handler().postDelayed(() -> Glide.with(this)
.download(imageURL.replace(" ", "%20"))
.listener(new RequestListener() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
progressDialog.dismiss();
return false;
}

@Override
public boolean onResourceReady(File resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
try {

InputStream is = new BufferedInputStream(new FileInputStream(resource));
String mimeType = URLConnection.guessContentTypeFromStream(is);

if (mimeType.equals("image/gif")) {
setAction(this, Tools.getBytesFromFile(resource), Tools.createName(imageName + ".gif"), SHARE);
} else if (mimeType.equals("image/png")) {
Tools.setAction(getApplicationContext(), Tools.getBytesFromFile(resource), Tools.createName(imageName + ".png"), SHARE);
} else {
setAction(this, Tools.getBytesFromFile(resource), Tools.createName(imageName + ".jpg"), SHARE);
}

progressDialog.dismiss();
} catch (IOException e) {
e.printStackTrace();
progressDialog.dismiss();
}
return true;
}
})
.submit(), DELAY_SET);
}

public void setAction( ActivityRecipeDetail1 this, RequestListener requestListener, byte[] bytes, String imgName, String action ) {
try {
File dir;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + this.getString(R.string.app_name));
} else {
dir = new File(Environment.getExternalStorageDirectory() + "/" + this.getString(R.string.app_name));
}
boolean success = true;
if (!dir.exists()) {
success = dir.mkdirs();
}
if (success) {
File imageFile = new File(dir, imgName);
FileOutputStream fileWriter = new FileOutputStream(imageFile);
fileWriter.write(bytes);
fileWriter.flush();
fileWriter.close();

Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File file = new File(imageFile.getAbsolutePath());
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());

switch (action) {

case SHARE:
String share_title = android.text.Html.fromHtml(post.recipe_title).toString();
String share_price = android.text.Html.fromHtml("price:" + post.discountprice).toString();
String share_Address = android.text.Html.fromHtml("Address:" + user.Address).toString();
String share_pincode = android.text.Html.fromHtml("PinCode:" + user.PinCode).toString();
String share_Distict = android.text.Html.fromHtml("State:" + user.State).toString();
String title = share_title + "\n\n" + share_price + "\n\n" + share_Address + "\n\n" + share_pincode + "\n\n" + share_Distict + "\n\n";
String toNumber = "+918072006997"; // contains spaces.
toNumber = toNumber.replace("+", "").replace(" ", "");
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
sendIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
sendIntent.putExtra(Intent.EXTRA_TEXT, title);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setPackage("com.whatsapp");
sendIntent.setType("image/png");
this.startActivity(sendIntent);
break;
}

}

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

}


Подробнее здесь: https://stackoverflow.com/questions/787 ... ion-denied
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Android»