How To Download Data from server in Android

How To Download Data from server in Android with php & MySql

Here I'm used php script to download data stored in MySQL database;

Create table in MySql

1
2
3
4
5
CREATE TABLE users(
id int,
name Text,
email Text
);

Table insert statement for users


1
INSERT INTO users(id,name,email) VALUES (1,'user1','user1@mail.com')

In order to download data from server we have to use JSON output in server.
myScript.php



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<?php
include("include_connection.php");
$hostName = "server ip";
$userName = "usesr name";
$password = "password";
$conn = mysql_connect($hostName,$userName,$password) or die("connection failed");
$dbName = "database name in MySQL server";
mysql_select_db($dbName,$conn) or die("db selection failed");
$name= $_REQUEST['name']; 
$result =mysql_query("SELECT * FROM users WHERE name= $name");
//getting the email no of paticular user
while($row=mysql_fetch_array($result))
 {
  $flag[data]=$row[email];

 }
echo (json_encode($flag));
?>


In above script we are going to retrieve Emal address of particular person by providing the person name.

When we want to download data and display in text field.

1.create an Android project.

  • activity_main.xml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<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=".MainActivity" >

    <EditText
        android:id="@+id/txtOutput"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="99dp"
        android:ems="10"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/btnGetData"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="39dp"
        android:text="Button" />

</RelativeLayout>

  • Main Activity class

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package com.example.asyncex;
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.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
 
 EditText output;
 Button getData;
 InputStream is=null;
 StringBuilder sb;
 String line=null;
 static String result="";
 String part2;
 
 static JSONObject json_data = null;
 String email;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  getData = (Button) findViewById(R.id.btnGetData);
  output = (EditText) findViewById(R.id.txtOutput);
  
  //button click
  getData.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View arg0) {
    //calling the async task
    new getDataAsync().execute();
   }
  });
 }

  //Async task to request the email address for provided user name
 private class getDataAsync extends AsyncTask<Void, Integer, Void> {
  private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);

    @Override  
         protected void onPreExecute()  
         {  
     //show dialog while downloading
          Dialog.setMessage("Loading data...");
             Dialog.show();
         }
  
  @Override
  protected Void doInBackground(Void... arg0) {
   ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
   //add the value that need to pass to the server.
    nameValuePairs.add(new BasicNameValuePair("phone","user1"));
    
     try{
     HttpClient httpclient = new DefaultHttpClient();
     //set the hosted address of the script
     HttpPost httppost = new HttpPost("http://userdomain.com/myScript.php");
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
     HttpResponse response = httpclient.execute(httppost);
     HttpEntity entity = response.getEntity();
     //get the input stream response by the server for the request
     is = entity.getContent();
           Log.e("pass 1", "connection success ");
     }catch(Exception e){
     Log.e("fail 1", e.toString());
     }
     
     try {
     BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            sb = new StringBuilder();
              while ((line = reader.readLine()) != null)
              {  
              sb.append(line + "\n");
              }
              is.close(); 
              result = sb.toString().substring(0, sb.toString().length()-1);
              Log.e("pass 2", "connection success ");
              String[] parts = result.split(">");
              part2 = parts[1]; 
    } catch (Exception e) {
    Log.e("fail 2", e.toString()); 
   }
     
     try {
      json_data = new JSONObject(part2);
      Log.e("pass 3", "Entered to try block");
      email = (json_data.getString("email"));
      Log.e("pass 3", "Name: " + email);
   } catch (Exception e) {
    Log.e("fail 3", e.toString());
   }
    
   return null;
  }
 
  @Override  
        protected void onPostExecute(Void result)  
        {     
   //After complete the background task close the alert dialog
            Dialog.dismiss();
            //Downloaded string data adding to the text field 
            output = (EditText) findViewById(R.id.txtOutput);
            output.setText(email);
        }
 
 }
 
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  
  return true;
 }

}


AndroidManifest.xml

add following statement inside AndroidManifest.xml file in order to get permissions to access internet.

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

Now we are done and make sure that you have WiFi or internet data connection before run the app.











No comments:

Post a Comment