What is System.in in android? - android

I am doing the dagger tutorial for android in java, and they told me to create this class:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
CommandRouterFactory commandRouterFactory =
DaggerCommandRouterFactory.create();
CommandRouter commandRouter = commandRouterFactory.router();
while (scanner.hasNextLine()) {
commandRouter.route(scanner.nextLine());
}
}
}
I wrote my own code to try to see what the scanner is pulling from, but nothing shows up. I am just wondering, if System.in is some sort of command line input, and if so, how would I see that show up? I tried typing in the terminal built into android, but that doesn't produce any output either.
Finally, where do you even get a class like this to run in android? I'm only used to having code run at least from the starting point of a main activity.
Here's the link to the tutorial - it doesn't help much with setting up
https://dagger.dev/tutorial/02-initial-dagger

Related

Android printing with Brother SDK via WiFi throws ERROR_WRONG_LABEL despite selecting correct labelNameIndex

I've been trying to print with Brother Print SDK 3.5.1 on Android 8.1.0. I keep getting ERROR_WRONG_LABEL.
This is the code I use
void printPdf() {
// Specify printer
final Printer printer = new Printer();
PrinterInfo settings = printer.getPrinterInfo();
settings.printerModel = PrinterInfo.Model.QL_810W;
settings.port = PrinterInfo.Port.NET;
settings.ipAddress = "192.168.1.73";
settings.workPath = "storage/emulated/0/Download/";
// Print Settings
settings.labelNameIndex = LabelInfo.QL700.W62RB.ordinal();
settings.printMode = PrinterInfo.PrintMode.FIT_TO_PAGE;
settings.orientation = PrinterInfo.Orientation.PORTRAIT;
settings.isAutoCut = true;
printer.setPrinterInfo(settings);
// Connect, then print
new Thread(new Runnable() {
#Override
public void run() {
if (printer.startCommunication()) {
PrinterStatus result = printer.printPdfFile("/storage/emulated/0/Download/hello world red.pdf", 1);
if (result.errorCode != PrinterInfo.ErrorCode.ERROR_NONE) {
Log.d("TAG", "ERROR - " + result.errorCode);
}
printer.endCommunication();
}
}
}).start();
}
My printer model is QL-810W and I use the black and red W62 roll.
I've tried the Sample Application, where setting W62RB in labelNameIndex prints fine.
Changing the roll for different one with different width didn't help.
I've also tried iterating over numbers 0 to 50 and using them as labelNameIndex.
Based on this thread, I thought that the issue may be in specifying the workPath attribute. Setting workPath to getContext().getCacheDir().getPath() results in ERROR_OUT_OF_MEMORY instead of ERROR_WRONG_LABEL. Not specifying workPath and adding <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> to AndroidManifest.xml results in ERROR_WRONG_LABEL
EDIT
I've modified the Brother Sample app and uploaded it to GitHub. The app now launches Activity_PrintPdf.java by default where I inserted my printing code with hardcoded values at the beginning of onCreate method - this works fine and prints the PDF file as expected.
Then I created a new Empty Activity project in Android Studio, copy pasted the library, added the imports to build.gradle and copy pasted the permissions into AndroidManifest.xml. Then I copy pasted the printing code at the beginning of onCreate method in MainActivity.java. Running the app results in ERROR_WRONG_LABEL.
This is the modified working example app and this is the one that results in the error. I want to use the code as native module that I call from my React Native app, so it's important that I manage to set up the printing code from scratch rather than modifying the existing example app.
EDIT 2
I've inspected the library with a debugger: when executing printer.setPrinterInfo(mPrinterInfo) the library internally calls private boolean createWorkPath(String dirPath) of Printer object. On return from this method, the debugger shows Source code doesn't match the bytecode and seems to forget the created directory. This also internally sets mResult.errorCode = ErrorCode.ERROR_WORKPATH_NOT_SET. However, instead of rising any error here the code just silently proceeds, which later results in ERROR_WRONG_LABEL when trying to print. Running the same code snipper in the modified Sample app works fine.
I'd be grateful if you could help or suggest what to try next.
Thank you!
I've now fixed the issue, which was that the Brother library silently failed to create a temporarily folder and instead of reporting an error, it continued and failed later to read the label information. Based on this thread, it is now required to specify runtime file read and write permissions as opposed to the compile-time ones in AndroidManifest.xml.
Adding
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
at the beginning of onCreate before the printing code fixed the issue.

Unity Android Build - error on change scene

I'm facing a rather odd problem, I'm using unity 2017.3.1f1 Personal.
When I build the APK and I copy that file to the phone and install it from the phone's file manager, I can't switch from the main menu to the first scene, the game crashes at the load scene or just freezes after selection, thought it was due to the Async code so I tried without it and have no result at all.
When I select Build and Run this doesn't happen at all and the application runs normally, what I'm I missing here or how can I fix this? Already restarted unity and the computer many times.
Here's the code I'm using to switch in between scenes including the code without the Async mode:
public void Car1()
{
selectedCar = 0;
canvasManagerGO.GetComponent<CanvasManager>().Close();
SceneManager.LoadScene("W" + selectedWorld + "-L1", LoadSceneMode.Single);
}
public void Car2()
{
selectedCar = 1;
canvasManagerGO.GetComponent<CanvasManager>().Close();
SceneManager.LoadScene(1, LoadSceneMode.Single);
}
public void Car3()
{
selectedCar = 2;
canvasManagerGO.GetComponent<CanvasManager>().Close();
StartCoroutine(ChangeScene("W" + selectedWorld + "-L1"));
public IEnumerator ChangeScene(string sceneName)
{
loadingCanvas.SetActive(true);
AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Single);
while (!asyncOperation.isDone)
{
float progress = Mathf.Clamp01(asyncOperation.progress / .9f);
//Debug.Log(asyncOperation.progress);
slider.value = progress;
yield return null;
}
yield return null;
}
Car 1 and 2 have a direct mode without using the coroutine to change the scene and none of them work, the code has no errors at all or at least the console is not reporting anything, I also tried with different build settings and compressions, also with or without development build to check the profiler and nothing, thanks you all :)
I ran the ADB debugger and found nothing, the app just shows a blank line and that's it goes dead, I even put Lunar console on my project and it was a great help to see errors unity doesn't show but was not of much help either.
The solution I found was at this video https://www.youtube.com/watch?v=OxLa2uPW0dI
I followed the exact settings for "player settings -> other settings" he used and apparently it solved the problem at least for now but can't point at which setting was causing this behaviour

BeanShell Android Issue. Unable to start activity remotely

Good day. The main amazing thing about the BeanShell is the idea that i can control what i want to be done dynamically from the server and i thought it would be amazing.
Although i never succeded in achieving that and seems no one else tried to start activity from the beanshell either.
Here how it goes. I simply want to pass the code from the server side to the Android,Android is going to evaluate that code within interpreter and run that.
The issue is that i am getting the exception from BeanShell no matter what i try.
The code from server side is the next.
$response['method'] = "import my.some.name.*;"
. "startActivity(new Intent(this,MyProfile.class))";
The code for Android is the next.
try {
String responseBody = response.body().string();
JSONObject jsonObject = new JSONObject(responseBody);
String method = jsonObject.optString("method");
Interpreter interpreter = new Interpreter();
try {
Object res = interpreter.eval(method);
} catch (EvalError evalError) {
evalError.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
But i am getting the next exception from the BeanShell
Sourced file: inline evaluation of: ``import my.some.name.*;startActivity(new Intent(this,MyProfile.class));'' : Class: MyProfile not found in namespace : at Line: 1 : in file: inline evaluation of: ``import my.some.name.*;startActivity(new Intent(this,MyProfile.class));'' : MyProfile
Any ideas what is going on?
Just in case if anyone needs the same solution i am posting for everyone to know.
Here how it goes.
Firstly you need to know that whatever you are trying to do on the server side remember that the BeanShell actually does not know anything about the String code you are passing itself,as it is going to interpret it just like a code out of box so with the help of CommonWare hint about full name path i managed to get it working.
So first step to do is to initialize the Interpreter.
Basic initialization goes like this :
String responseBody = response.body().string();
JSONObject jsonObject = new JSONObject(responseBody);
String method = jsonObject.optString("method");
Interpreter interpreter = new Interpreter();
try {
interpreter.set("context",getApplicationContext());
Object res = interpreter.eval(method);
} catch (EvalError evalError) {
evalError.printStackTrace();
}
Take a very attentive notice about the context as it was my main issue going back and forth as at the moment when i succeded to actually force BeanShell recognize my classes,the BeanShell started to throw Method not found exception about the startActivity() so by thinking logically we can assume that we would set the context as activity as the parent one for our remote methods and start evaluating everything from the context. So here how the remote code is looking.
$response['method'] = "import ink.va.activities;"
. "import android.content.Intent;"
. "import android.content.*;"
. "context.startActivity(new android.content.Intent(context, my.package.name.MyProfile.class));";
The most important things to notice here.
• We are importing everything possible for BeanSherll to recognize our classes,even if they are Android-Build,no matter,still we need to import them.
• If you are going to use any class,then as CommonWare noticed out,you MUST specify the full path to that Class E.G my.package.name.MyProfile.class.
• As i was getting Command Not Found i started to think about the context.startActivity() as i have defined the context beforehand in BeanShell as my parent from which i am going to use methods and Woala,everything worked like a charm!
Possible Problems
I don't know a lot about BeanShell, but there's a couple of issues here
You can import a class (in a compiled language) at runtime
You're trying to do the equivalent of Reflection (but aren't doing any)
Security. No user would consent to you having control to open a screen on their app remotely
Presumably BeanShell is supposed to do the reflection under the covers, but in an case you won't be able to do the import.
Possible solutions
The class/activity using the library should import everything (I'm not sure if a compiler will even retain this)
You can use reflection directly, with things like "method from name". The downside is it's very limited what code you can send from the server unless you handle a myriad of cases.
You could only send names/commands; to specific endpoints in your java app (this is what I recommend) and plan the actions you want ahead of time
$response['method'] = "my.some.name.MyProfile";
JSONObject jsonObject = new JSONObject(response.body().string());
String nameParam = jsonObject.optString("method");
Class<? extends Activity> clazz = Class.forName(nameParam); //wrap with try
startActivity( new Intent(this, clazz) )

Testing with Espresso in Android error

I'm working with espresso for testing. I'm following Espresso Intents
and problem happened when I try to work like this site. First is validateIntentSentToPackage method:
public void validateIntentSentToPackage() {
user.clickOnView(system.getView(R.id.callButton));
intended(toPackage("com.android.phone"));}
Android Studio display error at "user" and "system". I don't understand this error what does this mean.
Second is activityResult_IsHandledProperly method:
public void activityResult_IsHandledProperly() {
Intent resultData = new Intent();
String phoneNumber = "123-345-6789";
resultData.putExtra("phone", phoneNumber);
ActivityResult result = new ActivityResult(Activity.RESULT_OK, resultData);
intending(toPackage("com.example.unittestdemo")).respondWith(result));
onView(withId(R.id.pickButton)).perform(click());
onView(withId(R.id.phoneNumber).check(matches(withText(phoneNumber)));}
Android Studio display error java.lang.NullPointerException and in line intending(toPackage("com.example.unittestdemo")).respondWith(result);
Please help!!!
Android Studio display error at "user" and "system". I don't understand this error what does this mean.
I guess, you don't have previously declared these variables.
I don't see any logs or whole code of this testing class, so I can only recommend you to check this example
Here you would find all methods which you're looking for in one file.
Also please visit Google Samples - Espresso Testing repository

How to Replicate Java console behaviour in Android App

I have a Java SE Application that use
input = new Scanner(System.in);
to get Input parameters
and use System.out.println("..");
to print results
Since all Java APIs used in the original Java Project are also available in Android, I have tried to import all classes without any error, but now I don't know how replicate the behaviour of the classic Java console in Android.
I have seen that there are developers that have achieved this in some IDE-like apps, but I don't know how.
Could you help me?
Example:
assume that you want to port this dummy Java SE Application in Android mantaining the console-like approach of the original code
public static void main(String[] args) {
System.out.println("Please enter your choice");
System.out.println("A, B");
Scanner myScanner = new Scanner(System.in);
String choice = myScanner .nextLine();
if (choice.charAt(0) == 'A') {
...do something
}
else{
...do something
}
}
You can execute system commands with exec(). Here is how to do it:
Runtime r = Runtime.getRuntime();
Process p = r.exec("uname -a"); // here goes your input
p.waitFor();
BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = b.readLine()) != null) {
System.out.println(line);
}
Update:
Ok, from what I understand, you would like to compile and run code written by user. I can see 3 options:
Most difficult I think. Get the source code of some Java compiler and include it in your project. So, user inputs a text. You compile it, run and give the output.
Using already built compiler. This requires root. Install javac on your device. Then, in your application you can call it with the above exec() code.
Easiest one. Using internet and for example, Ideone.com. In your app you send code to compile on Ideone. You get back the output and present it to the user.

Categories

Resources