java.net.UnknownHostException: Unable to resolve host "api.themoviedb.org - java

I'm getting this error message "java.net.UnknownHostException: Unable to resolve host "api.themoviedb.org": No address associated with hostname".
All the stackoverflow posts I read said that the manifest file might be wrong, but I think at this point it's right, so I'm not sure how to continue.
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.flixster">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
MainActivity.java:
package com.example.flixster;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.codepath.asynchttpclient.AsyncHttpClient;
import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import okhttp3.Headers;
import static com.facebook.stetho.inspector.network.PrettyPrinterDisplayType.JSON;
public class MainActivity extends AppCompatActivity {
public static final String NOW_PLAYING_URL =
"https://api.themoviedb.org/3//movie/now_playing?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed";
public static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// make get request on URL to get currently playing movies
AsyncHttpClient client = new AsyncHttpClient();
// JSON response handler since API returns JSON- deals with response success/failure
client.get(NOW_PLAYING_URL, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Headers headers, JsonHttpResponseHandler.JSON json) {
Log.d(TAG, "onSuccess");
JSONObject jsonObject = json.jsonObject;
try {
JSONArray results = jsonObject.getJSONArray("result");
Log.i(TAG, "Results: " + results.toString());
} catch (JSONException e) {
Log.e(TAG, "Hit json exception", e);
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Headers headers, String response, Throwable throwable) {
Log.d(TAG, "onFailure");
}
});
}
}

Looking at your code I found 2 issues:
Your NOW_PLAYING_URL has an additional slash (themoviedb.org/3//movie/) after 3 so replace the string as
public static final String NOW_PLAYING_URL = "https://api.themoviedb.org/3/movie/now_playing?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed";
That was the reason why your api call returns a failure.
Next, the response is success but in your onSuccess() try block you are fetching data for "result" but your API response returns "results" so replace that key as below and you should not be having any issues.
JSONArray results = jsonObject.getJSONArray("results");
Hope this helps.

Related

Get JSON Data response from URL using Android?

I am trying to get JSON response from a URL. I have tried below code several time but i couldn't get the response. Please Help me to sort this out
I am using API level 29
Here i am using this url for getting data, url -> https://api.androidhive.info/contacts/
My Code :
public class MainActivity extends AppCompatActivity {
private final static String URL = "https://api.androidhive.info/contacts/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue queue = Volley.newRequestQueue(this);
JsonArrayRequest arrayRequest = new JsonArrayRequest(
Request.Method.GET, URL,null,new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("Response : ", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error : ", error.getMessage());
}
});
queue.add(arrayRequest);
}
}
AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.volleyparsing">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The Logcat response :
2020-05-03 22:19:49.600 11515-11515/? I/e.volleyparsin: Not late-enabling -Xcheck:jni (already on)
2020-05-03 22:19:49.749 11515-11515/? E/e.volleyparsin: Unknown bits set in runtime_flags: 0x8000
2020-05-03 22:19:53.066 11515-11515/com.example.volleyparsing D/Volley: [2] 2.onErrorResponse: Error :
2020-05-03 22:19:50.513 11515-11545/com.example.volleyparsing W/libc: Unable to set property "qemu.gles" to "1": connection failed; errno=13 (Permission denied)
Your response is jsonObject not jsonArray. That's way you are getting parsing error. Use jsonObject:
RequestQueue queue = Volley.newRequestQueue(context);
JsonObjectRequest objectRequest = new JsonObjectRequest(
Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray jsonArray = null;
try {
jsonArray = response.getJSONArray("contacts");
Log.d("Response : ", jsonArray.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error : ", error.getMessage());
}
});
queue.add(objectRequest);
Use android:usesCleartextTraffic="true" on your manifest file on application.
<application
...
android:usesCleartextTraffic="true"
... >

Cannot connect my android device to my python socket server?

I have a python socket server which my android devices are meant to connect to but my android emulator is able to connect to it but my phone is not able to connect to it and gives the error ETIMEDOUT. Can anyone tell what is wrong with it?
Python server:
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = socket.gethostname()
port = 12345
s.bind((host, port))
s.listen(10)
while True:
c, addr = s.accept()
print(addr)
c.send(bytes('Thank you for connecting','utf-8'))
c.close()
Android Client:
Client.java:
package com.example.abhishekroul.clientapp;
import android.os.AsyncTask;
import android.widget.TextView;
//import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client extends AsyncTask<Void,Void,Void>
{
String dstAddress;
int dstPort;
String response="";
TextView textResponse;
Client(String addr,int port, TextView textResponse)
{
dstAddress=addr;
dstPort=port;
this.textResponse=textResponse;
}
#Override
protected Void doInBackground(Void ...arg0)
{
Socket socket=null;
try
{
socket=new Socket(dstAddress,dstPort);
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream(1024);
byte[] buffer=new byte[1024];
int bytesRead;
InputStream inputStream= socket.getInputStream();
while((bytesRead=inputStream.read(buffer))!=-1)
{
byteArrayOutputStream.write(buffer,0,bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
}
catch(UnknownHostException e)
{
e.printStackTrace();
response="UnknownHostException:"+e.toString();
}
catch (IOException e)
{
e.printStackTrace();
response="IOException:"+e.toString();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
textResponse.setText(response);
super.onPostExecute(result);
}
}
MainActivity.java:
package com.example.abhishekroul.clientapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText address, port;
TextView response;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
address = (EditText) findViewById(R.id.address);
port = (EditText) findViewById(R.id.port);
response = (TextView) findViewById(R.id.response);
}
public void funcConnect(View v)
{
Client client= new Client(address.getText().toString(),Integer.parseInt(port.getText().toString()),response);
client.execute();
}
public void funcClear(View v)
{
response.setText("");
}
}
Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.abhishekroul.clientapp" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
on emulator its connecting but on an android phone it shows ETIMEDOUT error.
So after lot of testing I have found the solution to the problem by using the port 80 the HTTP protocol which is generally never blocked as HTTP based processes will stop as this port is generally used by this protocol so it is better to user port 80 for socket creation.

Android fetch data from mySql

I have to get some data from a MySQL database on server. I have the following code.but the app crashes when I run it. I also get the Permission denied (missing INTERNET permission?) in my Logcat even though I specified the internet permission in my Android Manifest.
Any idea what might be wrong here?
Java file
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
connect();
}
private void connect() {
String data;
List<String> r = new ArrayList<String>();
ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r);
ListView list=(ListView)findViewById(R.id.listView1);
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://xxxxx/data.php");
HttpResponse response = client.execute(request);
HttpEntity entity=response.getEntity();
data=EntityUtils.toString(entity);
Log.e("STRING", data);
try {
JSONArray json=new JSONArray(data);
for(int i=0;i<json.length(); i++)
{
JSONObject obj=json.getJSONObject(i);
String name=obj.getString("name");
String desc=obj.getString("description");
// String lat=obj.getString("lat");
Log.e("STRING", name);
r.add(name);
r.add(desc);
// r.add(lat);
list.setAdapter(adapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClientProtocolException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
} catch (IOException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.diana.menu" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<uses-permission android:name="android.permission.INTERNET"/>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
data.php
<?php
$conn=mysql_connect('localhost', 'xxxx', 'xxxxx','u199776286_pois');
if(!$conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT name, description FROM pois';
mysql_select_db('u199776286_pois');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "NAME : {$row['name']} <br> ".
"DESCRIPTION : {$row['description']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
my logcat
This happens because you're connecting to your MySQL server from the main UI thread. create a secondary thread (or async task) to connect and to get the results.
Use Async Task to get the data from your database..
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Writing the above code is not at all a better way to get rid from NetworkOnMainThreadException . You have to use any background thread for doing network operation in android above api 11 such as Asynch Task , Intent Service etc.
How to fix android.os.NetworkOnMainThreadException?
You can also use Executors for network task's
Executors.newSingleThreadExecutor().submit(new Runnable() {
#Override
public void run() {
//You can performed your task here.
}
});
Add Internet Permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
Use Asynck Task like
List<String> r = new ArrayList<String>();
Need to declare out of connect();
with Oncreate
new LongOperation().execute("");
now create
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
connect();
return "Executed";
}
#Override
protected void onPostExecute(String result) {
ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r);
ListView list=(ListView)findViewById(R.id.listView1);
list.setAdapter(adapter);
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
// need to remove Ui control from connect(); and that require value
bind it on onPostExecute
use Async. For more help check this

GcmBroadcastReceiver not fired on Android Lollipop

I am writing an GCM support for Android 5.0.1. The app registers fine and sending a message to the server also seems ok, however the onReceive method on my BroadcastReceiver doesn't get fired.
But I am able to see my gsm message id in the log cat.
Here is the manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.freshmanapp.gcmtest">
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="8" />
<permission
android:name="com.freshmanapp.gcmtest.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.freshmanapp.gcmtest.permission.C2D_MESSAGE" />
<application
android:allowBackup="true"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<meta-data
android:name="com.google.android.gms.version"
android:value="6" />
<receiver
android:name="com.freshmanapp.gcmtest.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.freshmanapp.gcmtest" />
</intent-filter>
</receiver>
<service android:name="com.freshmanapp.gcmtest.GcmIntentService" />
</manifest>
and here is my GcmBroadcastReceiver.java
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("GCM Reciever","Triggered");
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
MainActivity.java
package com.freshmanapp.gcmtest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by Ramkumar on 16/04/15.
*/
public class MainActivity extends Activity {
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private static final String TAG = "GCMRelated";
GoogleCloudMessaging gcm;
AtomicInteger msgId = new AtomicInteger();
String regid;
#Override
protected void onCreate(Bundle savedInstanceState) {
startService(new Intent(this, GcmIntentService.class));
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
regid = getRegistrationId(getApplicationContext());
Log.i("Registered Id ",regid);
if (regid.isEmpty()) {
new RegisterApp(getApplicationContext(), gcm, getAppVersion(getApplicationContext())).execute();
Toast.makeText(getApplicationContext(), "Device Registered Now", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Device already Registered ("+regid+")", Toast.LENGTH_SHORT).show();
}
}
}
/**
* Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
/**
* Gets the current registration ID for application on GCM service.
* <p>
* If result is empty, the app needs to register.
*
* #return registration ID, or empty string if there is no existing
* registration ID.
*/
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(getApplicationContext());
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
/**
* #return Application's {#code SharedPreferences}.
*/
private SharedPreferences getGCMPreferences(Context context) {
// This sample app persists the registration ID in shared preferences, but
// how you store the regID in your app is up to you.
return getSharedPreferences(MainActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
}
/**
* #return Application's version code from the {#code PackageManager}.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
}
Are you calling registerReceiver in your Activity?
You will need to call something like registerReceiver(new GcmBroadcastReceiver(), new IntentFilter(DISPLAY_MESSAGE_ACTION));

UnknownHostException (webservice http-get)

I have this simple code, that makes a get to a webservice.
For some reason it cant connect and gives the error in the log unknownHostException
This is the code:
String URL = "http://services.sapo.pt/EPG/GetChannelList";
String result = "";
final String tag = "Data received: ";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button btnSearch = (Button)findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
callWebService();
}
});
} // end onCreate()
public void callWebService(){
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(URL);
ResponseHandler<String> handler = new BasicResponseHandler();
try {
result = httpclient.execute(request, handler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
Log.i(tag, result);
}
This is part of my manifest
<permission android:name="android.permission.INTERNET"/>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".AndroidApp"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I found the solution.
I putted the internet permission using the GUI in manifest which added the tag
< permission android:name"android.permission.INTERNET"/>
Then by hand, i putted the correct tag that is:
< uses-permission android:name="android.permission.INTERNET" />
which is a different tag and it worked. GUI fail.
Not sure if you have already checked this, but please check if you are behind a proxy or firewall. Here is a way to configure the HttpClient for a proxy and official apache documentation.

Categories

Resources