Use database for Android App by downloading with php-script - php

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?

Related

get string from php json encode to android target api23+

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

android login from ios web service?

I'm attempting to connect an Android app to a web service originally designed for iOS and I'm not sure if it's going to be possible. I also did not design this web service so I am looking through this code that isn't mine and just kind of fumbling around. The current web service is written in PHP and uses SOAP and WSDL. If i can connect to this web service I will attempt to use ksoap2 unless I find a better alternative. I will be using a lot of links in this post because without them you will be looking at an obnoxious amount of code.
So anyways here is the problem in a nutshell. I have this list for the web service url's
URL List and from the looks of that list I need to make my login request to iphoneview/iphone_get_details.php which has this inside of it.
get_detailshowever when I use this code
class LogMeIn extends AsyncTask<String, Void, String> {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(
"http://www.fakesite.com/myv2/iphoneview/iphone_get_details.php");
protected String doInBackground(String... urls) {
try {
username = un.getText().toString();
password = pw.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs
.add(new BasicNameValuePair("username", username));
nameValuePairs
.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
String res = inputStream(response.getEntity().getContent())
.toString();
Log.v("RESPONSE", res);
// if username and password are valid, launch main activity
if (res.toString() == "1") {
Intent logIn = new Intent(getApplicationContext(),
Main.class);
startActivity(logIn);
}
// send the user a message saying the login failed
else {
runOnUiThread(new Runnable() {
public void run() {
pw.setText("");
fail.setText(R.string.fail);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
}
}
all I get back is this for a response
05-25 13:57:21.292: V/RESPONSE(5871): <?xml version='1.0' encoding='UTF-8'?><!DOCTYPE plist PUBLIC '-//Apple//DTD PLIST 1.0//EN' 'http://www.apple.com/DTDs/PropertyList-1.0.dtd'><plist version='1.0'><dict><key>iId</key><string>0</string><key>itemChildren</key><array></array></dict></plist>
I know where this response is coming from, there very bottom of the iphoneview/iphone_get_details.php. The problem is I don't know if it's because
I need to be wrapping this in a SOAP request
I can't use this code
I'm connecting to the wrong file (doubt it)
all of the above and/or something else
Now common sense tells me from looking at the current iphone_get_details.php file that I will not be receiving a response of "1" or "true" either way. As a matter of fact that file looks like it sends back a ton of information, when in essence all I want is a "1" or a "true" to make sure I'm properly connected with the correct login information. So if anyone has the time to look this question over I'd be grateful, I understand it's a lot of reading.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE plist PUBLIC '-//Apple//DTD PLIST 1.0//EN'http://www.apple.com/DTDs/PropertyList-1.0.dtd'>
<plist version='1.0'>
<dict>
<key>iId</key>
<string>0</string>
<key>itemChildren</key>
<array></array>
</dict>
</plist>
If you're going to examine the result, the iId is 0, it could mean that the iId is set to zero if the username and password does not exist, coz initially, ids's starts with 1 or it could be that the iId of the user in the database is 0 by then you can say the the username and password matched in the database and would mean the password and username provided by the user is correct or the other way around.
edited:::
I have checked your link here http://pastebin.com/8vv1Vvxj and based on the code and the xml returned, it signifies that the default value of iId is 0 if there are no matched username and password, otherwise if the iId is not 0 meaning the username and password is correct.
initial values in php
$vUserName = stripslashes(trim($_REQUEST["txtUser"]));
$vPassword = stripslashes(trim($_REQUEST["txtPass"]));
$returnFinalString = "";
$member_id = 0;
.
.
.
//if this condition is true, meaning, the username and password matched and exist
if(mysql_num_rows($member_res)>0){
$member_id = $mem_row['user_id'];
}
//and the $member_id is changed to non-zero
and for the result, you just have to parse the xml returned and get the iId value and check if it's 0 or not, by then you can determine if the user can be logged in or not.
Some pointers - you might consider using Robospice and then parsing the response into Java POJO's using Android Spring and the SimpleXML message converter. The response you are getting back is the XML for an iphone plist, which is going to be challenging to work with in the Android environment, but not impossible. The response from the server has nothing to do with your Android code, so you should be able to verify that it's the same as what gets sent to the iPhone app by using a web browser.
Hopefully this gives you some places to look and some forward momentum.

How to get an Image file from PHP and show in Android? [duplicate]

I have a remote database with MySQL, and I am storing photos of the users of my app on the database as a row of the database with LONGTEXT type.
I transform the photos to a string with Base64.
I connect to my remote database with JSON and PHP, because this, I have to use Base64, because as I know, JSON and PHP need to send strings on the parameters, and with Base64 I can transform the photo into a string.
It works ok, but it's very slow. When I am loading a photo of 100 KB, it takes a lot of time, but when I am loading a photo of 5 KB it takes only two or three seconds.
A friend told me to use BLOB instead of Base64, but how do I use BLOB with JSON and a PHP connection to the database? Also, I need to store the images on a row of the table USER. This is because the users don't have privileges to upload files into the remote server, but they can upload photos by uploading them as a string in a row of the table USER.
thanks
EDIT:
this is the code where it takes a looot time waiting (it waits in the line: while ((line = reader.readLine()) != null) { , it is waiting on reader.readLine() )
this code gets one user from the remote database, it takes a loooooot of time to show the user on my app
public Friend RetrieveOneUser(String email)
{
Friend friend=null;
String result = "";
//the parameter data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email",email));
//http post
InputStream is=null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(this.BaseURL + this.GetOneUser_URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
friend=new Friend(json_data.getString("email"),json_data.getString("password"), json_data.getString("fullName"), json_data.getString("mobilePhone"), json_data.getString("mobileOperatingSystem"),"",json_data.getString("photo"));
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return friend;
}
Segment the request into two parts:
First downloads the JSON with everything except the image, return a reference to the image as a URL instead
Second download the image as a binary chunk, potentially asynchronously depending on the app
I'm assuming you have something like http://example.com/userinfo/xxx as an endpoint that returns the JSON? Add an endpoint like http://example.com/userinfo_image/xxx to return just the image, then you can return it as a binary chunk instead of Base64 encoding it in the JSON.
It means you make two HTTP requests instead of one, but depending on the app you might be able to do the image load asynchronously, and if so you normally get a big gain in perceived application response time from the users perspective.
For info about lazy loading images in the background see the post on the Android Developers blog for a sample:
http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html
If you can't lazy load the image consider doing parallel requests for both the image and the JSON at the same time. With the binary version of the image taking a lot less network bandwidth, and a lot less processing once you get the data onto the handset, it should still seem a lot more speedy.
Why not dump your image as a file on the server and return the url of the written file in your json? This is really how you should do what you want to do since http is the protocol you should use for transfering images over the web.
Code similar to this should do what you want on the server
//code to get your row from database
//Code that writes it to a file.
$Data = $row['myblobfield'];
$fp = fopen('myimgname.jpg', 'w');
fwrite($fp, $Data);
fclose($fp);
This will write your blob or longtext fields as a file on your server which you can then download from your mobile app. You can then delete this temp files after an interval.
Hope this is useful
To answer your question:
No, JSON doesn't support binary data, you must escape it in some way before sending it. Storing it as BLOB in MySQL is not going to fix the major infrastructure issues you have.
From what I understand you have an Android device that is uploading a picture to a PHP server, this PHP server is encoding the picture to Base64, putting that into a JSON string and then posting it to a remote(how remote is remote? same data center? across the country? across the world? in outer space orbiting the moon?) MySQL server through an HTTP interface of some sort, that MySQL server is storing the Base64 image as LONGTEXT. To get the image back, the Android Client sends a request to PHP, PHP sends a request to the remote MySQL server, PHP then has to Base64 decode the image and send it down.
This is horribly inefficient, you are going to suffer latency every step of the way.
Edit: okay it looks like this is a client side issue and not a server side issue...
If that's the case then I'd suggest checking the posts # Uploading images to a PHP server from Android as they should have some more efficient examples.
Is the slowness coming from json/base64 encoding 100K of data, or from the database hit? Its probably from the encoding, and putting the files in the file system (as everyone in the comments is crying), on a small scale, is not going to make a bit of difference.
Do some measurements on the different parts of the operation, and try to pinpoint why its slow. I don't know how else you'd get an image blob into a json encoded string without base64, i suppose you could try and escape everything, which might be just as slow, and hope the parser doesn't choke on it.
Are you using the json_encode function in php, or manually building the string? Try building it manually. Are you base64 encoding raw data from the database, or is it encoded before its stored, you should encode it before its stored to save time when outputting.

How to communicate from php to Android

I am making a location application, where user can parameter some function from the server, so I want the server to begin a communication with the phone of the user.
But firstly, I want to open a communication with an android, from the php.
Is there a way to communicate with an android phone from a php server?
I already use the communication from android with HTTP to server with return of JSONObject, but I cant find anything for a php call to android.
I think its exactly like the application which can make your phone ring.
Check out Google Cloud Messaging for Android.
Google Cloud Messaging for Android (GCM) is a service that allows you to send data from your server to your users' Android-powered device. This could be a lightweight message telling your app there is new data to be fetched from the server (for instance, a movie uploaded by a friend), or it could be a message containing up to 4kb of payload data (so apps like instant messaging can consume the message directly).
The GET method
You will need to have the Android client connect to your server and pass your JSON messages. If the client needs to get some data from the server and disconnect, then you can just use a normal HTTP type GET.
The WebSocket method
If however, you decide you need a long running TCP connection passing JSON bidirectionally then you should consider something like WebSockets. I have written an Android WebSocket demo. The Android client by default connects to the websocket.org echo server, but that can be easily changed.
I also found a PHP WebSockets implementation.
The Push Method
Now if your plan is to push messages from the server to the client without the client initiating the connection you will need something like GCM (Google Cloud Messaging). Here is an article covering GCM and PHP.
Generally, creating connection from server side to client side is complex, because:
The client might use private IP address.
Inbound connection might be rejected if the device connected behind firewall.
You need to install an application if that can be run in the background and watches the server for new messages.
Using Web:
It depends on the browser how it support JavaScript API especially new HTML5 features such as Server Sent Events
To enable servers to push data to Web pages over HTTP or using
dedicated server-push protocols, this specification introduces the
EventSource interface.
Please use below link for store data in mysql using php and u need to create webservice in that you will get two response from php server
1) Json
2) xml
if you show example please visit below link
Creating a basic web services in php
also visit this link for better description
http://phpmaster.com/lets-talk-1/
You Can Use HTTpReq class :
public class HttpReq {
public String send (String url){
//send a http request and get the result
InputStream is = null;
String result = "";
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
}
Then you use this class to make connection and to call your php file to get the data as JSonObject .
ht = new HttpReq();
// send a http request with GET
x=ht.send("http://10.0.2.2/myFolder/myFile.php");
JSONArray jArray;
JSONObject json_data;
String h[]=x.split("<");
try {
jArray = new JSONArray(h[0]);
json_data = jArray.getJSONObject(0);
url=json_data.getString("url");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In Your Php file you may use this methods to get the JSon data or to send it to the android App
Json_decode($string);
And
Json_encode($string);
I hope that will help you :)

How to use BLOB with JSON and PHP?

I have a remote database with MySQL, and I am storing photos of the users of my app on the database as a row of the database with LONGTEXT type.
I transform the photos to a string with Base64.
I connect to my remote database with JSON and PHP, because this, I have to use Base64, because as I know, JSON and PHP need to send strings on the parameters, and with Base64 I can transform the photo into a string.
It works ok, but it's very slow. When I am loading a photo of 100 KB, it takes a lot of time, but when I am loading a photo of 5 KB it takes only two or three seconds.
A friend told me to use BLOB instead of Base64, but how do I use BLOB with JSON and a PHP connection to the database? Also, I need to store the images on a row of the table USER. This is because the users don't have privileges to upload files into the remote server, but they can upload photos by uploading them as a string in a row of the table USER.
thanks
EDIT:
this is the code where it takes a looot time waiting (it waits in the line: while ((line = reader.readLine()) != null) { , it is waiting on reader.readLine() )
this code gets one user from the remote database, it takes a loooooot of time to show the user on my app
public Friend RetrieveOneUser(String email)
{
Friend friend=null;
String result = "";
//the parameter data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email",email));
//http post
InputStream is=null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(this.BaseURL + this.GetOneUser_URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
friend=new Friend(json_data.getString("email"),json_data.getString("password"), json_data.getString("fullName"), json_data.getString("mobilePhone"), json_data.getString("mobileOperatingSystem"),"",json_data.getString("photo"));
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return friend;
}
Segment the request into two parts:
First downloads the JSON with everything except the image, return a reference to the image as a URL instead
Second download the image as a binary chunk, potentially asynchronously depending on the app
I'm assuming you have something like http://example.com/userinfo/xxx as an endpoint that returns the JSON? Add an endpoint like http://example.com/userinfo_image/xxx to return just the image, then you can return it as a binary chunk instead of Base64 encoding it in the JSON.
It means you make two HTTP requests instead of one, but depending on the app you might be able to do the image load asynchronously, and if so you normally get a big gain in perceived application response time from the users perspective.
For info about lazy loading images in the background see the post on the Android Developers blog for a sample:
http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html
If you can't lazy load the image consider doing parallel requests for both the image and the JSON at the same time. With the binary version of the image taking a lot less network bandwidth, and a lot less processing once you get the data onto the handset, it should still seem a lot more speedy.
Why not dump your image as a file on the server and return the url of the written file in your json? This is really how you should do what you want to do since http is the protocol you should use for transfering images over the web.
Code similar to this should do what you want on the server
//code to get your row from database
//Code that writes it to a file.
$Data = $row['myblobfield'];
$fp = fopen('myimgname.jpg', 'w');
fwrite($fp, $Data);
fclose($fp);
This will write your blob or longtext fields as a file on your server which you can then download from your mobile app. You can then delete this temp files after an interval.
Hope this is useful
To answer your question:
No, JSON doesn't support binary data, you must escape it in some way before sending it. Storing it as BLOB in MySQL is not going to fix the major infrastructure issues you have.
From what I understand you have an Android device that is uploading a picture to a PHP server, this PHP server is encoding the picture to Base64, putting that into a JSON string and then posting it to a remote(how remote is remote? same data center? across the country? across the world? in outer space orbiting the moon?) MySQL server through an HTTP interface of some sort, that MySQL server is storing the Base64 image as LONGTEXT. To get the image back, the Android Client sends a request to PHP, PHP sends a request to the remote MySQL server, PHP then has to Base64 decode the image and send it down.
This is horribly inefficient, you are going to suffer latency every step of the way.
Edit: okay it looks like this is a client side issue and not a server side issue...
If that's the case then I'd suggest checking the posts # Uploading images to a PHP server from Android as they should have some more efficient examples.
Is the slowness coming from json/base64 encoding 100K of data, or from the database hit? Its probably from the encoding, and putting the files in the file system (as everyone in the comments is crying), on a small scale, is not going to make a bit of difference.
Do some measurements on the different parts of the operation, and try to pinpoint why its slow. I don't know how else you'd get an image blob into a json encoded string without base64, i suppose you could try and escape everything, which might be just as slow, and hope the parser doesn't choke on it.
Are you using the json_encode function in php, or manually building the string? Try building it manually. Are you base64 encoding raw data from the database, or is it encoded before its stored, you should encode it before its stored to save time when outputting.

Categories