This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 7 years ago.
I'm trying to learn how to read and send json mensages in android.
I tried to follow the 2º answer from: "simplest way to read json from a URL in java", but for some reason it failed at the connection.
Here is the code i used:
String sURL = "http://freegeoip.net/json/";
URL url = null;
try {
url = new URL(sURL);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection request = null;
try {
request = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
request.connect();
} catch (IOException e) {
e.printStackTrace();
}
JsonParser jp = new JsonParser();
JsonElement root = null;
try {
root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
} catch (IOException e) {
e.printStackTrace();
}
JsonObject rootobj = root.getAsJsonObject();
content.setText(rootobj.get("zip_code").getAsString());
and here are the errors i got:
10-23 08:50:36.120 12366-12366/abff.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: abff.myapplication, PID: 12366
java.lang.RuntimeException: Unable to start activity ComponentInfo{abff.myapplication/abff.myapplication.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
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)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
at abff.myapplication.MainActivity.onCreate(MainActivity.java:65)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
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)
If you read the error you will see it says: android.os.NetworkOnMainThreadException. You can't perform http requests on the main thread. Make sure you use another thread or an AsyncTask
Related
It should be something easy to do, but these commands return error when I try to convert a String to integer:
Intent recibir = getIntent();
String nombre = recibir.getStringExtra("hora_inicio");
int numero=0;
try {
numero = Integer.parseInt(nombre);
} catch(NumberFormatException nfe) {
nfe.printStackTrace();
}
Toast.makeText(this, numero, Toast.LENGTH_SHORT).show();
Android monitor returns this error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cristobal.policlinica, PID: 11025
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.cristobal.policlinica/com.example.cristobal.policlinica.CalendarActivity}:
android.content.res.Resources$NotFoundException: String resource ID
0x9
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
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)
Caused by: android.content.res.Resources$NotFoundException: String
resource 0x9
at android.content.res.Resources.getText(Resources.java:312)
at android.widget.Toast.makeText(Toast.java:286)
at
com.example.cristobal.policlinica.CalendarActivity.onCreate(CalendarActivity.java:31)
at android.app.Activity.performCreate(Activity.java:6237)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
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)
thanks in advance
The problem is not with your conversion but with your Toast.makeText. When you call Toast.makeText(this, numero, Toast.LENGTH_SHORT).show();
It considers numero as resId and tries to find the relative string resource in strings.xml which fails giving error:
Resources$NotFoundException: String resource ID
Instead of
Toast.makeText(this, numero, Toast.LENGTH_SHORT).show();
DO
Toast.makeText(this, String.valueOf(numero), Toast.LENGTH_SHORT).show();
Try this:
number = Integer.parseInt(YourStringName.toString());
Toast.makeText(this, String.valueOf(numero), Toast.LENGTH_SHORT).show();
I want to use a pre fill database in my app so I found this code.
DB_NAME = "urg1718.sqlite"
public SQLiteDatabase openDatabase() {
File dbFile = context.getDatabasePath(DB_NAME);
String path = dbFile.getAbsolutePath();
Log.i("path", "openDatabase: " + path);
if (!dbFile.exists()) {
try {
//the file doesn't exist yet so this function is called
copyDatabase(dbFile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
//check if the database is present in the folder
Log.i("database", "openDatabase: " + dbFile.exists());
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
}
private void copyDatabase(File dbFile) throws IOException {
//pre fil database
InputStream is = context.getAssets().open(DB_NAME);
try {
//where the error occurs
OutputStream os = new FileOutputStream(dbFile);
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
os.write(buffer);
}
os.flush();
os.close();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();;
} catch (IOException e) {
e.printStackTrace();
}
}
The "OutputStream os = new FileOutputStream" catch the following error.
java.io.FileNotFoundException: /data/data/jle.urgdegarde17_18/databases/urg1718: open failed: ENOENT (No such file or directory)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:456)
W/System.err: at java.io.FileOutputStream.(FileOutputStream.java:87)
W/System.err: at java.io.FileOutputStream.(FileOutputStream.java:127)
W/System.err: at java.io.FileOutputStream.(FileOutputStream.java:116)
W/System.err: at jle.urgdegarde17_18.AssetDatabaseOpenHelper.copyDatabase(AssetDatabaseOpenHelper.java:49)
W/System.err: at jle.urgdegarde17_18.AssetDatabaseOpenHelper.openDatabase(AssetDatabaseOpenHelper.java:35)
W/System.err: at jle.urgdegarde17_18.Chargement.isStoragePermissionGranted(Chargement.java:40)
W/System.err: at jle.urgdegarde17_18.Chargement.onCreate(Chargement.java:18)
W/System.err: at android.app.Activity.performCreate(Activity.java:5990)
W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
W/System.err: at android.app.ActivityThread.access$800(ActivityThread.java:151)
W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err: at android.os.Looper.loop(Looper.java:135)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5254)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at java.lang.reflect.Method.invoke(Method.java:372)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
W/System.err: at libcore.io.Posix.open(Native Method)
W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:442)
W/System.err: ... 20 more
I tried to use getDatabasePath(), getDatabasePath().getAbsolutePath() and directly put the string returned by those functions into FileOutputStream
I also tried to remove the ".sqlite" from the database name.
I don't understand what i'm doing wrong ...
Thank's.
I have the following code to track uncaught exceptions using google analytics:
ExceptionReporter myHandler =
new ExceptionReporter(AnalyticsTrackers.getInstance().get(AnalyticsTrackers.Target.APP),
Thread.getDefaultUncaughtExceptionHandler(), this);
ExceptionParser ep = new ExceptionParser() {
#Override
public String getDescription(String s, Throwable throwable) {
return "UserID:" + userID + " Version:" + versionName + " Exception:" + stringifyStacktrace(null, throwable);
}
};
private String stringifyStacktrace (Exception e, Throwable t){
if(e != null) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
return sw.toString();
} else {
return t.toString() + Arrays.toString(t.getStackTrace());
}
}
The problem is I am getting only the following:
java.lang.RuntimeException: Unable to start activity ComponentInfo{in.jiyofit.basic_app/in.jiyofit.basic_app.WorkoutActivity}: java.lang.ArithmeticException: divide by zero
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2450)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2510)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
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)
I want the rest of the stacktrace that gives the line cause for the exception. I am not getting the following part of the stacktrace:
Caused by: java.lang.ArithmeticException: divide by zero
at in.jiyofit.basic_app.WorkoutActivity.onCreate(WorkoutActivity.java:79)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2510)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
How to get this also?
Try out the static method getStackTraceString() from the Log class
I want to load facebook.com in a webview with custom CSS to change a few things. I use jsoup but everytime i start the app it crashes.
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
Document doc = Jsoup.connect("https://www.facebook.com").get();
doc.head().getElementsByTag("link").remove();
doc.head().appendElement("link").attr("rel", "stylesheet").attr("type", "text/css").attr("href", "style.css");
String htmlData = doc.outerHtml();
WebView webview = new WebView(this);
setContentView(webview);
webview.loadDataWithBaseURL("file:///android_asset/.", htmlData, "text/html", "UTF-8", null);
} catch (IOException e) {
e.printStackTrace();
}
}
Logcat output
FATAL EXCEPTION: main Process: com.example.name.firstapp, PID: 23936
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.name.firstapp/com.example.name.firstapp.MainActivity}:
android.os.NetworkOnMainThreadException at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java) at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
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) Caused
by: android.os.NetworkOnMainThreadException at
android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
at java.net.InetAddress.lookupHostByName(InetAddress.java:431) at
java.net.InetAddress.getAllByNameImpl(InetAddress.java:252) at
java.net.InetAddress.getAllByName(InetAddress.java:215) at
com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
at
com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
at
com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
at
com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
at
com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
at
com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
at
com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
at
com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at
com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
at
com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
at
com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:89)
at
com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java)
at
org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:563)
at
org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:540)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:227) at
org.jsoup.helper.HttpConnection.get(HttpConnection.java:216) at
com.example.name.firstapp.MainActivity.onCreate(MainActivity.java:25)
at android.app.Activity.performCreate(Activity.java:6237) at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java) at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
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)
You are connecting to network in the main(UI) thread. So you get android.os.NetworkOnMainThreadException.
Android system wont allow that, as it blocks the UI thread. So Use some background threads like AsyncTask or IntentService to access network.
I am trying to copy a database out of assets but in my createDatabase() method I am getting a null pointer exception. This occurs on the call to getReadableDatabase.
public static synchronized MetroLinkDatabaseHelper getInstance(Context context) {
// Using a singleton to minmize the chance of opening multiple
// decreasing any chance of memory leak
if(myInstance == null) {
myInstance = new MetroLinkDatabaseHelper(context);
}
return myInstance;
}
private MetroLinkDatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.mycontext = context;
boolean dbexist = checkdatabase();
if (dbexist) {
} else {
System.out.println("Database doesn't exist");
try {
createdatabase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// Create (copy the original in assets) if not exist using copydatabase
public void createdatabase() throws IOException {
boolean dbexist = checkdatabase();
if (dbexist) {
} else {
// SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
this.getReadableDatabase();
try {
copydatabase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
Here is the error log:
08-29 14:13:05.147 2222-2222/com.bkane56.practice.practiceapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.bkane56.practice.practiceapp, PID: 2222
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.bkane56.practice.practiceapp/com.bkane56.practice.practiceapp.ListStopsActivity}: 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, android.database.DatabaseErrorHandler)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2250)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413)
at android.app.ActivityThread.access$800(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5356)
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:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
Caused by: 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, android.database.DatabaseErrorHandler)' on a null object reference
at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:268)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:187)
at com.bkane56.practice.practiceapp.MetroLinkDatabaseHelper.createdatabase(MetroLinkDatabaseHelper.java:66)
at com.bkane56.practice.practiceapp.MetroLinkDatabaseHelper.<init>(MetroLinkDatabaseHelper.java:52)
at com.bkane56.practice.practiceapp.MetroLinkDatabaseHelper.getInstance(MetroLinkDatabaseHelper.java:38)
at com.bkane56.practice.practiceapp.ListStopsActivity.<init>(ListStopsActivity.java:28)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1089)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2240)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413)
at android.app.ActivityThread.access$800(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5356)
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:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
Line 66 =
this.getReadableDatabase();
Any ideas? I did ask this question before in a much longer form but got no help.
Thanks
Your problem is here:
com.bkane56.practice.practiceapp.ListStopsActivity.<init>(ListStopsActivity.java:28)
You are attempting to do something with the Activity instance before the super.onCreate() call in the onCreate() method of that Activity. Generally, that does not work, with exceptions like this one.
Instead of calling getInstance() on MetroLinkDatabaseHelper from an initializer, move that call to after super.onCreate() in your onCreate() method.