get string from php json encode to android target api23+ - php

I have a php file that generates data that must take to Android.
This is the file output .php
[{"item":"1","title":"Title of one","link":"qwerty1234"},{"item":"2","title":"Title of two","link":"qwerty1234"},{"item":"3","title":"Title of three","link":"qwerty1234"}]
Now there have been changes with the class apache: Link here
Looking around I find several guides on the old method but I wanted to use the new one since my app is the targetSdkVersion 23.
I think this is the new method with JsonReader and HttpURLConnection.
I tried but I can not make it work or understand how to handle it.
So I ask, how do I take the strings from php page that creates? (example: title and link)

please try this.
it's working for me.
String url = "someurl.php";
HttpPost httppost = new HttpPost(url);
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(httpPost);
String responseString = EntityUtils.toString(response.getEntity());
JSONObject jsonObject = new JSONObject(responseString);
String error = jsonObject.getString("item1");
} catch (IOException e) {
e.printStackTrace();
}
in this case i was using GSON to later parse the response but you can parse it as you wish.
this is a snippet of code that i can provide, if you need more help or if some dependencies are missing please tell me so i can point you in the right direction.
have a look at this tutorial for more help
http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php
if you need a webservice PHP framework, take a look at this
http://www.slimframework.com/
it's very easy to use and ligthweight framework so you can use it as a service to send and recieve info from your server
hope it helps, feel free to ask if you need any more help
cheers

Related

How to call a PHP based web-service from Android?

I have a simple PHP web-service which return result as JSON .
if($_SERVER["REQUEST_METHOD"]=="POST"){
$arg1=$_POST["arg1"];
processArgs($arg1);
}
processArgs($arg1){
$result=doSomething($arg1);
echo json_encode($result);
}
I could call it from Android side using HttpURLConnection. But the problem is HttpURLConnection seems to be a work in very low level. Is there any level implementation which we could avoid writing the same code for making it asynchronous and for parsing the result.
Simply use HttpClient as follows.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://your-host/comm.php");
try {
//add your post data
List<NameValuePair> args = new ArrayList<NameValuePair>(2);
args.add(new BasicNameValuePair("arg1", "your-arg-1"));
httpPost.setEntity(new UrlEncodedFormEntity(args));
//send your request
HttpResponse response = httpClient.execute(httpPost);
} catch (ClientProtocolException | IOException e) {
e.printStackTrace();
}
HttpURLConnection (java.net.HttpURLConnection) is the default HTTP client in Android.
OkHttp, is another one which became the engine that powers HttpUrlConnection as of Android 4.4. It is offers easier method to customize each requests.
Both HttpURLConnection and OkHttp works at somewhat low level. So we need to write our own code for making it asynchronous and for parsing the result again and again.
Retrofit, on the other hand, is a high level implementation which uses OkHttp for connection and Gson for parsing result. It can be used to turn HTTP APIs into a Java interface with ease.
Therefore, Retrofit would be the best choice unless you have specific reason to go with OkHttp ( Like HTTP-based streaming).

android - Parallel task to execute PHP on server

I'm developping and android application and in some point I need to get some vaue from my server. This server has a simple PHP script that just echo a value.
In order to do it, that's what I do:
private static String executePHP(String URL) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
try {
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
return(response);
} catch (IOException e) {
// TODO Auto-generated catch block
return("");
}
}
The method is static, because I call it upon an SMS arrives. Then the URL comes from the SMS text.
From the broadcastReceiver I call:
MainActivity.executePHP(link);
I want the execution of the PHP to be on a background task.
I've been reading of AsyncTask but they need and instance, which I don't have.
What's the best way to do it??
Also, have in mind that the application may not be active right now.
I'll be happy if I can only Toast the result from the PHP executing on asyncTask (or other asyncrhonus thread).
Thanks you all!!
Have a nice day!
Finally, this solve my question! Now I need to see how to handle no-internet-connection.
solution

How to make a web service (preferably using PHP) that can be requested to get JSON objects by the android app

I am making an Android App which interacts with remote server's database and communicate with each other by passing JSON object to and from.
I need to know how to write such a service on my server (preferably in PHP) to which the android app can make request and on receiving the request, the server processes and makes a JSON object and passes that to the android app.
Also, i need to know, when this service is running on the server, on WHICH URL will the android app make request?
For example, if android app have to request to sever to fetch data for parameters:
name: Apple
location: US
then, i guess the android app will have to request the server in form of:
www.example.com?name='Apple"&location='US'
So how to make such a service running on the remote server?
Thanks in advance !
The best example you can refer for this is http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/. It has complete code[php+ android] with simple explanation.
You can write a method that request remote php file that responses to post or get request. if you want to use post request , you can use method below. and you have to add Internet permisson to your manifest file. As you see below , you can add parameters as being key -value pair.
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/webservice.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name", "Apple"));
nameValuePairs.add(new BasicNameValuePair("locaction", "US"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler <String> res=new BasicResponseHandler();
// Execute HTTP Post Request
String response = httpclient.execute(httppost,res);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient

Use database for Android App by downloading with php-script

I'm going nuts! Maybe someone can help me?!
I have an sqlite-database on a running server, which I receive due to an php-script. (To make it clear: I'm calling an php-script which gives me the the database as a response). With the response I'm now trying to "parse" it to an regular *.db file which I later on use for my app.
the app works fine, while placing the *.db into the assets folder. But I need to get the updated database everytime when calling the app. Therefore I need to receive it somehow from the server.
Just for notice: I don't know why they use a php-script for that, but it works perfectly with the iOS-Version of the app. So I am 100% sure that the script does work.
Got any hints or a solution to that?
Thanks!
EDIT: here is what I'm trying to do.
private void copyDatabase() {
InputStream myInputDB = null;
OutputStream myOutputDB = null;
HttpResponse response = null;
// Path to the just created empty db
String dbFilePath = DB_PATH + KeyConstants.DB_NAME;
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(
"http://USERNAME:PASSWORD#ADRESS/u/db.php");
try {
response = httpClient.execute(httpPost);
//Open your local db as the input stream
myInputDB = response.getEntity().getContent();
//Open the empty db as the output stream
myOutputDB = new FileOutputStream(dbFilePath);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInputDB.read(buffer)) > 0){
myOutputDB.write(buffer, 0, length);
}
//Close the streams
myOutputDB.flush();
myOutputDB.close();
myInputDB.close();
} catch (IOException ioEXC) {
throw new Error("Problem copying database from resource file.");
}
What do You have the problem with? With the Android app or with the PHP script?
I don't understand why there is a whole DB file request-response and not just the data (and better in some lazy reading), but that's not matter of Your case.
If You need to "download" all the DB at every run You should call and implement some method to do so - in the very first Activity call this method within onCreate() method. You can create a simple method within this Activity or in better approach create a simple class for this that will be instanciated and its method called within the first activity's onCreate().
But maybe I just don't understand You question...
EDIT: try reading through this problem: Can I download an SQLite db on /sdcard and access it from my Android app?

Sending information from android app to a php script

I'm neither a android or php expert, the thing is that I made a php script that gets the variables from the url ( www.myhost.com/mailScript.php?variable1=name&variable2=age ) and sends a mail with that information.
Mail:
Variable1=Name
Variable2=Age
Now, the problem is that i'm makin a android app that converts a normal form, which ask name, age, etc. And i want to take that information and run php script. But i dont want the users to see a web browser at any time, just that they click de button, get the info, run the url, and done.
The easiest way to do it is mentioned here. Basically, you just want to form the URL based on the value of each of your fields, then hit that URL with an HTTP request.
Use JSON to send data to your PHP script.
By combining that
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
Source : http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient
and looking about JSON, you should be able to do what you want
your php will be the server side and your android application will the be the client side you will just create a form using normal android's UI widgets. There's a plenty of examples around and send your data via HttpPost or HttpGet classes with your parameters set from this form.
http://mobile.tutsplus.com/tutorials/android/android-sdk-creating-forms/
and posting example Secure HTTP Post in Android

Categories