Thursday 11 July 2013

ANDROID RETRIEVING DATA FROM MYSQL DATABASE

first things first
create a table called
student
having fields NAME and YEAR and AGE from your php mypublicadmin
2.create a php file index.php
<?php
  header('Content-type: application/json');
  mysql_connect("127.0.0.1","root","");
  mysql_select_db("android");
  $sql=mysql_query("select * from students");
  while($row=mysql_fetch_assoc($sql))
  $output[]=$row;
  json_encode($output);
  print(json_encode($output));
  mysql_close();
?>
then after this go to eclipse MAINACTIVITY and add this
package com.example.httpclient;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class HTTPCLIENT extends Activity {
TextView text;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_httpclient);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        connect();
    }
    private void connect() {
    String data;
    List<String> r = new ArrayList<String>();
    ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r);
    ListView list=(ListView)findViewById(R.id.listView1);
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet("http://10.10.6.124/android/index.php");
            HttpResponse response = client.execute(request);
            HttpEntity entity=response.getEntity();
            data=EntityUtils.toString(entity);
            Log.e("STRING", data);
            try {
           
    JSONArray json=new JSONArray(data);
    for(int i=0;i<json.length(); i++)
    {
    JSONObject obj=json.getJSONObject(i);
    String name=obj.getString("name");
    String year=obj.getString("year");
    String age=obj.getString("age");
    Log.e("STRING", name);
    r.add(name);
    r.add(year);
    r.add(age);
    list.setAdapter(adapter);
   
    }
   
    } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
         
        } catch (ClientProtocolException e) {
            Log.d("HTTPCLIENT", e.getLocalizedMessage());
        } catch (IOException e) {
            Log.d("HTTPCLIENT", e.getLocalizedMessage());
        }
     
     
    }


}
xml file
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".HTTPCLIENT" >

      <ListView
          android:id="@+id/listView1"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_alignParentLeft="true"
          android:layout_alignParentTop="true" >
      </ListView>
    
</RelativeLayout>

in your manifest add permissions to internet
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.httpclient"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="17" />
   <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.httpclient.HTTPCLIENT"
            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>
and thats all if this fails then change your operating system hhahahahahahahahahaha

28 comments:

  1. It works.....i have searched every blog through google but didnt find any correct solutions. But this one did work for me. Thanks

    ReplyDelete
    Replies
    1. http://10.10.6.124/android/index.php"
      in this line what is android ???

      Delete
  2. where is insert.php? what should we write in insert.php?

    ReplyDelete
    Replies
    1. man sorry
      try this as youyr insert.php

      assuming you have a table with columns name,year,age you should be able to get those values on your android

      Delete
    2. insert.php use index.php instead

      Delete
    3. D/HTTPCLIENT: Connection to http://localhost refused


      how can i solve this Icytrey Richards...

      Delete
  3. very good tutorial, many thanks!

    ReplyDelete
  4. Yup boss.....it's working :)
    but can u pls post something for custom listview(text over the image)

    ReplyDelete
  5. http://10.10.6.124/android/index.php"
    in this line what is android ???

    ReplyDelete
  6. when i run, it says " org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray"

    ReplyDelete
    Replies
    1. me too , did you found any solutions?

      Delete
    2. D/HTTPCLIENT: Connection to http://localhost refused

      how can i solve this

      Delete
    3. insert some data into table student

      Delete
  7. D/HTTPCLIENT: Connection to http://localhost refused



    how can i solve this

    ReplyDelete
    Replies
    1. instead of localhost put ip addresss of pc..
      check ip with Windows key + R -> cmd -> enter
      type ipconfig

      Delete
  8. When i run the app there is nothing, help please

    ReplyDelete
    Replies
    1. insert some data into database students table... :)

      Delete
  9. How can I make this listview items clickable??? please answer

    ReplyDelete
  10. This code worked.. now my problem is that i don't know how to intent every listview items.. please help

    ReplyDelete
  11. Can I use this app 's code and layout with Android Studio

    ReplyDelete
  12. Does Http Client work now? I think it's deprecated. I really need to get it done. And I'm not understanding how to fetch the data from mysql database to android.

    ReplyDelete
  13. Pls add download link to download project

    ReplyDelete
  14. This comment has been removed by the author.

    ReplyDelete
  15. please post a code for data retrieve from mysql through php with asynctask as a separate class which is not included in Mainactivity

    ReplyDelete
    Replies
    1. with Listview of json i.e. data from php

      Delete