Logging and crash stack traces not showing in Android Studio - java

I'm trying to debug an app on my device and I'm having a bit of trouble with the debugger. I tried testing the logger to see if it would write to Logcat like so:
Log.d("MyActivity", "Testing logging...");
But nothing shows up in Logcat with the app: com.myapp.debug filter. It comes up when I simply filter by string (using my app name) but the entry looks like this:
01-08 13:45:07.468 29748-29748/? D/MyActivity﹕ Testing logging...
Does this question mark mean that something in the app is not getting passed through to the debugger? This might relate to my second issue with the debugger:
I've been debugging a crash and every time it happens, the phone simply shows the 'App is not responding' message then closes the current activity, disconnects the debugger, and the app keeps on running with the previous activity. No stack trace, no info about the crash, nothing. Is there something I need to set up in Android Studio to get this working?

I'm also having this trouble and I can't find too a good answer for this.
Instead I did a work around and catch the error with Thread.setDefaultUncaughtExceptionHandler() and Log it with Log.e()
I used this class to do it.
public class ExceptionHandler implements java.lang.Thread.UncaughtExceptionHandler {
private final String LINE_SEPARATOR = "\n";
public static final String LOG_TAG = ExceptionHandler.class.getSimpleName();
#SuppressWarnings("deprecation")
public void uncaughtException(Thread thread, Throwable exception) {
StringWriter stackTrace = new StringWriter();
exception.printStackTrace(new PrintWriter(stackTrace));
StringBuilder errorReport = new StringBuilder();
errorReport.append(stackTrace.toString());
Log.e(LOG_TAG, errorReport.toString());
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
}
}
Then in my Activity .
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* catch unexpected error
*/
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
setContentView(R.layout.activity_main);
//other codes
}
Hope this helps.

I think it is the same adb or filer problem.
At first remove all filters.
Restart adb - type in terminal adb kill-server && adb start-server.

Probably your google analytics "ga_reportUncaughtExceptions" is set to true, turning it to false fixes the issue and exceptions get printed to logcat.Please refer to below link for further details.
Why does android logcat not show the stack trace for a runtime exception?

You should define a class that implement UncaughtExceptionHandler and use stackTraceToString in Kotlin:
import android.util.Log
import java.lang.Thread.UncaughtExceptionHandler
class ExceptionHandler : UncaughtExceptionHandler {
override fun uncaughtException(t: Thread, e: Throwable) {
val stackTrace: String = e.stackTraceToString()
Log.d("TAG", stackTrace)
}
}
and register it in your application:
Thread.setDefaultUncaughtExceptionHandler(ExceptionHandler())

Related

ChatSDK initialize throwing InvocationTargetException error

Okay so, I am currently integrating chatSDK into a pre-existing app. This is all fine, but when i try to call ChatSDK.ui().startSplashScreenActivity(context); it throws an errors that it was invoked on a null pointer.
I managed to narrow this down to ChatSDK.initialize(context, builder.build(), FirebaseNetworkAdapter.class, BaseInterfaceAdapter.class);
Which was throwing java.lang.reflect.InvocationTargetException. In the stack trace this was also shown
at co.chatsdk.core.session.ChatSDK.initialize(ChatSDK.java:86)
--> which is :shared().setNetworkAdapter(networkAdapterClass.getConstructor().newInstance());
So from what I gather, there is something funky going on with the network adapter, i.e my connection to firebase (works with another chatsdk app), or internet connection?
I'm not quite sure how to go forward this this so would really appreciate your help.
Here is the code for reference.
Thank you
Context context = getApplicationContext();
try {
// Create a new configuration
Configuration.Builder builder = new Configuration.Builder();
// Perform any other configuration steps (optional)
builder.firebaseRootPath("prod");
// Initialize the Chat SDK
//Configuration.Builder config = new Configuration.Builder(context);
ChatSDK.initialize(context, builder.build(), FirebaseNetworkAdapter.class, BaseInterfaceAdapter.class);
// File storage is needed for profile image upload and image messages
FirebaseFileStorageModule.activate();
// Push notification module
//FirebasePushModule.activate();
// Activate any other modules you need.
// ...
} catch (Exception e) {
// Handle any exceptions
e.printStackTrace();
Log.e("chatsdkError",e.toString());
}
public class Messages extends AppCompatActivity {
#Override
protected void onCreate(Bundle onSavedInstance){
super.onCreate(onSavedInstance);
setContentView(R.layout.activity_messages);
Context context = getApplicationContext();
ChatSDK.ui().startSplashScreenActivity(context);
}
}
And lastly, here is some of the stack trace that i think is important
W/System.err: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at co.chatsdk.core.session.ChatSDK.initialize(ChatSDK.java:86)
at com.ul.pinter.Home.onCreate(Home.java:101)
at android.app.Activity.performCreate(Activity.java:7815)
at android.app.Activity.performCreate(Activity.java:7804)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1318)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3349)

How can I DetectFaces in Amazon Rekognition AWS with Android Studio?

I have tried so many way but i can't succeed. I haven't found any source code examples for Android(about rekognition)
there's a source code in JAVA in the Developer Guide but i cannot implement that even though I tried TT
I try to detect faces by sending an image file from an external storage(from the emulator)
I don't know what i did wrong(I'm not good at coding)
Here is my code
AmazonRekognitionClient amazonRekognitionClient;
Image getAmazonRekognitionImage;
DetectFacesRequest detectFaceRequest;
DetectFacesResult detectFaceResult;
File file = new File(Environment.getExternalStorageDirectory(),"sungyeol.jpg.jpg");
public void test_00(View view) {
ByteBuffer imageBytes;
try{
InputStream inputStream = new FileInputStream(file.getAbsolutePath().toString());
imageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream));
Log.e("InputStream: ",""+inputStream);
Log.e("imageBytes: ","");
getAmazonRekognitionImage.withBytes(imageBytes);
// Initialize the Amazon Cognito credentials provider
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(),
"us-east-2:.......", // Identity Pool ID
Regions.US_EAST_2 // Region
);
//I want "ALL" attributes
amazonRekognitionClient = new AmazonRekognitionClient(credentialsProvider);
detectFaceRequest = new DetectFacesRequest()
.withAttributes(Attribute.ALL.toString())
.withImage(getAmazonRekognitionImage);
detectFaceResult = amazonRekognitionClient.detectFaces(detectFaceRequest);
detectFaceResult.getFaceDetails();
}
catch(Exception ex){
Log.e("Error on something:","Message:"+ex.getMessage());
}
and here is my errors
02-04 09:30:07.268 29405-29405/? E/InputStream:: java.io.FileInputStream#a9b23e7
02-04 09:30:07.271 29405-29405/? E/Error on something:: Message:Attempt to invoke virtual method 'com.amazonaws.services.rekognition.model.Image com.amazonaws.services.rekognition.model.Image.withBytes(java.nio.ByteBuffer)' on a null object reference
what is a null object reference?
i try to change the file path but he said no such file ... and when I change to this path, there's errors above.
by the way I've already asked a user for a permission to access a folder from Emulator in Android
please help me
PS. sorry for my bad English
Thank you in advance.
Now I am ok with the issues. I have been through many many things <3 <3 <3.
Thank you
I'm Thai and I had to try harder to find the solutions because there's lack of information in the particular language. Here are my solutions.
My solutions are:
0.There is an endpoint for setting for the Rekognition-->
http://docs.aws.amazon.com/general/latest/gr/rande.html#rekognition_region
1.On a "null object reference issue" I found that I have to create a new object first such as "Image image = new Image();" <-- The "new" command creates an object instance in that class
2.After the above error, there are more errors (Errors on NetworkOnMainThreadException), so I tried everything until I found this page -->
https://docs.aws.amazon.com/cognito/latest/developerguide/getting-credentials.html the page said that ...
Consequently, I looked up for more information about the AsyncTask and after that I created an AsyncTask class and then I move all my code about the initialize, the request, the response to the AsyncTask class. ตอนรันตอนท้ายๆน้ำตาจิไหล my code worked... TT and by the conclusion the sungyeol.jpg.jpg file worked
for example
private void testTask(){
.... all code in the main thread particularly on the requests and responses
from the services
//print the response or the result
//Log.e() makes the message in the android monitor red like an error
Log.e("Response:", [responseparameter.toString()]);
}
//create the inherited class from the AsyncTask Class
//(you can create within your activity class)
class AsyncTaskRunner extends AsyncTask<String,String,String>{
#Override
public String doInBackground(String ... input){
testTask(); // call the testTask() method that i have created
return null; // this override method must return String
}
}
//I've created a button for running the task
public void buttonTask(View view){
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
}
for more information about the AsyncTask:
https://developer.android.com/training/basics/network-ops/connecting.html#AsyncTask
http://www.compiletimeerror.com/2013/01/why-and-how-to-use-asynctask.html#.WJdkqVOLTIU
I hope these help :)

Unity call android static function of java class

Hi i'd like to call this piece of android java code in unity with c# here the java code:
SmsDialog.getInstance().init(this);
//this is context of android activity
And right now i'm doing it like this in my c# code:
void ShowPaymentDialog()
{
AndroidJavaClass smsDialog = new AndroidJavaClass("com.mobagym.testsdkmobagym.SmsDialog");
smsDialog.CallStatic<AndroidJavaObject>("getInstance").Call("init",getContext());
}
AndroidJavaObject getContext()
{
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
return jo;
}
There are no crashes or anything, Just that game stops and doesnt execute lines after ShowPaymentDialog.
void Start ()
{
ShowPaymentDialog();
GoogleAnalyticsV4.getInstance().LogScreen(MyMenuManager.SPLASH_SCREEN);
StartCoroutine(Next());
}
IEnumerator Next()
{
yield return new WaitForSeconds(duration);
SceneManager.LoadScene(MyMenuManager.MAIN_MENU);
}
so i'd like to know if i'm doing sth wrong with c# syntax. And if there are any ways to log this.
You should try to log the error as you mention.
Try setting up a try catch block.
Try {
//do some logic
} catch (Exception e){
//Log exception
}
Check this link:
https://docs.unity3d.com/ScriptReference/Debug.LogException.html
Maybe when you have stacktrace with exact error we can provide more assistance.
You are probably having a native java exception and missing it. You should connect a device to it and monitor the device log with adb logcat looking for your method call. This should give you enough information to continue debugging.

Android InstrumentTest hangs until minimizing the app

I just started to look into Android instrumentation tests but have some problems with getting my tests executed. Here is what I tried:
Using Android Studio and gradle, I created a simple test class within src/instrumentTest/java/. Here it is:
package at.example.test;
import android.test.ActivityInstrumentationTestCase2;
import android.view.View;
import at.example.activity.MainActivity;
public class BasicAppTestCase extends ActivityInstrumentationTestCase2<MainActivity> {
private MainActivity activity;
public BasicAppTestCase() {
super(MainActivity.class);
}
#Override protected void setUp() throws Exception {
super.setUp();
activity = getActivity();
}
public void testAppHomeButtonExists() {
View homeButton = activity.findViewById(android.R.id.home);
assertNotNull("Home button does not exist", homeButton);
}
}
Next, I start the test using by right clicking on my project and selecting Run 'All Tests'. Android Studio executes assembleDebug and assembleTest tasks for my project, and installs both apk files onto my test device.
Afterwards, the app is successfully started on my test device. The setUp() method is getting executed (I checked this by putting a failing assert into the method as well as using logcat) and then the test execution hangs, showing Running tests... and testAppHomeButtonExists as being currently executed.
The test execution won't proceed until I change the activity state by minimizing the app pressing the home button or opening the app switcher. Then the test method testAppHomeButtonExists gets executed and (depending on the methods body) succeeds or fails. Again, I tested this behavior using assert calls and the logcat output.
UPDATE:
This is what the TestRunner is logging to my device's logcat stream:
11-11 15:34:59.750 24730-24748/at.example.activity I/TestRunner﹕ started: testAppHomeButtonExists(BasicAppTestCase)
Up until I stop the app nothing more is logged. After stopping the activity following is logged:
11-11 15:35:05.205 24730-24748/at.example.activity I/TestRunner﹕ finished: testAppHomeButtonExists(BasicAppTestCase)
11-11 15:35:05.205 24730-24748/at.example.activity I/TestRunner﹕ passed: testAppHomeButtonExists(BasicAppTestCase)
Am I doing something wrong? Am I missing something? What could cause this behavior?
Thanks in advance!
Instead of checking view like that u can try something like this :
public class BasicAppTestCase extends ActivityInstrumentationTestCase2<MainActivity> {
private MainActivity activity;
private Button;
public BasicAppTestCase() {
super(MainActivity.class);
}
#Override protected void setUp() throws Exception {
super.setUp();
activity = getActivity();
button = (Button) activity
.findViewById(android.R.id.home);
}
public final void testPreconditions() {
assertNotNull(activity);
}
public final void testFieldsOnScreen() {
final Window window = tAes_Activity.getWindow();
final View origin = window.getDecorView();
assertOnScreen(origin, button);
}
}
I have found the problem: I created an infinite invalidation loop inside one of my views onDraw() method. A velociraptor should eat me for using old code without checking it first. This is what the view's drawing method looked like:
#Override protected void onDraw(Canvas canvas) {
// Get the current location on screen in pixels (left = 0)
int[] location = new int[2];
this.getLocationOnScreen(location);
// Translate the canvas for the same location as its current offset (resulting in a doubled shift).
canvas.translate(location[0], 0);
// Now draw the translated content.
super.onDraw(canvas);
this.invalidate();
}
The above drawing method created a "faked parallax effect" of the view's content. The problem was, that although this did not result in a ANR it caused the hosting Activity to never go idle causing my test's getActivity() method not to return as it's implementation waits for an idle activity (meaning the setup completed). The question Android animation causing "Activity idle timeout for History Record" on start up is a similar problem. My quick solution was to defer the invalidate() call to the parent ViewPager. Since my parallax effect needed only to be updated when the position of my page changed I am now using a ViewPager.OnPageChangeListener() that updates child views as soon as they move.
This fixes the problem for me! My tests are running now and are fully functional!

How can I get logcat data with ddmlib?

I'm coding an utility to make a showcase movies on the PC of the apps running on the Android devices. I was able to do it using xuggler (http://www.xuggle.com/xuggler) and ddmlib. It is really easy to obtain image as RawImage from the Android's adb using ddmlib, but now i need to get Logcat data from the moments when I shot the movie. I can't find any examples to obtaint he Logcat data; the logcat package has some classes to handle Logcat messages, but none to instantiate it. Anybody, help! I'll be glad to see any example how to obtaing logcat messages using ddmlib.
I have fount that it is possible using
LogCatReceiverTask lcrt;
LogCatListener lcl;
lcrt=new LogCatReceiverTask(devices[0]);
lcl= new LogCatListener() {
#Override
public void log(List<LogCatMessage> msgList) {
System.out.println("Called with messages list length "+msgList.size());
for (LogCatMessage msg : msgList) {
// System.out.println(msg.toString());
/*
System.out.println(msg.getTime());
System.out.println(msg.getPid());
System.out.println(msg.getLogLevel());
System.out.println(msg.getAppName());
System.out.println(msg.getTag());
System.out.println(msg.getTid());
System.out.println(msg.getMessage());
*/
logcat = logcat + msg.toString() + "\n";
}
}
};
}
Thank llya Yevlampiev,This help me developing android logcat api on ddmlib.
Custom Logfilter

Categories

Resources