Go Back   Android Forums > Android Development > Application Development
Application Development Dev lounge for our application developers.

test: Reply
 
LinkBack Thread Tools
Old February 28th, 2012, 12:55 PM   #1 (permalink)
New Member
Thread Author (OP)
 
Join Date: Feb 2012
Posts: 2
 
Device(s):
Carrier: Not Provided

Thanks: 0
Thanked 0 Times in 0 Posts
Question Android mysql connexion problem

Hello,

I am trying to connect my android application with mysql database.
This is my source code:

php code:
PHP Code:
<?php
  mysql_connect
("localhost","root","");
  
mysql_select_db("bdville");
  
$sql=mysql_query("select * from tblville where Nom_ville like '".$_REQUEST['ville']."%'");
  while(
$row=mysql_fetch_assoc($sql))
  
$output[]=$row;
  print(
json_encode($output));
  
mysql_close();
?>
classVilleActivity.java:
Code:
package com.exemple.ville;
 
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;
 
import com.exemple.ville.R;
 
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
 
public class VilleActivity extends Activity {
	TextView txt;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
 
		LinearLayout rootLayout = new LinearLayout(getApplicationContext());  
		txt = new TextView(getApplicationContext());  
		rootLayout.addView(txt);  
		setContentView(rootLayout);  
 
		// Définir le texte et appeler la fonction de connexion.  
		txt.setText("Connexion..."); 
		// Appeler la méthode pour récupérer les données JSON
		txt.setText(getServerData(strURL)); 
	}
	public static final String strURL = "http://10.0.2.2/mesRequetes/ville.php";
 
	private String getServerData(String returnString) {
		InputStream is = null;
		String result = "";
		// Envoyer la requête au script PHP.
		// Script PHP : $sql=mysql_query("select * from tblVille where Nom_ville like '".$_REQUEST['ville']."%'");
		// $_REQUEST['ville'] sera remplacé par L dans notre exemple.
		// Ce qui veut dire que la requête enverra les villes commençant par la lettre L
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("ville","L"));
 
		// Envoie de la commande http
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(strURL);
			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());
		}
 
		// Convertion de la requête en 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 les données JSON
		try{
			JSONArray jArray = new JSONArray(result);
			for(int i=0;i<jArray.length();i++){
				JSONObject json_data = jArray.getJSONObject(i);
				// Affichage ID_ville et Nom_ville dans le LogCat
				Log.i("log_tag","ID_ville: "+json_data.getInt("ID_ville")+
						", Nom_ville: "+json_data.getString("Nom_ville")
				);
				// Résultats de la requête
				returnString += "\n\t" + jArray.getJSONObject(i); 
			}
		}catch(JSONException e){
			Log.e("log_tag", "Error parsing data " + e.toString());
		}
		return returnString; 
	}
    }
manifest:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.exemple.ville"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".VilleActivity"
            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>
However, when I execute, the emulator display the URL of my php file but it does not display the two countries starting with the letter "L"

Please help me!!

Advertisements
anddebutan is offline  
Reply With Quote
sponsored links
Reply


Go Back   Android Forums > Android Development > Application Development
Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



All times are GMT -5. The time now is 01:22 PM.
Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2014, vBulletin Solutions, Inc.