Frage

I'm very new to Android Programming. I've developed many programmes in .net but I've no experience about Android. My problem is:
I've created a java class and I want to call it from main activity.

myClass newMyClass = new myClass();
String memberID = newMyClass.executeHttpGet("http://www.mysite.com");

Android studio puts a red underline at the newMyClass.executeHttpGet.
Error description is: Unhandled exception: java.lang.Exception.

I'm sure, there is a very simple solution, but I couldn't find it yet!

Could you please help me ?

War es hilfreich?

Lösung

As usual in Java, You should surround this kind of code with try-catch block. So do:

try {
  String memberID = newMyClass.executeHttpGet("http://www.mysite.com");
} catch(Exception e) {
  Log.d("ERROR", e.getMessage());
}

It should be available as quick fix in most of IDE.

Andere Tipps

The method throws an Exception that must be caught. You must surround the calling method with try-catch blocks or specify that your method throws this exception

try {
    String memberID = newMyClass.executeHttpGet("http://www.mysite.com");
}
catch (Exception ex) {
    System.err.println("Error");
}

I'm going to expand on the other answers a bit (which are correct), but fail to mention a powerful shortcut that Android Studio exposes to you which allows you to easily do this without typing.

  1. Highlight the line in question

    String memberID = newMyClass.executeHttpGet("http://www.mysite.com");
    
  2. Use the keyboard shortcut Ctrl+Alt+T on PC, ++J on Mac

  3. Choose try / catch, try / finally, or try / catch / finally depending on your needs.

The result will be the following, without typing any code at all. It makes you much more efficient and you will begin to enjoy Android Studio and become a more powerful

try {
    String memberID = newMyClass.executeHttpGet("http://www.mysite.com");
} catch (Exception e) {
    e.printStackTrace();
}

You're going to need to re-scope the String of course.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top