Search code examples
androidphpmyadmin3g

Connecting to a server through Android 3g and retrieving data from phpmyadmin


I want to create a connection to a server from my Android through 3G but I was unsuccessful. I succeed if the Android phone is connected through wifi and if it is the same wifi as my server. Could you help me please and giving my a piece of code to do it?

Here is my code, first, the php which requests my database:

<?php
// on se connecte à notre base  pour recuperer les data
$base = mysql_connect ('localhost', 'root', ''); 
mysql_select_db ('routelibre', $base) ;  
$variable = $_GET['variable'];
$first_token  = strtok($variable, ";;");
$second_token = strtok(";;");
$req =mysql_query("SELECT message from messages where departement='$first_token' AND            voie='$second_token'");
$output=array();
while ($row=mysql_fetch_array($req)) {    
$output[]=$row;    
} 
//on encode en JSON 
print(json_encode($output));
mysql_free_result ($req);  
?>

Here is the code for android:

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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;  
import android.content.Context;
import android.net.ParseException;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import android.content.Context;


 public class ConnexionSQL  {
public void ConnexionSQLActivity(){};

public ArrayList<String> ConnexionBD(String dataFromHMI, Context context) {
    String result = null;
    InputStream is = null;
    JSONObject json_data=null;
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    ArrayList<String> lesMessages = new ArrayList<String>();

    StrictMode.ThreadPolicy policy = new 

            StrictMode.ThreadPolicy.Builder().permitAll().build();

    StrictMode.setThreadPolicy(policy); 

    try{
        //commandes httpClient
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new 

                    HttpPost("http://192.168.1.1:80/connexion_mysql.php?variable=" + dataFromHMI);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    }
    catch(Exception e){
        Log.i("taghttppost",""+e.toString());
        Toast.makeText(context,e.toString() ,Toast.LENGTH_LONG).show();
    }


    //conversion de la réponse en chaine de caractère
    try
    {
        BufferedReader reader = new BufferedReader(new 

        InputStreamReader(is,"UTF-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.i("tagconvertstr",""+e.toString());
    }
    //recuperation des donnees json
    try{
        JSONArray jArray = new JSONArray(result);

        for(int i=0;i<jArray.length();i++)
        {

            json_data = jArray.getJSONObject(i);
            lesMessages.add(json_data.getString("message"));
            //r.add(json_data.getString("categorie"));

        }
    }
    catch(JSONException e){
        Log.i("tagjsonexp",""+e.toString());
    } catch (ParseException e) {
        Log.i("tagjsonpars",""+e.toString());
    }
    return lesMessages;
}

}


Solution

  • This is trying to connect locally.

    HttpPost("http://192.168.1.1:80/connexion_mysql.php?variable=" + dataFromHMI);
    

    Do you have your code on a server that you can access while not connected to your local machine? That is the url you need to post to!

    192.168.1.1 is the default IP address used by Linksys routers (and maybe others?) See: http://www.tech-faq.com/192-168-1-1.html

    So, when you are connected over wifi to this router than you able to access sources stored @192.168.1.1:80 but over 3g you are no longer connected to this router. You will need to host your files in another way...by setting up a server, hosting your files through a web hosting service, etc... in order to access the files remotely!