I would like to start an application (example Calculator) on a fragment for example on my application.
I try this code but i get an error (line Fragment):
String packageName = "com.android.calculator2";
Context ctx = getApplicationContext().createPackageContext(packageName, Context.CONTEXT_INCLUDE_CODE |
Context.CONTEXT_IGNORE_SECURITY);
ClassLoader cl = ctx.getClassLoader();
Class<?> c = cl.loadClass("com.android.calculator2.Calculator");
Fragment fragObj = (Fragment)c.newInstance();
i get this error:
Process: fr.jm.managercamera, PID: 14006
java.lang.RuntimeException: Unable to start activity ComponentInfo{fr.jm.managercamera/fr.jm.managercamera.MainActivity}: java.lang.ClassCastException: com.android.calculator2.Calculator cannot be cast to android.app.Fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
I try this code, i get other problem:
Class requiredClass = null;
final String apkPath = getPackageManager().getApplicationInfo("com.android.calculator2",0).sourceDir;
final File dexTemp = getDir("temp_folder", 0);
final String fullName = "com.android.calculator2.Calculator";
boolean isLoaded = true;
// Check if class loaded
try {
requiredClass = Class.forName(fullName);
} catch(ClassNotFoundException e) {
isLoaded = false;
}
if (!isLoaded) {
System.out.println("apkPath: " + apkPath);
System.out.println("dexTemp.getAbsolutePath(): " + dexTemp.getAbsolutePath());
final DexClassLoader classLoader = new DexClassLoader(apkPath,
dexTemp.getAbsolutePath(),
null,
getClass().getClassLoader());
/* DexClassLoader classLoader = new DexClassLoader(apkPath,"/tmp", null,
getClass().getClassLoader());*/
requiredClass = classLoader.loadClass(fullName);
}
I get this error (line loadClass):
10-03 17:50:22.776 14133-14133/? W/System.err: java.lang.ClassNotFoundException: Didn't find class "com.android.calculator2.Calculator" on path: DexPathList[[zip file "/system/app/Calculator/Calculator.apk"],nativeLibraryDirectories=[/vendor/lib64, /system/lib64]]
10-03 17:50:22.776 14133-14133/? W/System.err: at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
10-03 17:50:22.776 14133-14133/? W/System.err: at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
10-03 17:50:22.776 14133-14133/? W/System.err: at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
You can't do that. You can launch the calculator as an Activity, but you cannot load foreign code into your own OS process. That would be a security violation.
The calculator app's code is only allowed to run in the calculator app's OS Process, not in any other OS Process. The Android security model doesn't allow that.
Related
In my Roblectric test, I try to confirm permission dialog with UiDevice
#RunWith(RobolectricTestRunner::class)
#Config(sdk = [Build.VERSION_CODES.P])
open class FooTest {
#Before
private fun before() {
var device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
// Confirm permissions dialog with device object
// ...
}
but this line throws an NPE exception
var device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
with stack trace
java.lang.NullPointerException
at androidx.test.uiautomator.QueryController.<init>(QueryController.java:95)
at androidx.test.uiautomator.UiDevice.<init>(UiDevice.java:109)
at androidx.test.uiautomator.UiDevice.getInstance(UiDevice.java:261)
because UiDevice.getUiAutomation(instrumentation) is returning null
public QueryController(Instrumentation instrumentation) {
mInstrumentation = instrumentation;
UiDevice.getUiAutomation(instrumentation).setOnAccessibilityEventListener(mEventListener);
}
I am able to open the database from within the main app activity using the following code, but once it's wrapped into a singleton object, it keeps throwing a null-object error:
object CommonClass {
fun openSQLDatabase(): SQLiteDatabase? {
var dbase: SQLiteDatabase? = null
try {
dbase = openOrCreateDatabase(
"dbfile.sqlite",
Context.MODE_PRIVATE, null
)
} catch (e: SQLException) {
println(e.message)
}
return dbase
}
}
I'm assuming that the main AppCompatActivity should be passing its context to the object in some way, but I've not been able to find a working model.
to Swayangjit
Android Studio highlights the Context.MODE_PRIVATE parameter and flags it as:
Type mismatch.
Required: SQLiteDatabase.CursorFactory?
Found: Int
But when I implement the AppCompatActivity to the singleton object and pass the Context.MODE_PRIVATE from the main activity, it runs but throws this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory)' on a null object reference
I believe the following will work :
object CommonClass {
fun openSQLDatabase(context: Context): SQLiteDatabase? {
var dbase: SQLiteDatabase? = null
if (dbase == null) {
try {
dbase = openOrCreateDatabase(context.getDatabasePath("dbfile.sqlite"), null)
} catch (e: SQLException) {
println(e.message)
}
}
return dbase
}
}
Note this assumes that you want the database in the default location i.e. data/data/the_package_name/databases/dbfile.sqlite
You could invoke/call it using something like :-
val mydb = CommonClass.openSQLDatabase(this)
i'm trying to use firebase storage to upload images.
and here is what I've tried.
public void firetalk(string path)
{
Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance;
Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl("gs://<myurl>.appspot.com/");
Firebase.Storage.StorageReference art_image_ref = storage_ref.Child("images/innocence.jpg");
art_image_ref.PutFileAsync(path).ContinueWith((Task<StorageMetadata> task) =>
{
if (task.IsFaulted || task.IsCanceled)
{
Debug.Log(task.Exception.ToString());
// Uh-oh, an error occurred!
}
else
{
// Metadata contains file metadata such as size, content-type, and download URL.
Firebase.Storage.StorageMetadata metadata = task.Result;
string download_url = metadata.DownloadUrl.ToString();
Debug.Log("Finished uploading...");
Debug.Log("download url = " + download_url);
}
});
}
the firetalk funtion recieves a path and i use PutFileAsync for using the upload using path ,however i'm getting this error..
System.AggregateException: Exception of type 'System.AggregateException' was thrown.
-----------------
Firebase.Storage.StorageException: Permission denied. Could not perform this operation
UnityEngine.Debug:Log(Object)
GracesGames.SimpleFileBrowser.Scripts.explorer_script:m__0(Task`1) (at Assets/scripts/explorer_script.cs:85)
System.Threading.Tasks.TaskCompletionSource`1:SetException(Exception)
Firebase.Storage.StorageReference:CompleteTask(Task`1, TaskCompletionSource`1, Func`1, String, Boolean)
Firebase.Storage.c__AnonStorey6:<>m__0(Task`1)
System.Threading.Tasks.TaskCompletionSource`1:SetException(Exception)
Firebase.Storage.c__AnonStorey0:<>m__0()
Firebase.Storage.Future_StorageMetadata:SWIG_CompletionDispatcher(Int32)
Firebase.AppUtilPINVOKE:PollCallbacks()
Firebase.AppUtil:PollCallbacks()
Firebase.Platform.FirebaseAppUtils:PollCallbacks()
Firebase.Platform.FirebaseHandler:Update()
Firebase.Platform.FirebaseMonoBehaviour:Update()
any gueses?
I have a list that has icon to most right of cell row
when I implementing BindingContextChanged to control context action (enable and disable according to certain condition )
<customRender:ExtViewCell BindingContextChanged="FlightDetialCell_OnBindingContextChanged">
private void FlightDetialCell_OnBindingContextChanged(object sender, EventArgs e)
{
var deleteAction = new MenuItem { Text="Delete" , IsDestructive=true};
deleteAction.SetBinding(MenuItem.CommandParameterProperty, new Binding("."));
deleteAction.Clicked += (sender2, e2) =>
{
DeleteMenuItem_OnClicked(sender2, e2);
};
ViewCell theViewCell = ((ViewCell)sender);
var item = theViewCell?.BindingContext as DocumentsListItem;
if (item != null)
{
if (item.Title !="certain title" )
{
theViewCell.ContextActions.Add(deleteAction);
}
}
// theViewCell.BindingContextChanged -= FlightDetialCell_OnBindingContextChanged;
}
I has two strange behavior happened
in iOS platform icon take margin to left then when I keep scroll it become normal
in Android platform app crashed
Attempt to invoke virtual method 'boolean java.lang.Object.equals(java.lang.Object)' on a null object reference
--- End of managed Java.Lang.NullPointerException stack trace ---
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Object.equals(java.lang.Object)' on a null object reference
at android.widget.AdapterView.getPositionForView(AdapterView.java:602)
at md5b60ffeb829f638581ab2bb9b1a7f4f3f.ViewCellRenderer_ViewCellContainer_LongPressGestureListener.n_onLongPress(Native Method)
at md5b60ffeb829f638581ab2bb9b1a7f4f3f.ViewCellRenderer_ViewCellContainer_LongPressGestureListener.onLongPress(ViewCellRenderer_ViewCellContainer_LongPressGestureListener.java:51)
at android.view.GestureDetector.dispatchLongPress(GestureDetector.java:690)
at android.view.GestureDetector.access$200(GestureDetector.java:37)
at android.view.GestureDetector$GestureHandler.handleMessage(GestureDetector.java:266)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
my attempts to fix the issue detach listener
theViewCell.BindingContextChanged -= FlightDetialCell_OnBindingContextChanged;
but this don't solve my problem
I need to obtain classifications tags for ITextSnapshotLine lines in a current text view.
First, I get the active text view:
public static IWpfTextView GetTextView()
{
var textManager = (IVsTextManager)ServiceProvider.GlobalProvider.GetService(typeof(SVsTextManager));
IVsTextView vTextView = null;
var mustHaveFocus = 1;
textManager.GetActiveView(mustHaveFocus, null, out vTextView);
var userData = vTextView as IVsUserData;
if (userData != null)
{
IWpfTextViewHost viewHost;
object holder;
var guidViewHost = DefGuidList.guidIWpfTextViewHost;
userData.GetData(ref guidViewHost, out holder);
viewHost = (IWpfTextViewHost)holder;
var textView = viewHost.TextView;
return textView;
}
return null;
}
Then, I get the collection of ITextViewLine lines from the view and call GetClassificationTags method on each:
GetClassificationTags(new SnapshotSpan(line.Start, line.Length), textView)
The method looks like this:
public IEnumerable<IMappingTagSpan<IClassificationTag>> GetClassificationTags(SnapshotSpan span, ITextView textView)
{
var snapshot = textView.TextSnapshot;
var componentModel = (IComponentModel)ServiceProvider.GlobalProvider.GetService(typeof(SComponentModel));
var exportProvider = componentModel.DefaultExportProvider;
var viewTagAggregatorFactoryService = exportProvider.GetExportedValue<IViewTagAggregatorFactoryService>();
var tagAggregator = viewTagAggregatorFactoryService.CreateTagAggregator<IClassificationTag>(textView);
return tagAggregator.GetTags(span);
}
As a result I have everything classified correctly. However, Visual Studio throws an exception and logs it to the ActivityLog.xml file. This happens only after classifying all the lines for the first time. The information in log file says:
System.InvalidOperationException:
Unexpected false
at Roslyn.Utilities.Contract.ThrowIfFalse(Boolean condition, String message)
at Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.AbstractDiagnosticsTaggerProvider`1.CreateTagger[T](ITextBuffer buffer)
at Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.AbstractDiagnosticsTaggerProvider`1.Microsoft.VisualStudio.Text.Tagging.ITaggerProvider.CreateTagger[T](ITextBuffer buffer)
at Microsoft.VisualStudio.Text.Tagging.Implementation.TagAggregator`1.GatherTaggers(ITextBuffer textBuffer)
I noticed that the exception is not thrown after commenting out the line below:
var tagAggregator = viewTagAggregatorFactoryService.CreateTagAggregator<IClassificationTag>(textView);
Sometimes, there is also this exception in the log file:
System.InvalidOperationException: Unexpected false
at Roslyn.Utilities.Contract.ThrowIfFalse(Boolean condition, String message)
at Microsoft.CodeAnalysis.Editor.Tagging.AbstractAsynchronousTaggerProvider`1.TagSource.GetTagIntervalTreeForBuffer(ITextBuffer buffer)
at Microsoft.CodeAnalysis.Editor.Tagging.AbstractAsynchronousTaggerProvider`1.Tagger.GetTagsWorker(NormalizedSnapshotSpanCollection requestedSpans, Boolean accurate, CancellationToken cancellationToken)
at Microsoft.CodeAnalysis.Editor.Tagging.AbstractAsynchronousTaggerProvider`1.Tagger.GetTags(NormalizedSnapshotSpanCollection requestedSpans)
at Microsoft.VisualStudio.Text.Tagging.Implementation.TagAggregator`1.<GetTagsForBuffer>d__38.MoveNext()
My question is: what causes this exception and how can I get rid of it?
The code is open source, you can just take a look. My guess is you're trying that on a background thread.