I am trying to get json data from a table that i am querying in my wamp server with a select.php the data shows in the browser but android for some reason can't download the data.
select.php
<?php
$conn=mysqli_connect("localhost","root","", "shady") or die("Unable to connect");
if(mysqli_connect_error($conn)) {
echo "Failed To Connect";
}
$qry = "SELECT * FROM `wellden`";
$res = mysqli_query($conn, $qry);
if ($res) {
while ($row = mysqli_fetch_array($res)) {
$flag[] = $row;
}
// returns tthe json data
echo json_encode($flag);
}
mysqli_close($conn);
?>
works fine and prints data in browser:
but for some weird reason android cant seem to get the echoed data from the php file.
Android code:
public class ListOfCourses extends AppCompatActivity {
ListView listView;
ArrayList<String> arrayList;
ArrayAdapter<String> arrayAdapter;
String REG_URL;
public class Listdata extends AsyncTask<String, Void, String>{
HttpURLConnection conn;
URL url;
String jsonStringForMe;
#Override
protected String doInBackground(String... strings) {
// MOST CRITICAL PART.....................................
String s = strings[0];
try {
url = new URL(s);
conn = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line);
}
// Stroring it to use in the onPostExecute Cause we do not have any Button in this view
jsonStringForMe = sb.toString();
return jsonStringForMe;
}catch (Exception e){
return e.getMessage();
}
// MOST CRITICA PART ENDS HERE..............................
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// JsonParsing Happens Here
Toast.makeText(getApplicationContext(), jsonStringForMe+" ", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_courses);
Listdata listdata = new Listdata();
REG_URL="http://1.0.0.2/android_db_pool/select.php";
listdata.execute(REG_URL);
}
}
but everytime the jsonStringForMe gives me null in postExecute everything seems Ok should work, but for some reason does not work. What can be the cause of the json data not receiving in the android end ?
EDIT
I added internet permission also:
AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.slimshady.jamalsir1">
<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>
<activity android:name=".ListOfCourses"></activity>
</application>
</manifest>
EDIT 2
It may seem that ip address may be an issue but it is not insertion works fine with insert.php, and i can get the json data with the ip address that is my server's ip address 1.0.0.2. In android i am using the ip address of the server not localhost in only php i am using localhost because the php file is in my server.
As already commented;
Stroring it to use in the onPostExecute Cause we do not have any
Button in this view
You didn't add or use to get the json in onPostExecute() method but you have added the Toast in onPreExecute.
Try to add onPostExecute() then show Toast.
protected void onPreExecute()
Runs on the UI thread before doInBackground(Params...).
https://developer.android.com/reference/android/os/AsyncTask#onPreExecute%28%29
Related
I created a small demo program
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
(new Requester()).execute();
}
static class Requester extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... voids) {
URL loginURL;
HttpURLConnection urlConnection;
try {
loginURL = new URL("https://google.com");
urlConnection = (HttpURLConnection) loginURL.openConnection();
int responseCode = urlConnection.getResponseCode();
Log.d("response", "response is" + responseCode);
}
catch (MalformedURLException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
return null;
}
}
}
I set a breakpoint at int responseCode = urlConnection.getResponseCode(); and then step through. It never gets to the next line for me to read the response code. There is no error; it just hangs forever.
I feel like this is the most basic urlconnection code I can come up with. Perhaps I'm missing something important.
Edit: I have indeed added the internet permission to my manifest. Here is my entire manifest just in case you want it:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testingcorruptbitmap">
<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>
Update:
I've edited my code to include reading from the request.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
(new Requester()).execute();
}
static class Requester extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... voids) {
URL loginURL;
HttpURLConnection urlConnection;
try {
loginURL = new URL("https://google.com");
urlConnection = (HttpURLConnection) loginURL.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = reader.readLine();
Log.d("urlconnection", "line is " + line);
int responseCode = urlConnection.getResponseCode();
Log.d("urlconnection", "response is " + responseCode);
}
catch (MalformedURLException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
return null;
}
}
}
When I set a breakpoint at the beginning of the code and walkthrough, it freezes at InputStream in = new BufferedInputStream(urlConnection.getInputStream());
So this does not solve the issue.
Solution update:
Something was wrong with the android emulated device I was working on. I restarted it and the problem is now fixed. If you know of the reason why this would happen please let me and the rest of the internet know, so we can avoid it!
You are not doing an actual request, so there is no response either, that's why your code is waiting for a response.
See here: Http Get using Android HttpURLConnection
have you added the INTERNET permission in your AndroidManifest? If not do so.
If you did take a look at this document by android-dev. It shows how to make simple requests using the volley library.
Hope this helps
Edit:
I personally never worked with URLConnection but according to the android docs you have to do it like this:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
Source: https://developer.android.com/reference/java/net/HttpURLConnection
In your example you just created a HttpURLConnection but never executed it and thats why you can'T get something of it.
While it can definitly work this this method I would greatly encurage you to take a look at Volley as it is more simple and easier to use. It also helps you with JSONRequests. Furthermore it is async by default meaning you don't need to use the deprecated AsyncTask anymore.
Edit 2:
When trying to connect to a secure website over https as you try to do in your example you need to cast to HttpsURLConnection instead.
I also have the same problem, the call to the getResponseCode method freezes. If I set a timeout, the timeout expired exception is thrown.
But all of the above happens when I have the phone in power saving mode, if I remove it, the call to the getResponseCode method works perfectly.
If the Volley api is used, a timeout also occurs.
But this only happens in background processes for example when updating a widget due to restrictions imposed by the system.
The solution is to add your app to the list of energy saving exclusions. Although this can be done through the PowerManager api, it is preferable that it be the user of your app who does it, as discussed in this answer https://stackoverflow.com/a/53115804/1735246.
I included following permissions into Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I am using this code:
try {
java.net.URL url = new URL("http://www.temp372.000webhostapp.com/s.php?t=hello_there");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
t1.setText("problem occured..");
}
Following is the PHP code:
<?php
$fn = "android.txt";
$data = "";
// get whatever they send and store it to the file.
if($_GET["t"])
{
$data = $_GET["t"];
if ($data !== '')
{
$myfile = fopen($fn, "a");
fwrite($myfile, $data . "\n");
fclose($myfile);
}
}
?>
No errors are coming, I am trying running this app into bluestacks and my cellphone (ROG Phone).
But results are same, no error or anything as textview is not setting and it just my PHP code is not receiving the information but when I try same URL into my web browser, PHP code runs cool.
HTTP or "clear text" forbidden on default, you should allow it inside < application > in AndroidManifest.xml android:usesCleartextTraffic="true"
It worked well following are things I got:
I don't have to add the following into manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I also didn't have to add any permission like android:usesCleartextTraffic="true" OR any network_security_config.xml in Manifest.
It worked when I ran the code into AsyncTask in Background thread like followings:
AsyncTask.execute(new Runnable() {
#Override
public void run() {
HttpClient httpclient = new DefaultHttpClient();
try {
httpclient.execute(new HttpGet("https://temp372.000webhostapp.com/s_get.php?t=MyWorld"));
} catch (IOException e) {
e.printStackTrace();
}
}
});
I thanks Artem for this and everyone else who were trying their best.
So I had google maps V2 implemented for about a year now, No issues with it. However after I implemented the weather service from open map , Authorization seems to fail .
Any help will be greatly appreciated!
This is a class that calls for OPEN WEATHER.I am wondering if the http call from here interferes with G.Maps sending request for authorization.
public class RemoteFetch {
private static final String OPEN_WEATHER_MAP_API =
"http://api.openweathermap.org/data/2.5/weather?q=%s&units=metric";
public static JSONObject getJSON(Context context, String city){
try {
URL url = new URL(String.format(OPEN_WEATHER_MAP_API, city));
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
connection.addRequestProperty("x-api-key",
context.getString(R.string.open_weather_maps_app_id));
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp="";
while((tmp=reader.readLine())!=null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
// This value will be 404 if the request was not
// successful
if(data.getInt("cod") != 200){
return null;
}
return data;
}catch(Exception e){
return null;
}
}
}
Those are related with maps
In Manifest :
<permission
android:name="donate.cinek.wit.ie.ridetogether.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="donate.cinek.wit.ie.ridetogether.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIza.............................." />
Any other code as i said worked fine so not much point to post, will do if requested.
Thanks
Add your GoogleApi client key to your Singleton class (Do a initialization) which is accessible throughout the Application and it Should work fine.
I have done for me Like this by Making a Singleton Class
public class Model {
private static Model singleton = new Model( );
private GoogleApiClient _googleClient;
public void setGoogleClient(GoogleApiClient client){
this._googleClient = client;
}
public GoogleApiClient getGoogleClient(){
return this._googleClient;
}}
Note: I have used this for Sign in with Google +
I'm writing my first Android app where the first thing to do is collect a list of maps from a server, but I'm having difficulty getting a simple REST request working. I've been following a number of tutorials and am trying to employ both AsyncTask and HttpURLConnection to do this properly.
For my simple initial test, I just call getMapsJson, with serverUrl set to "http://httpbin.org/ip" (just to make sure it's sending and receiving data correctly).
Code
public String getMapsJson()
{
Log.d(Globals.tag, ">> getting maps json from " + serverUrl.toString());
String output = "";
new GetMapsJsonTask().execute(serverUrl);
return output;
}
private class GetMapsJsonTask extends AsyncTask<URL, Void, String>
{
private HttpURLConnection connection = null;
protected String doInBackground(URL... url)
{
String output = "";
try
{
connection = (HttpURLConnection) url[0].openConnection();
connection.setRequestMethod("GET");
Log.d(Globals.tag, "connection opened!");
InputStream in = new BufferedInputStream(connection.getInputStream());
Log.d(Globals.tag, "input stream captured");
output = readStream(in);
Log.d(Globals.tag, "stream read");
}
catch (IOException e)
{
Log.d(Globals.tag, (e.getMessage() == null ? "IO Exception" : "IO : " + e.getMessage()));
}
finally
{
return output;
}
}
protected void onPostExecute(String json)
{
Log.d(Globals.tag, "Json response: " + json);
}
}
private String readStream(InputStream in) throws IOException
{
Log.d(Globals.tag, "entering readStream");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = reader.readLine();
String output = line;
while((line = reader.readLine()) != null)
output += line;
return output;
}
AndroidManifest.xml
I have the android.permission.INTERNET line in there, but I'm not positive it's in the correct location. May cause issues?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.northstar.minimap"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="com.northstar.minimap.Globals"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.northstar.minimap.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>
<activity
android:name="com.northstar.minimap.MapActivity"
android:label="#string/title_activity_map"
android:parentActivityName="com.northstar.minimap.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.northstar.minimap.MainActivity" />
</activity>
</application>
</manifest>
Output
Logcat yields the following lines:
12-01 21:31:44.727 2188-2188/com.northstar.minimap D/Minimap﹕ >> getting maps json from http://httpbin.org/ip/
12-01 21:31:44.727 2188-2232/com.northstar.minimap D/Minimap﹕ connection opened!
12-01 21:31:45.106 2188-2232/com.northstar.minimap D/Minimap﹕ IO: http://httpbin.org/ip/
12-01 21:31:45.106 2188-2188/com.northstar.minimap D/Minimap﹕ Json response:
Basically, something's causing an IOException, and I'm not sure what - the exception's getMessage isn't exactly verbose. Do I have to do any configuration for the emulator (JellyBean, API level 17)?
Thanks!
I've seen similar posts about this problem, but none of them relate to the use of the Visual Studio development server for ASP .NET.
I'm receiving the following error.
An established connection was aborted by the software in your host machine.
And I'm executing the following code:
String employeesJson = client.downloadString("http://localhost:60000/Api/Employee/GetEmployees.aspx");
When I run this in a regular webbrowser (Chrome 21 or Internet Explorer 10) it runs just fine. I get the JSON result that I want.
And my WebClient class being used (under the variable "client") is defined as follows.
public class WebClient {
private HttpClient httpClient;
public WebClient() {
httpClient = new DefaultHttpClient();
}
public String downloadString(String url) throws IOException {
HttpGet get = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(get); //this is where the error occurs.
HttpEntity entity = response.getEntity();
if(entity != null) {
InputStream stream = entity.getContent();
InputStreamReader streamReader = new InputStreamReader(stream);
BufferedReader bufferedReader = new BufferedReader(streamReader);
StringBuilder builder = new StringBuilder();
String line = null;
try {
while ((line = bufferedReader.readLine()) != null) {
builder.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return builder.toString();
}
//catch all the types of exceptions this method can throw. catching "Exception" is considered bad.
} catch (ClientProtocolException e) {
e.printStackTrace();
}
return null;
}
}
My AndroidManifest.xml file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="specialisering.android"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<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>
face same problem, it was firewall stoping it .... so turned off the firewall and it working now... :)
I can't believe I didn't seek an answer from the documentation. It clearly states that 127.0.0.1 is the IP of the emulator itself, while 10.0.2.2 is the IP of the developer machine.
Changing from localhost to 10.0.2.2 solved my issue.