Android UnkownHostException on devices with a lower API level - java

When trying my app on lower api levels such as 15 or 19(on emulators and real devices), i get a UnknownHostException for a specific URL: http://jotihunt-api_v2.mysite123.nl/login mysite123 is fictional. But i don't get a UnknownHostException for other urls such as that of google . So i seems the URL is wrong, but on API level 22 for example i don't get this exception. I have a Internet Connection and i have the required permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I use this code to execute post/get requests to a web API:
#Override
protected List<WebResponse> doInBackground(WebRequest... params) {
ArrayList<WebResponse> responses = new ArrayList<>();
WebRequest current;
for(int i = 0; i < params.length; i++)
{
current = params[i];
try {
InetAddress address = InetAddress.getByName(current.getUrl().getHost());
Log.i("WebRequestTask", address.toString());
} catch (UnknownHostException exception) {
Log.e("WebRequestTask", exception.toString(), exception);
}
TRYCATCH:
try
{
if(current.getUrl() == null) break TRYCATCH;
HttpURLConnection connection = (HttpURLConnection)current.getUrl().openConnection();
switch (current.getMethod())
{
case WebRequestMethod.POST:
if(current.hasData())
{
connection.setDoOutput(true);
connection.setRequestMethod(WebRequestMethod.POST);
OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
streamWriter.write(current.getData());
streamWriter.flush();
streamWriter.close();
}
break;
}
InputStream response;
if(connection.getResponseCode() == 200)
{
/*
* Get the response stream.
* */
response = connection.getInputStream();
}
else
{
/*
* Get the error stream.
* */
response = connection.getErrorStream();
}
/**
* Read the stream.
* */
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
bufferedReader.close();
/**
* Create a response
* */
responses.add(new WebResponse(current, builder.toString(), connection.getResponseCode()));
current.setExecutionDate(new Date());
connection.disconnect();
}
catch(Exception e)
{
/**
* Print the stack trace
* */
e.printStackTrace();
/**
* Log a error.
* */
Log.e("WebRequestTask", e.toString(), e);
/**
* Add a response with as text the error message
* */
responses.add(new WebResponse(current, e.toString(), 0));
}
}
return responses;
}
The state of the objects: http://imgur.com/8ehGBUf
The creation and execution of the request:
WebRequest request = new WebRequest.Builder()
.setId(MY_REQUEST_ID)
.setMethod(WebRequestMethod.POST)
.setUrl(new UrlBuilder().append("http://jotihunt-api_v2.mysite123.nl/login").build())
.setData("sfsf")
.create();
request.executeAsync(new WebRequest.OnWebRequestCompletedCallback() {
#Override
public void onWebRequestCompleted(WebResponse response) {
Log.i("",response.getData());
}
});
This is the exception i get:
08-16 12:33:36.340 4277-4356/nl.rsdt.japp W/System.err: java.net.UnknownHostException: http://jotihunt-api_v2.mysite123.nl/login
08-16 12:33:36.342 4277-4356/nl.rsdt.japp W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:279)
08-16 12:33:36.344 4277-4356/nl.rsdt.japp W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
08-16 12:33:36.346 4277-4356/nl.rsdt.japp W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
08-16 12:33:36.348 4277-4356/nl.rsdt.japp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
08-16 12:33:36.352 4277-4356/nl.rsdt.japp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
08-16 12:33:36.355 4277-4356/nl.rsdt.japp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)
08-16 12:33:36.356 4277-4356/nl.rsdt.japp W/System.err: at com.rsdt.anl.WebRequestTask.doInBackground(WebRequestTask.java:53)
08-16 12:33:36.357 4277-4356/nl.rsdt.japp W/System.err: at com.rsdt.anl.WebRequestTask.doInBackground(WebRequestTask.java:21)
08-16 12:33:36.358 4277-4356/nl.rsdt.japp W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
08-16 12:33:36.359 4277-4356/nl.rsdt.japp W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
08-16 12:33:36.360 4277-4356/nl.rsdt.japp W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
08-16 12:33:36.365 4277-4356/nl.rsdt.japp W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
08-16 12:33:36.372 4277-4356/nl.rsdt.japp W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
08-16 12:33:36.373 4277-4356/nl.rsdt.japp W/System.err: at java.lang.Thread.run(Thread.java:848)
UPDATE
I can resolve the host with InetAdress, but it still doesn't work
UPDATE 2
I found similar issues after some more googling, it seems that underscores are not valid URLs characters.
Sources:
(i cannot include more than 2 links so i left the begin of the link out)
stackoverflow.com/questions/36074952/unknown-host-exception-using-emulator-and-httpurlconnection
code.google.com/p/android/issues/detail?id=37577
github.com/google/ExoPlayer/issues/239

I changed the hostname so that is doesn't contain a underscore, this resolved my issues. It seems that the DNS on older android versions does not support URLs with a underscore
Sources:
Similiar issue
http://code.google.com/p/android/issues/detail?id=37577

Related

Connection between Arduino bluetooth module HC-05 and Androidstudio app

i've a problem with the connection between the module HC-05 of Arduino and my android app on AndroidStudio.
When i try to connect, the log show me that after the socket creation, it doesn't make the connection. Why?
This is the part of code where i make the connection:
if(nome_device.equals("BT05") || nome_device.equals("BT06")){
BluetoothDevice dev = mBlueadapter.getRemoteDevice(MAC_address);
ParcelUuid list[] = dev.getUuids();
System.out.println("ciao");
System.out.println(dev);
BluetoothSocket btSocket = null;
int count = 0;
do {
try {
btSocket = dev.createRfcommSocketToServiceRecord(uuid); //creo un socket per comunicare
// System.out.println(dev);
// System.out.println(btSocket);
btSocket.connect(); //avvio la connessione
System.out.println(btSocket.isConnected());
} catch (IOException e) {
e.printStackTrace();
}
count++;
} while(!btSocket.isConnected() && count < 3);
try {
OutputStream outputStream = btSocket.getOutputStream();
outputStream.write(48);
} catch (IOException e) {
e.printStackTrace();
}
try {
InputStream inputStream = btSocket.getInputStream();
inputStream.skip(inputStream.available()); //pulisce il buffer
for(int i=0; i<26; i++){
byte b = (byte) inputStream.read();
System.out.println((char) b);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
btSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else
Toast.makeText(this, "The selected device is not compatible with this app! ", Toast.LENGTH_SHORT).show();
And this is the log after i click on the name of the module:
2021-03-15 21:22:43.978 8585-8585/com.example.skatex W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
2021-03-15 21:22:43.983 8585-8585/com.example.skatex D/BluetoothUtils: isSocketAllowedBySecurityPolicy start : device null
2021-03-15 21:22:43.984 8585-8585/com.example.skatex W/System.err: java.io.IOException: bt socket closed, read return: -1
2021-03-15 21:22:43.985 8585-8585/com.example.skatex W/System.err: at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:721)
2021-03-15 21:22:43.985 8585-8585/com.example.skatex W/System.err: at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:59)
2021-03-15 21:22:43.986 8585-8585/com.example.skatex W/System.err: at com.example.skatex.Bluetooth.connection(Bluetooth.java:200)
2021-03-15 21:22:43.986 8585-8585/com.example.skatex W/System.err: at com.example.skatex.Bluetooth.access$200(Bluetooth.java:32)
2021-03-15 21:22:43.986 8585-8585/com.example.skatex W/System.err: at com.example.skatex.Bluetooth$2.onItemClick(Bluetooth.java:93)
2021-03-15 21:22:43.987 8585-8585/com.example.skatex W/System.err: at android.widget.AdapterView.performItemClick(AdapterView.java:374)
2021-03-15 21:22:43.987 8585-8585/com.example.skatex W/System.err: at android.widget.AbsListView.performItemClick(AbsListView.java:1736)
2021-03-15 21:22:43.987 8585-8585/com.example.skatex W/System.err: at android.widget.AbsListView$PerformClick.run(AbsListView.java:4207)
2021-03-15 21:22:43.988 8585-8585/com.example.skatex W/System.err: at android.widget.AbsListView$7.run(AbsListView.java:6692)
2021-03-15 21:22:43.988 8585-8585/com.example.skatex W/System.err: at android.os.Handler.handleCallback(Handler.java:883)
2021-03-15 21:22:43.989 8585-8585/com.example.skatex W/System.err: at android.os.Handler.dispatchMessage(Handler.java:100)
2021-03-15 21:22:43.989 8585-8585/com.example.skatex W/System.err: at android.os.Looper.loop(Looper.java:237)
2021-03-15 21:22:43.989 8585-8585/com.example.skatex W/System.err: at android.app.ActivityThread.main(ActivityThread.java:8107)
2021-03-15 21:22:43.990 8585-8585/com.example.skatex W/System.err: at java.lang.reflect.Method.invoke(Native Method)
2021-03-15 21:22:43.990 8585-8585/com.example.skatex W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
2021-03-15 21:22:43.990 8585-8585/com.example.skatex W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
2021-03-15 21:22:43.992 8585-8585/com.example.skatex D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket#3a48555, channel: -1, mSocketIS: android.net.LocalSocketImpl$SocketInputStream#26adb6a, mSocketOS: android.net.LocalSocketImpl$SocketOutputStream#455e85bmSocket: android.net.LocalSocket#6c1d8f8 impl:android.net.LocalSocketImpl#87521d1 fd:java.io.FileDescriptor#2d34436, mSocketState: INIT
2021-03-15 21:22:43.994 8585-8585/com.example.skatex I/Choreographer: Skipped 1163 frames! The application may be doing too much work on its main thread.
If someone can help me i appreciate a lot.
isSocketAllowedBySecurityPolicy start : device null
this means you didn't get the remote device.
The application may be doing too much work on its main thread
This is another important message, you are running a long task on the main thread.
Take a look on this google example on how to manage the bluetooth connection

Added mysql-connector, but connection is still dying

I try to send query to my database in android studio, i managed this a few years back with eclipse, but now i want to code apps with this IDE
First i show you my code:
private static int getAktuelleArtikelID() throws NumberFormatException, SQLException
{
ResultSet ergebnisSet = null;
int ergebnis;
try
{
Connection verbindung = DriverManager.getConnection("jdbc:mysql://localhost:3306/foo", "bar", "foobar!");
Statement statement = verbindung.createStatement();
String abfrage = "SELECT artikel_id FROM Artikel order by 1 desc limit 1";
ergebnisSet = statement.executeQuery(abfrage);
ergebnisSet.next();
}
catch (Exception exc)
{
exc.printStackTrace();
}
ergebnis = Integer.parseInt(ergebnisSet.getString(1));
return ergebnis;
}
The Code seems right in my opinoin, i rather have the problem with jdbc.
I added the mysqlconnector 5.1.44 like eplained here:
Answer 2 from
How to Mysql JDBC Driver to android studio
But i get this error:
W/System.err: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
W/System.err: at java.lang.reflect.Constructor.newInstance0(Native Method)
W/System.err: at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
W/System.err: at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
W/System.err: at com.mysql.jdbc.Util.getInstance(Util.java:408)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
W/System.err: at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2268)
W/System.err: at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2017)
W/System.err: at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:779)
W/System.err: at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
W/System.err: at java.lang.reflect.Constructor.newInstance0(Native Method)
W/System.err: at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
W/System.err: at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
W/System.err: at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389)
W/System.err: at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
W/System.err: at java.sql.DriverManager.getConnection(DriverManager.java:569)
at java.sql.DriverManager.getConnection(DriverManager.java:219)
W/System.err: at com.example.androidcameraapi2.Database.getAktuelleArtikelID(Database.java:20)
W/System.err: at com.example.androidcameraapi2.Database.artikelHochladen(Database.java:40)
W/System.err: at com.example.androidcameraapi2.MainActivity$7.onClick(MainActivity.java:227)
W/System.err: at android.view.View.performClick(View.java:6597)
W/System.err: at android.view.View.performClickInternal(View.java:6574)
W/System.err: at android.view.View.access$3100(View.java:778)
W/System.err: at android.view.View$PerformClick.run(View.java:25885)
W/System.err: at android.os.Handler.handleCallback(Handler.java:873)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err: at android.os.Looper.loop(Looper.java:193)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6669)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
W/System.err: Caused by: android.os.NetworkOnMainThreadException
W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:117)
W/System.err: at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:105)
at java.net.InetAddress.getAllByName(InetAddress.java:1154)
W/System.err: at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:188)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:300)
W/System.err: at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2189)
W/System.err: at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2222)
W/System.err: ... 24 more
D/AndroidRuntime: Shutting down VM
Also graddle wants an update, but i already tried it and it seems to make everything worse
Here are some suggestions:
Never, ever pass a ResultSet out of method scope. You create it in a method and clean it up in that method. Load the data into objects and return those to the caller.
Never, ever create a Connection in a data access class this way. You should be using pooled connections.
Real applications log exceptions.
Stick to SQL that isn't database specific (e.g. MySQL). You keep your code portable that way.
If a value should be unique, build that requirement into your schema, not the query that fetches it.
Connection parameters like URL, username, password should be externalized from your app in configuration.
You should never use a database admin credential in an application.
Plain text credentials are an invitation to break into your database.
Here's how I might write your method:
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
* JDBC demo.
* User: mduffy
* Date: 5/8/19
* Time: 2:37 PM
* #link https://stackoverflow.com/questions/56046854/added-mysql-connector-but-connection-is-still-dying?noredirect=1#comment98735575_56046854
*/
public class JdbcDemo {
private static final String SELECT_SQL = "SELECT artikel_id FROM Artikel ";
private DataSource dataSource;
public JdbcDemo(DataSource dataSource) {
this.dataSource = dataSource;
}
public List<String> getAktuelleArtikelID() {
List<String> aktuelleArtikelId = new ArrayList<>();
ResultSet rs = null;
Statement st = null;
try {
st = this.dataSource.getConnection().createStatement();
rs = st.executeQuery(SELECT_SQL);
while (rs.next()) {
aktuelleArtikelId.add(rs.getString(1));
}
}
catch (Exception e) {
e.printStackTrace();
} finally {
close(rs);
close(st);
}
return aktuelleArtikelId;
}
// Should be in a utility class
private static void close(ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void close(Statement st) {
try {
if (st != null) {
st.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

Unable to resolve host "My URL" - No address associated with hostname

The exception occurs randomly and then its hard to get rid of. I am tired of this error and despite the fact that I have tried almost everything on stackoverflow from changing url to respective IP address, using real device, adding internet permissions as mentioned or checking wifi connection. Everything is all right except the error which keeps coming back. Yes I also added checking connection code as below :
try {
ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo().isConnectedOrConnecting()) {
URL url = new URL(urlx);
HttpURLConnection urlc = (HttpURLConnection) url
.openConnection();
urlc.setConnectTimeout(1000); // mTimeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
runOnUiThread(new Runnable() {
public void run() {
//Do something on UiThread
upsuccess = true;
}
});
} else {
runOnUiThread(new Runnable() {
public void run() {
//Do something on UiThread
upsuccess = false;
}
});
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and System.setProperty("http.proxyHost", "myurl.com");
System.setProperty("http.proxyPort", "8080");
but each of them separately as well as together did not fetch me any useful results. Can you suggest me what to do?
I am basically doing this : I am uploading a pdf file on my server and loading the google docs viewer url with that url. I however see the following exception several times. I also added retrying in case I find the exception but the exception randomly happens and is not easy to get out of if you encounter it.
Exception :
java.net.UnknownHostException: Unable to resolve host "myurl.com": No
address associated with hostname 07-20 01:12:11.554
24907-24997/securitymsg.listmydocs W/System.err: at
java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:95)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at java.net.InetAddress.getAllByName(InetAddress.java:752) 07-20
01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err: at
okhttp3.Dns$1.lookup(Dns.java:39) 07-20 01:12:11.554
24907-24997/securitymsg.listmydocs W/System.err: at
okhttp3.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:173)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
okhttp3.internal.http.RouteSelector.nextProxy(RouteSelector.java:139)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at okhttp3.internal.http.RouteSelector.next(RouteSelector.java:81)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:172)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:123)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:93)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:296) 07-20
01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err: at
okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at okhttp3.RealCall.getResponse(RealCall.java:243) 07-20 01:12:11.554
24907-24997/securitymsg.listmydocs W/System.err: at
okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:201)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:163)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at okhttp3.RealCall.execute(RealCall.java:57) 07-20 01:12:11.554
24907-24997/securitymsg.listmydocs W/System.err: at
securitymsg.listmydocs.CloudViewer$UploadFileAsync.doInBackground(CloudViewer.java:678)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
securitymsg.listmydocs.CloudViewer$UploadFileAsync.doInBackground(CloudViewer.java:650)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at android.os.AsyncTask$2.call(AsyncTask.java:305) 07-20 01:12:11.554
24907-24997/securitymsg.listmydocs W/System.err: at
java.util.concurrent.FutureTask.run(FutureTask.java:237) 07-20
01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err: at
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 07-20
01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err: at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at java.lang.Thread.run(Thread.java:761) 07-20 01:12:13.016
24907-24907/securitymsg.listmydocs W/cr_BindingManager: Cannot call
determinedVisibility() - never saw a connection for the pid: 24907
07-20 01:12:13.677 24907-24907/securitymsg.listmydocs
W/cr_BindingManager: Cannot call determinedVisibility() - never saw a
connection for the pid: 24907 07-20 01:12:13.678
24907-24907/securitymsg.listmydocs W/cr_BindingManager: Cannot call
determinedVisibility() - never saw a connection for the pid: 24907
My Permissions in manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
My code to upload file :
*PHP :
<?php
$file_path = "images/";
$neran = $_GET['neran'];
$ext = pathinfo(basename( $_FILES['uploaded_file']['name']), PATHINFO_EXTENSION);
$file_path = "images/".$neran.".".$ext;
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path) ){
echo "success";
} else{
echo "fail";
}
?>
Android side (I use Retrofit) : The following code is in doinbackground block of AsyncTask
String file_path = f.getAbsolutePath();
OkHttpClient client = new OkHttpClient();
RequestBody file_body = RequestBody.create(MediaType.parse(content_type),f);
Log.e("msh", content_type);
RequestBody request_body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("type",content_type)
.addFormDataPart("uploaded_file",file_path.substring(file_path.lastIndexOf("/")+1), file_body)
.build();
Request request = new Request.Builder()
.url("http://reviewitapp.co/retrofit_example/save_file.php?neran="+neran)
.post(request_body)
.build();
response = client.newCall(request).execute();
} catch (UnknownHostException e) {
e.printStackTrace();
/*uploadFile(selectedFilePath);*/
upsuccess = false;
} catch (IOException e) {
e.printStackTrace();
upsuccess = false;
} catch (NullPointerException e) {
e.printStackTrace();
/*uploadFile(selectedFilePath);*/
upsuccess = false;
}
if(response!=null) {
if (response.isSuccessful()) {
upsuccess = true;
}
response.body().close();
}

Android FATAL EXCEPTION Asynch Task #1

I am trying to make a simple weather app. Everytime I try and access the Yahoo weather api to return a JSON object, I get this exception. To do the task without the api, I copy pasted the JSON object into a separate string and have been working with that string as the JSON object.
This is my asynch task:
public class WeatherInfoThread extends AsyncTask{
#Override
protected String doInBackground(Void... params) {
String resultString = null;
try {
url = new URL("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22"+location+"%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream = connection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
try {
jsonInfo = bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
resultString = jsonInfo;
try {
weatherinfo = new JSONObject(testString);
// Log.d(JSON_INFO,weatherinfo.toString()+"df");
JSONObject channel = weatherinfo.getJSONObject("query").getJSONObject("results").getJSONObject("channel");
JSONObject item = channel.getJSONObject("item");
currentTemp = item.getJSONObject("condition");
cCurrentInt = currentTemp.getInt("code");
forecast = item.getJSONArray("forecast");
cOne = forecast.getJSONObject(1).getString("text");
cTwo = forecast.getJSONObject(2).getString("text");
cThree = forecast.getJSONObject(3).getString("text");
cFour = forecast.getJSONObject(4).getString("text");
cFive = forecast.getJSONObject(5).getString("text");
dOne = forecast.getJSONObject(1).getString("day");
dTwo = forecast.getJSONObject(2).getString("day");
dThree = forecast.getJSONObject(3).getString("day");
dFour = forecast.getJSONObject(4).getString("day");
dFive = forecast.getJSONObject(5).getString("day");
// Log.d(JSON_INFO,forecast.get(1).toString()+"ddf");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
This is the error I got:
12-16 16:48:06.677 10523-10549/com.example.aakashmahesh.weatherapp E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at libcore.net.http.HttpConnection.(HttpConnection.java:70)
at libcore.net.http.HttpConnection.(HttpConnection.java:50)
at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461)
at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)
at com.example.aakashmahesh.weatherapp.MainActivity$WeatherInfoThread.doInBackground(MainActivity.java:269)
at com.example.aakashmahesh.weatherapp.MainActivity$WeatherInfoThread.doInBackground(MainActivity.java:250)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137) 
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 
at java.lang.Thread.run(Thread.java:856) 
Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
at libcore.io.Posix.getaddrinfo(Native Method)
at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:55)
at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 
at java.net.InetAddress.getAllByName(InetAddress.java:214) 
at libcore.net.http.HttpConnection.(HttpConnection.java:70) 
at libcore.net.http.HttpConnection.(HttpConnection.java:50) 
at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340) 
at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87) 
at libcore.net.http.HttpConnection.connect(HttpConnection.java:128) 
at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315) 
at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461) 
at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433) 
at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289) 
at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239) 
at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273) 
at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168) 
at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271) 
at com.example.aakashmahesh.weatherapp.MainActivity$WeatherInfoThread.doInBackground(MainActivity.java:269) 
at com.example.aakashmahesh.weatherapp.MainActivity$WeatherInfoThread.doInBackground(MainActivity.java:250) 
at android.os.AsyncTask$2.call(AsyncTask.java:287) 
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 
at java.util.concurrent.FutureTask.run(FutureTask.java:137) 
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 
at java.lang.Thread.run(Thread.java:856) 
Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied)
at libcore.io.Posix.getaddrinfo(Native Method) 
at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:55) 
at java.net.InetAddress.lookupHostByName(InetAddress.java:405) 
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 
at java.net.InetAddress.getAllByName(InetAddress.java:214) 
at libcore.net.http.HttpConnection.(HttpConnection.java:70) 
at libcore.net.http.HttpConnection.(HttpConnection.java:50) 
at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340) 
at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87) 
at libcore.net.http.HttpConnection.connect(HttpConnection.java:128) 
at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315) 
at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461) 
at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433) 
at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289) 
at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239) 
at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273) 
at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168) 
at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271) 
at com.example.aakashmahesh.weatherapp.MainActivity$WeatherInfoThread.doInBackground(MainActivity.java:269) 
at com.example.aakashmahesh.weatherapp.MainActivity$WeatherInfoThread.doInBackground(MainActivity.java:250) 
at android.os.AsyncTask$2.call(AsyncTask.java:287) 
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 
at java.util.concurrent.FutureTask.run(FutureTask.java:137) 
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 
at java.lang.Thread.run(Thread.java:856) 
12-16 16:48:06.677 1370-17136/system_process W/ActivityManager: Force finishing activity com.example.aakashmahesh.weatherapp/.MainActivity
12-16 16:48:06.737 1370-17136/system_process D/dalvikvm: GC_FOR_ALLOC freed 647K, 12% free 16559K/18695K, paused 10ms, total 10ms
12-16 16:48:06.767 10523-10523/com.example.aakashmahesh.weatherapp D/libEGL: loaded /system/lib/egl/libEGL_emulation.so
12-16 16:48:06.767 10523-10523/com.example.aakashmahesh.weatherapp D/libEGL: loaded /system/lib/egl/libGLESv1_CM_emulation.so
12-16 16:48:06.767 10523-10523/com.example.aakashmahesh.weatherapp D/libEGL: loaded /system/lib/egl/libGLESv2_emulation.so
[ 12-16 16:48:06.767 10523:10523 D/ ]
HostConnection::get() New Host Connection established 0xb8071030, tid 10523
read the error, will you?
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?) at
May be you did not write the permission to access Internet in Manifest file
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)

Parsing a text file in android from an HTML

So I have been working on this for a bit and hit a brick wall. It keeps giving me a fatal error when it start to process.
So basically I want to read in a text file off the internet and then parse it so I can start to break that apart and use a JSON parser to deal with JSON data. But that further down the line (and i have the part built). I just am having trouble with the connection and downloading of the data. I just want to read in the text file and then print it out again.
Thank you for any help with this.
This is what it gives me
01-26 15:11:48.373 1958-1958/com.example.mmillar.urljsonparser I/art: Not late-enabling -Xcheck:jni (already on)
01-26 15:11:48.556 1958-1958/com.example.mmillar.urljsonparser D/HTML P1:: http://textfiles.com/100/914bbs.txt
01-26 15:11:48.556 1958-1958/com.example.mmillar.urljsonparser D/HTML P2:: http://textfiles.com/100/914bbs.txt
01-26 15:11:48.557 1958-1958/com.example.mmillar.urljsonparser D/HTML inJSON:: http://textfiles.com/100/914bbs.txt
01-26 15:11:48.569 1958-1958/com.example.mmillar.urljsonparser D/Status:: Connection Opened
01-26 15:11:48.569 1958-1958/com.example.mmillar.urljsonparser D/Status:: Closing connection
01-26 15:11:48.569 1958-1958/com.example.mmillar.urljsonparser D/AndroidRuntime: Shutting down VM
01-26 15:11:48.570 1958-1958/com.example.mmillar.urljsonparser E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mmillar.urljsonparser, PID: 1958
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mmillar.urljsonparser/com.example.mmillar.urljsonparser.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:332)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:199)
at com.example.mmillar.urljsonparser.JSONParser.getStream(JSONParser.java:40)
at com.example.mmillar.urljsonparser.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
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:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
01-26 15:11:53.474 1958-1958/? I/Process: Sending signal. PID: 1958 SIG: 9
So I'm a bit lost to where this is going wrong. I think I have everything set up and going good. Like the inputstream, bufferreader and all. So here is what I have.
This is the Parser program
public class JSONParser extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... inputUrl) {
getStream(inputUrl[0]);
return null;
}
public void getStream(String urlString)
{
Log.d("HTML inJSON: ", urlString );
//variables for the connection and downloading the JSON data
URL url = null;
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
url = new URL(urlString);
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
Log.d("Status:","Connection Opened");
//read in the data
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
//build the data for parsing
StringBuilder myString = new StringBuilder();
String line;
while((line = br.readLine()) !=null)
{
myString.append(line);
}
Log.d("Status:"," JSON loaded into string");
Log.d("Total:", myString.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
if (urlConnection != null)
{
//close the connection
urlConnection.disconnect();
Log.d("Status:", " Closing connection");
}
}
}
}
And here is the main program I just run the thing because I just want to output from the file to the console I just want to make sure it works.
public class MainActivity extends AppCompatActivity {
//http://textfiles.com/100/914bbs.txt
private String testHtml = "http://textfiles.com/100/914bbs.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("HTML P1: ", testHtml );
JSONParser jp = new JSONParser();
Log.d("HTML P2: ", testHtml );
jp.getStream(testHtml);
Log.d("HTML P3: ", testHtml);
}
instead of using
jp.getStream(testHtml);
use
jp.execute("stream url here");
Currently you are trying to create a function in your Asynctask, but are not leveraging the use of AsyncTask. It still tries to make a HttpConnection on the mainThread, and that throws the exception.

Categories

Resources