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();
}
Related
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
I try count data and remove Duplicate data by the following code ,but I got an error message with this code.
Can anyone help me?
StructorRecords.java
public class StructorRecords {
public String recorusername;
public String id;
public String full_name;
public String recordimg;
public Integer count;}
counter.java
public static void orderbylike(StructorRecords data) {
if (G.bollike) {
G.savelike.add(data);
} else {
Iterator itr = G.savelike.iterator();
int i = 1;
while (itr.hasNext()) {
StructorRecords SR = (StructorRecords) itr.next();
if (SR.id.equals(data.id)) {
data.count = SR.count + 1;
G.savelike.set(i, data);
} else {
G.savelike.add(data);
}
i++;
}
}
}
this is logs that get me
LOG
02-01 17:19:23.142 7587-9416/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: java.util.ConcurrentModificationException
02-01 17:19:23.152 7587-9416/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:569)
02-01 17:19:23.152 7587-9416/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at sanjinsgr.limosoftwaregroup.ir.instasanj.counter.orderbylike(counter.java:21)
02-01 17:19:23.152 7587-9416/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at sanjinsgr.limosoftwaregroup.ir.instasanj.loginActivity$11.run(loginActivity.java:460)
02-01 17:19:23.162 7587-9416/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at java.lang.Thread.run(Thread.java:856)
02-01 17:19:23.451 7587-9472/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: java.util.ConcurrentModificationException
02-01 17:19:23.451 7587-9472/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:569)
02-01 17:19:23.451 7587-9472/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at sanjinsgr.limosoftwaregroup.ir.instasanj.counter.orderbylike(counter.java:21)
02-01 17:19:23.461 7587-9472/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at sanjinsgr.limosoftwaregroup.ir.instasanj.loginActivity$11.run(loginActivity.java:460)
02-01 17:19:23.461 7587-9472/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at java.lang.Thread.run(Thread.java:856)
02-01 17:19:23.583 7587-9417/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: java.util.ConcurrentModificationException
02-01 17:19:23.583 7587-9417/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:569)
02-01 17:19:23.583 7587-9417/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at sanjinsgr.limosoftwaregroup.ir.instasanj.counter.orderbylike(counter.java:21)
02-01 17:19:23.583 7587-9417/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at sanjinsgr.limosoftwaregroup.ir.instasanj.loginActivity$11.run(loginActivity.java:460)
02-01 17:19:23.592 7587-9417/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at java.lang.Thread.run(Thread.java:856)
Error is there because
you try to add element to the List (I assume G.savelike is a List), while you iterate through the same list with iterator.
It is not allowed. Instead make another tmpList for all new elements, add them in it and after iterator loop done use addAll() method.
Like that:
List<StructorRecords> tmpList = new ArrayList<StructorRecords> tmpList;
while (itr.hasNext()) {
StructorRecords SR = (StructorRecords) itr.next();
if (SR.id.equals(data.id)) {
data.count = SR.count + 1;
G.savelike.set(i, data);
} else {
// here put to temp list
tmpList.add(data);
}
i++;
}
// add all new elements
G.savelike.addAll(tmpList);
You can use the Collections from java concurrency package which will provide fail safe iterator, If you use Collections from java.util package the iterators are of Fail fast type and will throw Concurrent modification exception whenever you iterate and try update the collection at the same time.
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?)
I have uploaded file and when I try to get the shared link then it gives NullPointerException.
FileInputStream fis = new FileInputStream(mFile);
String path = mPath + mFile.getName();
DropboxAPI.Entry response = mApi.putFile(path, fis,
mFile.length(), null, new ProgressListener() {
#Override
public long progressInterval() {
// Update the progress bar every half-second or so
return 500;
}
#Override
public void onProgress(long bytes, long total) {
publishProgress(bytes);
}
});
Log.i("DbExampleLog", "The uploaded file's rev is: " + response.rev);
if (response != null) {
mErrorMsg=response.path;
Log.e("DbExampleLog", "*****"+response.path+" The uploaded file's rev is: " + response.rev);
DropboxAPI.DropboxLink shareLink = mApi.share(response.path);
Log.e("DbExampleLog", "*****"+shareLink+" The uploaded file's rev is: " + response.rev);
if(shareLink!=null) {
if(shareLink.url!=null) {
Log.e("Null error URL*****",""+shareLink.url);
Log.e("Null error URL*****",""+getShareURL(shareLink.url));
String shareAddress = getShareURL(shareLink.url).toString();
Log.e("DbExampleLog", "URL -" + shareAddress + "*****" + response.path + " The uploaded file's rev is: " + response.rev);
}
else
Log.e("Null error URL*****",""+shareLink.url);
}
else{
Log.e("Null error*****",""+shareLink);
}
return true;
}
It returns like -
12-05 12:09:09.207 7335-7502/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/DbExampleLog: *****/1480919937073.jpg The uploaded file's rev is: 2ef4a7ca38e
12-05 12:09:10.966 7335-7502/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/DbExampleLog: *****com.dropbox.client2.DropboxAPI$DropboxLink#d9d5da1 The uploaded file's rev is: 2ef4a7ca38e
12-05 12:09:10.966 7335-7502/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/Null error URL*****: https://db.tt/ru6e39XK0
12-05 12:09:12.457 7335-7502/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/Null error URL*****: null
12-05 12:09:13.520 7335-7502/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.trucker.gtd.satyaki.dropboxintegrationapiv1, PID: 7335
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:318)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.UploadFile.doInBackground(UploadFile.java:147)
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.UploadFile.doInBackground(UploadFile.java:63)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
12-05 12:09:13.645 1248-1248/? E/EGL_emulation: tid 1248: eglCreateSyncKHR(1641): error 0x3004 (EGL_BAD_ATTRIBUTE)
12-05 12:09:13.796 2071-2205/com.android.launcher3 E/EGL_emulation: tid 2205: eglSurfaceAttrib(1146): error 0x3009 (EGL_BAD_MATCH)
12-05 12:09:14.006 1530-1640/system_process E/EGL_emulation: tid 1640: eglSurfaceAttrib(1146): error 0x3009 (EGL_BAD_MATCH)
12-05 12:09:14.304 7335-7335/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/WindowManager: android.view.WindowLeaked: Activity com.trucker.gtd.satyaki.dropboxintegrationapiv1.Main has leaked window DecorView#3bf9cac[] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:417)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:331)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.app.Dialog.show(Dialog.java:316)
at android.app.AlertDialog$Builder.show(AlertDialog.java:1112)
at com.dropbox.client2.android.AuthActivity.checkAppBeforeAuth(AuthActivity.java:284)
at com.dropbox.client2.android.AndroidAuthSession.startAuthentication(AndroidAuthSession.java:213)
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.Main.onActivityResult(Main.java:132)
at android.app.Activity.dispatchActivityResult(Activity.java:6915)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4049)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
12-05 12:09:14.310 7335-7335/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/WindowManager: android.view.WindowLeaked: Activity com.trucker.gtd.satyaki.dropboxintegrationapiv1.Main has leaked window DecorView#e8ad10a[] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:417)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:331)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.app.Dialog.show(Dialog.java:316)
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.UploadFile.<init>(UploadFile.java:98)
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.Main.setLoggedIn(Main.java:144)
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.Main.onResume(Main.java:168)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1269)
at android.app.Activity.performResume(Activity.java:6766)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3377)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3440)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1510)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Mainly in this particular line-
getShareURL(shareLink.url)
Please suggest me why this error occur, but yesterday using this code it worked.
UPDATE CODE ASKED BY Greg
String getShareURL(String strURL) {
URLConnection conn = null;
String redirectedUrl = null;
try {
URL inputURL = new URL(strURL);
conn = inputURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
System.out.println("Redirected URL: " + conn.getURL());
Log.e("Get Redirected URL",""+conn.getURL());
redirectedUrl = conn.getURL().toString();
is.close();
} catch (MalformedURLException e) {
Log.e("TAG", "Please input a valid URL");
} catch (IOException ioe) {
Log.e("TAG", "Can not connect to the URL");
}
return redirectedUrl;
}
This code taken from Share file in Dropbox
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