I have a task to create a file and send it by email through a mail application. I have fileProvider in AndroidManifest.xml
<application
... >
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.test.example.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>
...
</application>
I also added paths to provider_paths is
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external-path"
path="."/>
<external-files-path
name="external-files-path"
path="."/>
<files-path
name="files_path"
path="."/>
</paths>
Then I create a file and give it through the URI. Next, I create an intent to send a letter via email
suspend fun collectLogsToFile(): Uri {
val logcatFile = File(context.filesDir, "logcat.log")
withContext(Dispatchers.IO) { BufferedOutputStream(FileOutputStream(logcatFile.path)).use { stream ->
stream.write("test".toByteArray())
}
}
if (!logcatFile.exists()) {
withContext(Dispatchers.IO) {
logcatFile.createNewFile()
}
}
return FileProvider.getUriForFile(
context,
"com.test.example.fileprovider",
logcatFile
)
}
private suspend fun createEmailIntent(): Intent {
val logFileUri = collectLogsToFile()
return Intent(Intent.ACTION_SENDTO).apply {
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
data = Uri.parse("mailto:")
putExtra(
Intent.EXTRA_EMAIL,
arrayOf(DEVELOPERS_EMAIL)
)
putExtra(
Intent.EXTRA_TEXT,
"text"
)
putExtra(
Intent.EXTRA_SUBJECT,
"subject"
)
putExtra(
Intent.EXTRA_STREAM,
logFileUri
)
}
}
but I, when I open the Google mail app or another mail app, I get error:
E Failed to find provider info for com.test.example.fileprovider
E ComposeActivity: Error adding attachment [CONTEXT
geq: FileNotFoundException when openAssetFileDescriptor.
at fyx.f(PG:28)
at gmz.I(PG:4)
at gll.run(PG:59)
at gmz.at(PG:31)
at gmz.as(Unknown Source:6)
at fyz.a(PG:86)
at aswv.c(PG:2)
at aswx.run(PG:9)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:462)
at aqkz.run(PG:3)
at airh.run(PG:81)
at aqjm.run(PG:29)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8653)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
Caused by: java.io.FileNotFoundException: No content provider:
content://com.test.example.fileprovider/files_path/logcat.log
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1979)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1808)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1724)
at fyx.f(PG:23)
at gmz.I(PG:4)
at gll.run(PG:59)
at gmz.at(PG:31)
at gmz.as(Unknown Source:6)
at fyz.a(PG:86)
at aswv.c(PG:2)
at aswx.run(PG:9)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:462)
at aqkz.run(PG:3)
at airh.run(PG:81)
at aqjm.run(PG:29)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8653)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
But I always get the fileContentProvider error. Tell me, please, what am I doing wrong? I was looking for a lot of similar questions and did. as I seem to think correctly
What am I doing wrong? Thanks
Related
I'm working on a Xamarin.Form App (Android and iOs) which need to get AAID and IDFA.
I started with Android part, I implemented AdvertisingIdClient.GetAdvertisingIdInfo but this function return Timeout error (about after 10s)
I use DependencyService from Form to get AAID from Android project and I compile with Android 11.0
I followed internet examples to achieve it but I'm quite sure I missed something or did something wrong, but what?
What I did :
Added nuget Xamarin.GooglePlayServices.Ads (120.3.0.3) and Xamarin.GooglePlayServices.Basement (117.6.0.4), should be latest compliant with Android 11
Created Interface for dependency service and Created cs in Android project
In Form I call my Dependencyservice function using Task.Run to run i in background (not sure it's the rigth way, but function run, otherwise function raise an error)
IDeviceAdIdentifier service = DependencyService.Get<IDeviceAdIdentifier>();
var tadid = Task.Run(() =>
{
var t = service.GetAdvertisingIdentifier();
t.Wait();
return t.Result;
});
tadid.Wait();
Idfa = tadid.Result;
In Android I save Context from MainActivity
In Android Service I have :
[assembly: Dependency(typeof(TestAdId.Droid.Services.DeviceAdIdentifier))]
namespace TestAdId.Droid.Services
{
public class DeviceAdIdentifier : TestAdId.Services.IDeviceAdIdentifier
{
public async Task<string> GetAdvertisingIdentifier()
{
if (MainActivity.Context == null) return "";
string id = "";
try
{
AdvertisingIdClient.SetShouldSkipGmsCoreVersionCheck(true);
var adinfo = AdvertisingIdClient.GetAdvertisingIdInfo(MainActivity.Instance); // Also tested with MainActivity.Context which is Application context saved during init
if (adinfo != null)
return adinfo.Id;
}
catch (IOException ioerr)
{
return ioerr.Message;
}
catch (Exception err)
{
return err.Message;
}
return "";
}
}
}
In my manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.testadid" android:installLocation="auto">
<uses-sdk android:minSdkVersion="25" android:targetSdkVersion="30" />
<application android:label="TestAdId.Android" android:theme="#style/MainTheme" android:icon="#drawable/xamarin_logo">
<meta-data android:name="com.google.android.gms.ads.AD_MANAGER_APP" android:value="true" />
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
The error raised on my Samsung Galaxy A71 is :
Message : java.util.concurrent.TimeoutException: Timed out waiting for the service connection
StackTrace :
at Java.Interop.JniPeerMembers+JniStaticMethods.InvokeObjectMethod (System.String encodedMember, Java.Interop.JniArgumentValue* parameters) [0x00018] in <1921523bc22e407fa9a0855bdae29335>:0
at Google.Ads.Identifier.AdvertisingIdClient.GetAdvertisingIdInfo (Android.Content.Context context) [0x00027] in /Users/runner/work/1/s/generated/com.google.android.gms.play-services-ads-identifier/obj/Release/monoandroid90/generated/src/Google.Ads.Identifier.AdvertisingIdClient.cs:171
at TestAdId.Droid.Services.DeviceAdIdentifier.GetAdvertisingIdentifier () [0x00032] in C:\Working\Digital\Sources\TestAdId\TestAdId\TestAdId.Android\Services\DeviceAdIdentifier.cs:30
--- End of managed Java.IO.IOException stack trace ---
java.io.IOException: java.util.concurrent.TimeoutException: Timed out waiting for the service connection
at com.google.android.gms.ads.identifier.AdvertisingIdClient.zzb(com.google.android.gms:play-services-ads-identifier##17.0.1:16)
at com.google.android.gms.ads.identifier.AdvertisingIdClient.getAdvertisingIdInfo(com.google.android.gms:play-services-ads-identifier##17.0.1:3)
Caused by: java.util.concurrent.TimeoutException: Timed out waiting for the service connection
at com.google.android.gms.common.BlockingServiceConnection.getServiceWithTimeout(com.google.android.gms:play-services-basement##17.6.0:4)
at com.google.android.gms.ads.identifier.AdvertisingIdClient.zzb(com.google.android.gms:play-services-ads-identifier##17.0.1:14)
... 1 more
I tested an application to retrieve AAID and it works on my phone.
So if someone can help me it will be great. Tell me if you need more information/code
Thanks
Hervé
It's just a POC so nothing really special in MainActivity. I created a standard xamarin.Forms project and put my code in about page in a button
Android MainActivity.cs
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.OS;
using Android.Content;
namespace TestAdId.Droid
{
[Activity(Label = "TestAdId", Icon = "#mipmap/icon", Theme = "#style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
public static Context Context =null;
public static MainActivity Instance = null;
protected override void OnCreate(Bundle savedInstanceState)
{
Instance = this;
base.OnCreate(savedInstanceState);
Context = Android.App.Application.Context;
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
The About Screen xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="TestAdId.Views.AboutPage"
xmlns:vm="clr-namespace:TestAdId.ViewModels"
Title="{Binding Title}">
<ContentPage.BindingContext>
<vm:AboutViewModel />
</ContentPage.BindingContext>
<ContentPage.Resources>
<ResourceDictionary>
<Color x:Key="Accent">#96d1ff</Color>
</ResourceDictionary>
</ContentPage.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackLayout BackgroundColor="{StaticResource Accent}" VerticalOptions="FillAndExpand" HorizontalOptions="Fill">
<StackLayout Orientation="Horizontal" HorizontalOptions="Center" VerticalOptions="Center">
<ContentView Padding="0,40,0,40" VerticalOptions="FillAndExpand">
<Image Source="xamarin_logo.png" VerticalOptions="Center" HeightRequest="64" />
</ContentView>
</StackLayout>
</StackLayout>
<ScrollView Grid.Row="1">
<StackLayout Orientation="Vertical" Padding="30,24,30,24" Spacing="10">
<Label Text="Start developing now" FontSize="Title"/>
<Label Text="Make changes to your XAML file and save to see your UI update in the running app with XAML Hot Reload. Give it a try!" FontSize="16" Padding="0,0,0,0"/>
<Label FontSize="16" Padding="0,24,0,0">
<Label.FormattedText>
<FormattedString>
<FormattedString.Spans>
<Span Text="Learn more at "/>
<Span Text="https://aka.ms/xamarin-quickstart" FontAttributes="Bold"/>
</FormattedString.Spans>
</FormattedString>
</Label.FormattedText>
</Label>
<Label x:Name="IdfaLabel" Text="Unknown" TextColor="Black" FontSize="16" ></Label>
<Button Margin="0,10,0,0" Text="Get IDFA"
Clicked="Button_Clicked"
BackgroundColor="{StaticResource Primary}"
TextColor="White" />
</StackLayout>
</ScrollView>
</Grid>
</ContentPage>
The About Form Code
using System;
using System.ComponentModel;
using System.Threading.Tasks;
using TestAdId.Services;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using System.Net;
namespace TestAdId.Views
{
public partial class AboutPage : ContentPage
{
public string Idfa = "";
public AboutPage()
{
InitializeComponent();
}
private void Button_Clicked(object sender, EventArgs e)
{
IdfaLabel.Text = "Getting IDFA...";
IDeviceAdIdentifier service = DependencyService.Get<IDeviceAdIdentifier>();
var tadid = Task.Run(() =>
{
var t = service.GetAdvertisingIdentifier();
t.Wait();
return t.Result;
});
tadid.Wait();
Idfa = tadid.Result;
IdfaLabel.Text = Idfa;
}
}
}```
Tell me if you need another thing. This is a really simple sample just to try to making AAID working
Thanks
Regards
Hervé
please help. i got this error but don't know what is going on. i tried to make a search view in my fragment.
i make this code for menu item
<item
android:id="#+id/action_search"
android:icon="#drawable/ic_search"
android:title="search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView" />
and make this code in my fragment
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
menu?.clear()
inflater?.inflate(R.menu.menu_home, menu)
val searchItem = menu?.findItem(R.id.action_search)
val searchView = MenuItemCompat.getActionView(searchItem) as SearchView
searchView.backgroundColorResource = Color.WHITE
searchView.queryHint = "Search Review Title"
searchView.setOnQueryTextListener(object: SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
presenter.getSearchReviewList(query)
return true
}
override fun onQueryTextChange(query: String?): Boolean {
presenter.getSearchReviewList(query)
return true
}
})
super.onCreateOptionsMenu(menu, inflater)
}
but i got this error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mqa.android.moviereview, PID: 22280
android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
at android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:204)
at android.content.res.Resources.getColor(Resources.java:949)
at android.content.res.Resources.getColor(Resources.java:925)
at org.jetbrains.anko.CustomViewPropertiesKt.setBackgroundColorResource(CustomViewProperties.kt:36)
at com.mqa.android.moviereview.module.fragment.home.HomeFragment.onCreateOptionsMenu(HomeFragment.kt:97)
at android.support.v4.app.Fragment.performCreateOptionsMenu(Fragment.java:2561)
at android.support.v4.app.FragmentManagerImpl.dispatchCreateOptionsMenu(FragmentManager.java:3321)
at android.support.v4.app.FragmentController.dispatchCreateOptionsMenu(FragmentController.java:331)
at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:379)
at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:94)
at android.support.v7.app.AppCompatDelegateImpl$AppCompatWindowCallback.onCreatePanelMenu(AppCompatDelegateImpl.java:2549)
at android.support.v7.app.AppCompatDelegateImpl.preparePanel(AppCompatDelegateImpl.java:1589)
at android.support.v7.app.AppCompatDelegateImpl.doInvalidatePanelMenu(AppCompatDelegateImpl.java:1869)
at android.support.v7.app.AppCompatDelegateImpl$2.run(AppCompatDelegateImpl.java:227)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
please help me what is going on
searchView.backgroundColorResource = Color.WHITE is the problem. You need to set a resource id here but Color.WHITE is a color value, not a resource id. You can try
searchView.backgroundColorResource = android.R.color.white
You're using a Color value, not a resource reference, so you can't use
searchView.backgroundColorResource = Color.WHITE
As an alternative to Henry's answer, you can use the old Java-style method with
searchView.setBackgroundColor(Color.WHITE)
Use
getApplicationContext().getColor(R.color.white);
And put your color values in xml file, such as
res/values/colors.xml
looking like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="white">#ffffff</color>
//other colors...
</resources>
I am using NoNonsense-FilePicker for filtering the sd card for pdf files by extending the FilePickerActivity and creating a FilteredFilePickerFragment instance through it but i get an error related to an Image button in it's resources.
this is the File Picker Fragment Extender:
public class FilePickerFragmentExtender extends FilePickerActivity {
public FilePickerFragmentExtender() {
super();
}
#Override
protected AbstractFilePickerFragment<File> getFragment(#Nullable String startPath, int mode, boolean allowMultiple, boolean allowCreateDir, boolean allowExistingFile, boolean singleClick) {
AbstractFilePickerFragment<File> fragment = new FilteredFilePickerFragment();
// startPath is allowed to be null. In that case, default folder should be SD-card and not "/"
fragment.setArgs(startPath != null ? startPath : Environment.getExternalStorageDirectory().getPath(),
mode, allowMultiple, allowCreateDir, allowExistingFile, singleClick);
return fragment;
}
}
and this is the Filtered File Picker Fragment:
public class FilteredFilePickerFragment extends FilePickerFragment {
private static final String TAG = "FilteredFilePickerFragm";
// File extension to filter on
private static final String EXTENSION = ".pdf";
public FilteredFilePickerFragment() {
super();
}
/**
* #param file
* #return The file extension. If file has no extension, it returns null.
*/
private String getExtension(#NonNull File file) {
String path = file.getPath();
int i = path.lastIndexOf(".");
if (i < 0) {
return null;
} else {
return path.substring(i);
}
}
#Override
protected boolean isItemVisible(final File file) {
boolean ret = super.isItemVisible(file);
if (ret && !isDir(file) && (mode == MODE_FILE || mode == MODE_FILE_AND_DIR)) {
String ext = getExtension(file);
return ext != null && EXTENSION.equalsIgnoreCase(ext);
}
return ret;
}
}
the error:
FATAL EXCEPTION: main
Process: com.pdfviewer.debug, PID: 15693
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pdfviewer.debug/com.pdfviewer.FilePickerFragmentExtender}: android.view.InflateException: Binary XML file line #90: Binary XML file line #90: Error inflating class ImageButton
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2684)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6186)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Caused by: android.view.InflateException: Binary XML file line #90: Binary XML file line #90: Error inflating class ImageButton
Caused by: android.view.InflateException: Binary XML file line #90: Error inflating class ImageButton
Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 5: TypedValue{t=0x2/d=0x7f010031 a=-1}
at android.content.res.TypedArray.getColorStateList(TypedArray.java:528)
at android.widget.ImageView.<init>(ImageView.java:180)
at android.widget.ImageButton.<init>(ImageButton.java:84)
at android.widget.ImageButton.<init>(ImageButton.java:80)
at android.support.v7.widget.AppCompatImageButton.<init>(AppCompatImageButton.java:60)
at android.support.v7.widget.AppCompatImageButton.<init>(AppCompatImageButton.java:56)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:118)
at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1026)
at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1083)
at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:192)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:769)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:861)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:861)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
at com.nononsenseapps.filepicker.AbstractFilePickerFragment.inflateRootView(AbstractFilePickerFragment.java:239)
at com.nononsenseapps.filepicker.AbstractFilePickerFragment.onCreateView(AbstractFilePickerFragment.java:165)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2239)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1332)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1574)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1641)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:794)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2415)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2200)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2153)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2063)
at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:388)
com.pdfviewer.debug E/AndroidRuntime: at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:554)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1249)
at android.app.Activity.performStart(Activity.java:6701)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2647)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6186)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
I searched and found that it's related to the theme of the file-picker but also i didn't find anything wrong in the theme:
<style name="FilePickerTheme" parent="NNF_BaseTheme">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<!-- Setting a divider is entirely optional -->
<item name="nnf_list_item_divider">?android:attr/listDivider</item>
<!-- Need to set this also to style create folder dialog -->
<item name="alertDialogTheme">#style/FilePickerAlertDialogTheme</item>
</style>
<style name="FilePickerAlertDialogTheme" parent="Theme.AppCompat.Dialog.Alert">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
colorss.xml:
<color name="colorPrimary">#3f51b5</color>
<color name="colorPrimaryDark">#303f9f</color>
<color name="colorAccent">#5495fd</color>
The problem was actually related to the theme I am applying to the parent activity of this fragment android:theme="#style/AppTheme" was causing the app to crash because the layout wasn't finding it's appropriate attributes and debugging xml is kinda tricky.
The ImageButton in the resources:
<ImageButton
android:id="#+id/nnf_button_ok_newfile"
// this style line is the cause
style="?attr/borderlessButtonStyle"
android:layout_width="48dp"
android:layout_height="48dp"
android:hint="#android:string/ok"
app:srcCompat="#drawable/nnf_ic_save_black_24dp"
android:tint="?attr/nnf_save_icon_color"/>
and the solution to this problem was to either change your Activity theme in the manifest to android:theme="#style/FilePickerTheme" which is bad for user experience to user different themes between activities, or the other solution which is to Override the onCreate method and set the theme before the creation of the activity happens as follows:
FilteredFilePickerFragment
#Override
public void onCreate(Bundle savedInstanceState) {
getActivity().setTheme(R.style.FilePickerTheme);
super.onCreate(savedInstanceState);
}
Just getting into the Glide image loading library for Android.
Working with code from here: https://github.com/bumptech/glide/issues/459
Full project here:
https://github.com/mhurwicz/glide02
I'm getting the following exception when I run the app in the emulator in Android Studio:
java.lang.IllegalArgumentException: Failed to find configured root that contains /data/data/com.example.glide02/cache/image_manager_disk_cache/5a992029460eed14244e8b970d969d45518b2f7ac10f71eb26bd0aaf7c3bcf06.0
The rest of the messages are:
at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:711)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:400)
at com.example.glide02.ShareTask.onPostExecute(ShareTask.java:37)
at com.example.glide02.ShareTask.onPostExecute(ShareTask.java:15)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
The error occurs on FileProvider.getUriForFile()
#Override protected void onPostExecute(File result) {
if (result == null) { return; }
Uri uri = FileProvider.getUriForFile(context, context.getPackageName(), result);
share(uri); // startActivity probably needs UI thread
}
I've looked at several other questions relating to this error, but can't see how they relate to my case, perhaps due to my lack of familiarity with this whole area.
Any help will be greatly appreciated.
This is the full code for the class in which the above method occurs:
class ShareTask extends AsyncTask<String, Void, File> {
private final Context context;
public ShareTask(Context context) {
this.context = context;
}
#Override protected File doInBackground(String... params) {
String url = params[0]; // should be easy to extend to share multiple images at once
try {
return Glide
.with(context)
.load(url)
.downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.get() // needs to be called on background thread
;
} catch (Exception ex) {
Log.w("SHARE", "Sharing " + url + " failed", ex);
return null;
}
}
#Override protected void onPostExecute(File result) {
if (result == null) { return; }
Uri uri = FileProvider.getUriForFile(context, context.getPackageName(), result);
share(uri); // startActivity probably needs UI thread
}
private void share(Uri result) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_SUBJECT, "Shared image");
intent.putExtra(Intent.EXTRA_TEXT, "Look what I found!");
intent.putExtra(Intent.EXTRA_STREAM, result);
context.startActivity(Intent.createChooser(intent, "Share image"));
}
}
In my case, this was the solution in filepath.xml
<paths>
<root-path name="root" path="." />
</paths>
In filepaths.xml you need
<cache-path name="shared_images_from_glide_cache" path="image_manager_disk_cache"/>
This will result in mapping
new File("/data/data/com.example.glide02/cache/image_manager_disk_cache/5a992029460eed14244e8b970d969d45518b2f7ac10f71eb26bd0aaf7c3bcf06.0")
to
Uri.parse("content://com.example.glide02/shared_images_from_glide_cache/5a992029460eed14244e8b970d969d45518b2f7ac10f71eb26bd0aaf7c3bcf06.0")
(Not sure if I got it exactly right, but you should get the point.)
When I was trying to get Uri for the file stored in an external SD card, I was getting this error. but when I do the same set of operations with files stored in internal storage, it worked fine. In my case making the below-mentioned changes in the resource file which is #xml/file_path(you can check yours under meta-data tag of the provider in the manifest.)
//adding the below line will give you a warning saying that Element root-path is not allowed here
//but you can ignore that.
<paths>
<root-path name="root" path="." />
</paths
The below code is for reference.
//#xml/file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="files" path="." />
<external-files-path name="external_files" path="." />
<external-path name="external_files" path="." />
<cache-path name="cached_files" path="." />
<external-cache-path name="cached_files" path="." />
<root-path name="root" path="." />
</paths>
//My provider in Manifest.xml
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
Tested with android 11, 10 and 7
I am new at nativescript and developing programs about a few months. I got same error and I am using radList view and Web image cache plugins. We got an api for sending products and their images and images about 500kb. And I am making tab from their categories and in category i am making a list view for each category and listing products inside it. My code like that;
var tabView = page.getViewById("tabViewContainer");
var meal_list = config.meal_list;
meal_list.forEach(function (item) {
var items = new observable_array_1.ObservableArray();
item.meal_list.forEach(function (item2) {
items.push(new DataItemWithImage(item2.meal_id, item2.meal_name, item2.meal_cost,"http://sezginserpen.com.tr/test_image/" + item2.meal_id + ".jpg"));
// items.push(new DataItemWithImage(item2.meal_id, item2.meal_name, item2.meal_cost,"http://pngimg.com/upload/pizza_PNG7132.png"));
});
var wrapLayout = new wrapLayoutModule.WrapLayout();
var radListView = new listViewModule.RadListView();
var layoutBase = new listViewModule.ListViewGridLayout();
layoutBase.scrollDirection = "Vertical";
layoutBase.spanCount = 2;
wrapLayout.className = "item";
wrapLayout.orientation = "horizontal";
radListView.listViewLayout = layoutBase;
radListView.items = items;//<IC:WebImage stretch="fill" height="250" class="my-image-1" src="{{ image }}></IC:WebImage>
radListView.itemTemplate = '<Border xmlns:IC="nativescript-web-image-cache" borderWidth="0.5" borderColor="lightgray"><stack-layout orientation="vertical" height="250" ><IC:WebImage horizontalAlignment="center" src="{{ image }}"></IC:WebImage><stack-layout width="100%" height="50%"> <label id="product_id_label" text="{{ id }}" style="visibility: collapsed" /><label class="align_center product_label" textWrap="true" text="{{ itemName }}" /> <label class="align_center product_label" textWrap="true" style="color:lightgray" text="{{ itemDescription }}" /> <Border borderWidth="1" borderColor="green" borderRadius="2" style="height:22%;width:95%"> <label tap="add_to_basket" class="align_center" style="background-color:white;color:green;" text="Sepete Ekle" /> </Border> </stack-layout> </stack-layout> </Border>';
wrapLayout.addChild(radListView);
var tabViewItem = new tabViewModule.TabViewItem();
tabViewItem.title = item.category.category_name,
tabViewItem.view = wrapLayout;
var tabView = page.getViewById("tabViewContainer");
tabView.items.push(tabViewItem);
});
AND XML like;
<drawer:rad-side-drawer id="drawer">
<drawer:rad-side-drawer.mainContent>
<!-- Home page contents -->
<stack-layout loaded="contentLoaded">
<TabView id="tabViewContainer" selectedIndex="{{ index }}" selectedColor="#d43b2b" selectedIndexChanged="change" tabsBackgroundColor="#ffffff" >
<TabView.items>
</TabView.items>
</TabView>
</stack-layout>
</drawer:rad-side-drawer.mainContent>
<drawer:rad-side-drawer.drawerContent>
<widgets:drawer-content />
</drawer:rad-side-drawer.drawerContent>
</drawer:rad-side-drawer>
Any idea for what causing this ? And I am using ımagecache but every time got this. And one of my Stack Trace1:
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)Caused by: java.lang.OutOfMemoryError: Failed to allocate a 14745612 byte allocation with 12939040 free bytes and 12MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeByteArray(Native Method)
at android.graphics.BitmapFactory.decodeByteArray(BitmapFactory.java:763)
at org.nativescript.widgets.Async$Http$RequestResult.readResponseStream(Async.java:225)
at org.nativescript.widgets.Async$Http$HttpRequestTask.doInBackground(Async.java:303)
at org.nativescript.widgets.Async$Http$HttpRequestTask.doInBackground(Async.java:253)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
... 3 more
Trace2:
java.lang.OutOfMemoryError: Failed to allocate a 1508364 byte allocation with 301952 free bytes and 294KB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.Bitmap.nativeCreate(Native Method)
at android.graphics.Bitmap.createBitmap(Bitmap.java:975)
at android.graphics.Bitmap.createBitmap(Bitmap.java:946)
at android.graphics.Bitmap.createBitmap(Bitmap.java:913)
at com.facebook.imagepipeline.memory.BitmapPool.alloc(BitmapPool.java:55)
at com.facebook.imagepipeline.memory.BitmapPool.alloc(BitmapPool.java:30)
at com.facebook.imagepipeline.memory.BasePool.get(BasePool.java:259)
at com.facebook.imagepipeline.platform.ArtDecoder.decodeStaticImageFromStream(ArtDecoder.java:137)
at com.facebook.imagepipeline.platform.ArtDecoder.decodeFromEncodedImage(ArtDecoder.java:81)
at com.facebook.imagepipeline.decoder.ImageDecoder.decodeStaticImage(ImageDecoder.java:128)
at com.facebook.imagepipeline.decoder.ImageDecoder.decodeImage(ImageDecoder.java:94)
at com.facebook.imagepipeline.producers.DecodeProducer$ProgressiveDecoder.doDecode(DecodeProducer.java:194)
at com.facebook.imagepipeline.producers.DecodeProducer$ProgressiveDecoder.access$200(DecodeProducer.java:97)
at com.facebook.imagepipeline.producers.DecodeProducer$ProgressiveDecoder$1.run(DecodeProducer.java:129)
at com.facebook.imagepipeline.producers.JobScheduler.doJob(JobScheduler.java:207)
at com.facebook.imagepipeline.producers.JobScheduler.access$000(JobScheduler.java:27)
at com.facebook.imagepipeline.producers.JobScheduler$1.run(JobScheduler.java:78)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at com.facebook.imagepipeline.core.PriorityThreadFactory$1.run(PriorityThreadFactory.java:43)
at java.lang.Thread.run(Thread.java:818)
This one is another and does not about this eror types but i got this too :
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.bringToFront()' on a null object reference
at com.telerik.android.primitives.widget.sidedrawer.transitions.DrawerTransitionBase.setProgress(DrawerTransitionBase.java:77)
at com.telerik.android.primitives.widget.sidedrawer.transitions.DrawerTransitionBase.onEnded(DrawerTransitionBase.java:226)
at com.telerik.android.primitives.widget.sidedrawer.transitions.DrawerTransitionBase.run(DrawerTransitionBase.java:221)
at android.view.ViewPropertyAnimator$AnimatorEventListener.onAnimationEnd(ViewPropertyAnimator.java:1119)
at android.animation.ValueAnimator.endAnimation(ValueAnimator.java:1239)
at android.animation.ValueAnimator$AnimationHandler.doAnimationFrame(ValueAnimator.java:766)
at android.animation.ValueAnimator$AnimationHandler$1.run(ValueAnimator.java:801)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:920)
at android.view.Choreographer.doCallbacks(Choreographer.java:695)
at android.view.Choreographer.doFrame(Choreographer.java:628)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:906)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
And any idea About how can I catch this types of Error??
Thank you for your helps.
The below-attached example shows, how you could remove tabs from TabView in NativeScirpt for both iOS and Android.
main-page.xml
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo">
<TabView id="tabViewContainer" loaded="tabviewLoaded">
<TabView.items>
<TabViewItem title="">
<TabViewItem.view>
<Label text="This is Label in Tab 1" />
</TabViewItem.view>
</TabViewItem>
<TabViewItem title="">
<TabViewItem.view>
<Label text="This is Label in Tab 2" />
</TabViewItem.view>
</TabViewItem>
</TabView.items>
</TabView>
</Page>
main-page.ts
import { EventData } from "data/observable";
import { Page } from "ui/page";
import {TabView} from "ui/tab-view";
import {isAndroid, isIOS} from "platform"
export function tabviewLoaded(args:EventData){
var tabview =<any> args.object;
if(isAndroid){
var tabViewgrid = tabview._grid;
console.dump(tabViewgrid.removeViewAt(0));
}
if(isIOS){
tabview._ios.tabBar.hidden = true;
}
}
main-page.js
var platform_1 = require("platform");
function tabviewLoaded(args) {
var tabview = args.object;
if (platform_1.isAndroid) {
var tabViewgrid = tabview._grid;
console.dump(tabViewgrid.removeViewAt(0));
}
if (platform_1.isIOS) {
tabview._ios.tabBar.hidden = true;
}
}
exports.tabviewLoaded = tabviewLoaded;