0

I am a beginner to android .I am trying to connect android to mysql . but the application is closed unexceptedly.please fix my problem : I tried this code for connect php to mysql .I use textview in the layout file.Also i add the internet permission in my manifest .

My Code is :

   public class AndroidConnectActivity extends Activity 
     {
        private TextView outputStream;
        public void onCreate(Bundle savedInstanceState) 
        {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_android_connect);
        JSONArray jArray;
        String result = null;
        InputStream is = null;
        StringBuilder sb = null;
        outputStream = (TextView)findViewById(R.id.hello_world);
        ArrayList<NameValuePair> namevaluepairs = new ArrayList<NameValuePair>();
        try
        {

            //http post
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://localhost/android/index.php");
            httppost.setEntity(new UrlEncodedFormEntity(namevaluepairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            if (response.getStatusLine().getStatusCode() != 200) 
            {
                Log.d("MyApp", "Server encountered an error");
            }
        }
        catch(Exception e)
        {
            Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
        }

        //Convert response to string
        try
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF8"));
            sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");
            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());
        }
        //END Convert response to string

        try
        {
            jArray = new JSONArray(result);
            JSONObject json_data=null;
            for(int i=0;i<jArray.length();i++)
            {
                json_data = jArray.getJSONObject(i);
                int id=json_data.getInt("id");
                String name=json_data.getString("name");
                outputStream.append(id +"" + name + "\n");
            }
        }
        catch(JSONException e1)
        {
            e1.printStackTrace();           
        } 
        catch (ParseException e1) 
        {
            e1.printStackTrace(); 
        }
    }
}

<?php 
    mysql_connect("localhost","root","");
    mysql_select_db("android");
    $sql=mysql_query("SELECT * FROM table_1 Where name like 'M%' ");
    while($row=mysql_fetch_assoc($sql))
    $output[]=$row;
    print(json_encode($output));
    mysql_close();
?>
1
  • Try not to use mysql_* functions, they might soon get deprecated. Use mysqli() instead :) Commented Aug 14, 2012 at 10:19

5 Answers 5

1

Use ip address instead of localhost in http://localhost/android/index.php

Sign up to request clarification or add additional context in comments.

2 Comments

wat is the exception getting while execution
go to command prompt and type ipconfig and press enter then u get a address like 192.168.1.1 then copy that address and paste at localhost place and execute app
0

Debug your application using the eclipse android plugin. An error or an exception is necessarily thrown, you need to find out what it is.

Comments

0

It looks like you are missing curly brackets around this:

while($row=mysql_fetch_assoc($sql))
{
    $output[]=$row;
    print(json_encode($output));
}

2 Comments

I try this . but my problem is not solved . thank you It shows the error in log_cat: Error in http connection org.apache.http.conn.HttpHostConnectException: Connection to localhost refused
I am not familiar with android, just saw the problem in the PHP code, thought I would point it out.
0

You may not be able to connect to your localhost from emulator with "http://localhost/.." Try this "http://10.0.2.2/.." instead. Also put some logs between your code and try to discover after which line you are getting the error.

1 Comment

Thank you for your comment .It works fine. HttpPost httppost = new HttpPost("10.0.2.2/name of your folder /index.php"); thank you very much
0

Finally i identify my error .Below I mention the code .It is works fine.It retrive the data from the database.

    public class AndroidConnectActivity extends Activity 
    {
    private TextView outputStream;
    public void onCreate(Bundle savedInstanceState) 
    {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_android_connect);
    JSONArray jArray;
    String result = null;
    InputStream is = null;
    StringBuilder sb = null;
    outputStream = (TextView)findViewById(R.id.hello_world);
    ArrayList<NameValuePair> namevaluepairs = new ArrayList<NameValuePair>();
    try
    {

        //http post
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://10.0.2.2/android/index.php");
        httppost.setEntity(new UrlEncodedFormEntity(namevaluepairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        if (response.getStatusLine().getStatusCode() != 200) 
        {
            Log.d("MyApp", "Server encountered an error");
        }
    }
    catch(Exception e)
    {
        Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
    }

    //Convert response to string
    try
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF8"));
        sb = new StringBuilder();
        sb.append(reader.readLine() + "\n");
        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());
    }
    //END Convert response to string

    try
    {
        jArray = new JSONArray(result);
        JSONObject json_data=null;
        for(int i=0;i<jArray.length();i++)
        {
            json_data = jArray.getJSONObject(i);
            outputStream.append( "\n"+"Id="+json_data.getString("id") +"\t"+"Name=" +                     json_data.getString("name") + "\n");
            result += "\n" + jArray.getJSONObject(i); 
        }
    }
    catch(JSONException e1)
    {
        e1.printStackTrace();           
    } 
    catch (ParseException e1) 
    {
        e1.printStackTrace(); 
    }
}

}

Index.php
<?php 
   mysql_connect("localhost","root","");
   mysql_select_db("android");
   $sql=mysql_query("SELECT * FROM table_1 ");
   while($row=mysql_fetch_assoc($sql))
   $output[]=$row;
   print(json_encode($output));
   mysql_close();
?>

Before you Run the App .You Should Start the localserver(xamp)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.