MySQL Connectivity

Quickly share your Android Code Snippets here...

MySQL Connectivity

Postby rosebeat » Thu Sep 09, 2010 6:04 am

Hello,
I am new to android. I have this project of loading the data from the server to android. I do not know how to establish MySQL connectivity with android and PHP as an intermediate language. Consider an example - I have a website where I have got posts. Now I want those posts to be visible on the android device when the Android code sends a request to PHP and the query gets executed by PHP. So the posts get loaded on the android screen. (Only one good thing that I know a little bit of PHP nad MySQL connectivity)

Since I am new to codings and all, I need the code to be very easy and step by step. The more complex the code, it will be more hard for me to understand.

I need help asap.
Please help me out.
rosebeat
Junior Developer
Junior Developer
 
Posts: 15
Joined: Wed Sep 08, 2010 6:06 am

Top

Re: MySQL Connectivity

Postby achie1266 » Thu Sep 09, 2010 5:47 pm

You can send the data from your php code as either json on xml easily.
Now from the android you will need to handle the httppost and response to get that response and handle it appropriately depending on what kind of format it is in.
You would want to look at the tutorials related to HttpPosts , webservices to handle xml or json data in android.
You will need to know Java since you have to do the android coding in java.

Search for those tutorials in this forum or do a Google search. There are a bunch of them online.
achie
User avatar
achie1266
Master Developer
Master Developer
 
Posts: 223
Joined: Mon Nov 09, 2009 10:56 pm
Location: Denver

Re: MySQL Connectivity

Postby rosebeat » Sun Sep 12, 2010 6:50 am

I have been trying from the ff site
http://www.helloandroid.com/tutorials/c ... l-database
Since i am trying on localhost, I have made changes and replaced the URL from my IP. But when I run the android, it says
"Applcation process.org has stopped unexpectedly"
I have to force close it. IDK what is the issue with this. Please help...
rosebeat
Junior Developer
Junior Developer
 
Posts: 15
Joined: Wed Sep 08, 2010 6:06 am

Re: MySQL Connectivity

Postby rosebeat » Sun Sep 12, 2010 6:52 am

Also, I haven't seen any success of the code when we try it on localhost.
rosebeat
Junior Developer
Junior Developer
 
Posts: 15
Joined: Wed Sep 08, 2010 6:06 am

Re: MySQL Connectivity

Postby rosebeat » Sun Sep 12, 2010 7:10 am

Now I changed the code a bit
And I see nothing
Let me just paste the code

here is the php code


<?php
mysql_connect("localhost","username","password");
mysql_select_db("game");
echo "Database has been selected";
$a=mysql_query("SELECT * from game1 where id>'".$_REQUEST['id']."'");

while($b=mysql_fetch_assoc($a))

$output[]=$b;

print(json_encode($output));
?>


Here is the android code


package org.me.androidapplication21;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


/**
*/
public class two extends Activity {

String KEY_121 = "http://192.168.0.150/index.php";
InputStream is;
String result;
//the roll data to send
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

nameValuePairs.add(new BasicNameValuePair("id","2"));

//http post


try{

HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost("KEY_121");

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");
}
result=sb.toString();
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", Question: "+json_data.getString("Question")

);
}


}catch(Exception e){

Log.e("log_tag", "Error converting result "+e.toString());

}

}
}
rosebeat
Junior Developer
Junior Developer
 
Posts: 15
Joined: Wed Sep 08, 2010 6:06 am

Re: MySQL Connectivity

Postby rosebeat » Sun Sep 12, 2010 10:08 am

Now I get the error that the application has closed unexpectedly....
rosebeat
Junior Developer
Junior Developer
 
Posts: 15
Joined: Wed Sep 08, 2010 6:06 am

Top

Re: MySQL Connectivity

Postby junkdog » Thu Sep 23, 2010 6:18 am

rosebeat wrote:Now I get the error that the application has closed unexpectedly....


What IDE are you using for developing? If you're using Eclipse, debug the application ("RMB on project, Debug As -> Android Application), switch to DDMS perspective and check the logcat output. It should print the stacktrace upon crashing, somewhere in it you should find the offending line. You might have to press continue once or twice when the application throws the exception (and switches to the Debug perspective).

Good luck.
junkdog
Freshman
Freshman
 
Posts: 2
Joined: Thu Sep 23, 2010 4:22 am
Location: Gothenburg, Sweden

Re: MySQL Connectivity

Postby shamim81 » Sat Nov 27, 2010 8:10 pm

I am facing a strange problem in getting output in andr.. emulator. I have written the code as stated in helloandroid.com, now when Im running the code it is showing black screen though it does not report any errors in the code.


Please help..


:( Im stuck off here actually Im learning android and new to it.
shamim81
Freshman
Freshman
 
Posts: 2
Joined: Sat Nov 27, 2010 7:41 pm

Re: MySQL Connectivity

Postby shamim81 » Sat Nov 27, 2010 8:11 pm

shamim81 wrote:I am facing a strange problem in getting output in andr.. emulator. I have written the code as stated in helloandroid.com, now when Im running the code it is showing black screen though it does not report any errors in the code.


Please help..


:( Im stuck off here actually Im learning android and new to it.
shamim81
Freshman
Freshman
 
Posts: 2
Joined: Sat Nov 27, 2010 7:41 pm

Re: MySQL Connectivity

Postby aatifaqua » Sat Dec 25, 2010 3:45 pm

even i need to do get and post through website

can any1 give us a tutorial for that?????
aatifaqua
Junior Developer
Junior Developer
 
Posts: 13
Joined: Tue Dec 07, 2010 8:08 am

Re: MySQL Connectivity

Postby androidworkz » Mon Dec 27, 2010 4:40 pm

I have an app that uses this method to retrieve JSON encoded data from my web server. Your PHP code should work fine though I would point out that using the raw $_REQUEST['id'] is a security issue...

Syntax: [ Download ] [ Hide ]
Using php Syntax Highlighting
  1. <?php
  2. mysql_connect("localhost","username","password");
  3. mysql_select_db("game");
  4. $id = intval(trim($_REQUEST['id']));
  5. $a=mysql_query("SELECT * from game1 where id > {$id}");
  6.  
  7. while($b=mysql_fetch_assoc($a))
  8.  
  9. $output[]=$b;
  10.  
  11. print(json_encode($output));
  12. ?>
  13.  
Parsed in 0.054 seconds, using GeSHi 1.0.8.4


I have a class that I use for the result... so you could probably do the same thing:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. public class Result {
  2.         public int id;
  3.         public String title;
  4. }
  5.  
Parsed in 0.031 seconds, using GeSHi 1.0.8.4


Here is the method that I use to fetch results from my website using GET:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. private ArrayList<Result> getResults(int id) {
  2.         ArrayList<Result> listItems = new ArrayList<Result>();
  3.  
  4.         try {
  5.                 URL conn = new URL("http://yourdomain.com/getjson.php?id="+id);
  6.                 URLConnection tc = conn.openConnection();
  7.                 BufferedReader in = new BufferedReader(new InputStreamReader(
  8.                                 tc.getInputStream()));
  9.  
  10.                 String line;
  11.                 while ((line = in.readLine()) != null) {
  12.                         JSONArray ja = new JSONArray(line);
  13.  
  14.                         for (int i = 0; i < ja.length(); i++) {
  15.                                 JSONObject jo = (JSONObject) ja.get(i);
  16.                                 Result result = new Result();
  17.                                 result.id = jo.getInt("id");
  18.                                 result.title = jo.getString("title");
  19.                                 listItems.add(result);
  20.                         }
  21.                 }
  22.         } catch (MalformedURLException e) {
  23.                 e.printStackTrace();
  24.         } catch (IOException e) {
  25.                 e.printStackTrace();
  26.         } catch (JSONException e) {
  27.                 e.printStackTrace();
  28.         }
  29.         return listItems;
  30. }
  31.  
Parsed in 0.038 seconds, using GeSHi 1.0.8.4
androidworkz
Freshman
Freshman
 
Posts: 9
Joined: Tue Jun 01, 2010 9:32 pm

Re: MySQL Connectivity

Postby androidworkz » Mon Dec 27, 2010 4:44 pm

Don't forget to add the right permissions to your AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
androidworkz
Freshman
Freshman
 
Posts: 9
Joined: Tue Jun 01, 2010 9:32 pm

Re: MySQL Connectivity

Postby whitehat » Sun Jan 02, 2011 11:53 am

I somehow fixed this tutorial and putted th howto here:
post91169.html#p91169
whitehat
Freshman
Freshman
 
Posts: 4
Joined: Thu Dec 30, 2010 11:43 pm

Re: MySQL Connectivity

Postby lowenbrau » Wed Nov 09, 2011 10:54 pm

HI.
In PHP, nothing special to do. I think, in your case, Json is not required.

In server side:
You execute your sql statement and process resultset normally using echo (to try).
You may format with table, controls, etc.


From android device, you make a http request, so:

//very important
import android.net.Uri;
......

//if u wan to send a parameter
String _codigo = _pedidosTxtCodigo.getText().toString();

//the address
String myData= "http://www.yourpage.com/showPhoto.php?code=" + _codigo;

//create and execute an intent.
Intent myActivity2 = new Intent(Intent.ACTION_VIEW, Uri.parse(myData));
startActivity(myActivity2);

***************************************WARNING***************************************
Dont foret to put this in manifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


//That's all folks!!
lowenbrau
Freshman
Freshman
 
Posts: 4
Joined: Wed Nov 09, 2011 10:01 pm

Top

Return to Code Snippets for Android

Who is online

Users browsing this forum: No registered users and 5 guests