This Tutorial Describes Fetching data from remote database and store it in the layout using AsyncTask
Android application creates main thread and it will perform all the operation in one main thread if the process is time consuming like handling with network and other time consuming operation application will crash. So that AsyncTask is used to overcome this issue
Asynchronous task
It will perform the main operation in background thread like heavy process in background
Asynchronous task can be done using three threads it easy for understandable
1) onPreExecute() : it will perform initial operation to perform heavy operation
2)doInBackground() : it will perform the heavyy operation
3)onPostExecute() : it will perform with the heavy operation done in doInBackground() thread
In the example i am using mysql for create database and php for generate JSON encoded data
Create database in PhpMyAdmin in your host CPanel or in ( Xamp /WAMP) am creating
database : mobdroidme
Create Table based on your reqirement
PHP script for connection between database
Connect.php
< ?php
$conn = mysql_connect("HostName","database username","database password");
$db = mysql_select_db("database");
?>
select.php
< ?php
include_once("connect.php");
$sqlString = "select * from tablename ";
$rs = mysql_query($sqlString);
if($rs){
while($objRs = mysql_fetch_assoc($rs)){
$output[] = $objRs;
}
echo json_encode($output);
}
mysql_close();
?>
main.xml
< LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="10dp">
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Id Number:"
android:textStyle="bold"
android:gravity="center"
android:textSize="15dp"
android:layout_marginLeft="15dp"
/>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/txt1"
android:layout_marginLeft="20dp"/>
</LinearLayout>
<LinearLayout android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="10dp">
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text=" Name:"
android:textStyle="bold"
android:gravity="center"
android:textSize="15dp"
android:layout_marginLeft="35dp"
/>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/txt2"
android:layout_marginLeft="20dp"/>
</LinearLayout>
<LinearLayout android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="10dp">
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Birthday:"
android:textStyle="bold"
android:gravity="center"
android:textSize="15dp"
android:layout_marginLeft="75dp"
/>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/txt3"
android:layout_marginLeft="20dp"/>
</LinearLayout>
< /LinearLayout>
myinfo.java
package com.rchospitalne;
import android.app.Activity;
import android.app.ProgressDialog;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
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.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
//import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Myinfo extends Activity {
TextView txt1,txt2,txt3;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.myinfo1);
new task().execute();
}
class task extends AsyncTask<String, String, Void>
{
private ProgressDialog progressDialog = new ProgressDialog(Myinfo.this);
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Fetching data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
task.this.cancel(true);
}
});
}
@Override
protected Void doInBackground(String... params) {
String url_select = "http://www.esarmobile.com/newhosp/select.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
// ambil data dari Json database
try {
JSONArray Jarray = new JSONArray(result);
for(int i=0;i<Jarray.length();i++)
{
JSONObject Jasonobject = null;
txt1 = (TextView)findViewById(R.id.txt1);
txt2 = (TextView)findViewById(R.id.txt2);
txt3 = (TextView)findViewById(R.id.txt3);
Jasonobject = Jarray.getJSONObject(i);
//get an output on the screen
String no = Jasonobject.getString("no// this should be same in the table field name");
String name = Jasonobject.getString("name");
String birthday = Jasonobject.getString("birthday");
txt1.setText(no);
txt2.setText(name);
txt3.setText(birthday);
}
this.progressDialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
}
In manifest file add permissions <uses-permission android:name="android.permission.INTERNET"/>
If you find Any difficulty please feel free to comment
hi mohammed nissar. can you make a tutorial on how to (android)get current location (latitude and longitude) every minute and send it to a remote mysql server? tnx :)
ReplyDelete