Tuesday, July 16, 2013

Android Notification Example

This Tutorial for Showing Fake push notification in android device

1) Create xml layout for android event handler button for display notification
 
   <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="createNotification"
        android:text="Create Notification" >
    </Button>

</LinearLayout>

2)Create the xml layout result.xml to display screen after notification recieved

     <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is the result activity opened from the notification" >
    </TextView>

</LinearLayout>


Create java class CreateNotificationActivity which extends Activity . This class create notification will be display on the android notification bar

import android.app.Activity;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class CreateNotificationActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }

  public void createNotification(View view) {
    // Prepare intent which is triggered if the
    // notification is selected
    Intent intent = new Intent(this, NotificationReceiverActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

    // Build notification
    // Actions are just fake
    Notification noti = new Notification.Builder(this)
        .setContentTitle("New mail from " + "test@gmail.com")
        .setContentText("Subject").setSmallIcon(R.drawable.icon)
        .setContentIntent(pIntent)
        .addAction(R.drawable.ic_launcher, "Call", pIntent)
        .addAction(R.drawable.ic_launcher, "More", pIntent)
        .addAction(R.drawable.ic_launcher, "And more", pIntent).build();
    noti.defaults |= Notification.DEFAULT_VIBRATE |
            Notification.DEFAULT_LIGHTS |
            Notification.DEFAULT_SOUND;
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    // Hide the notification after its selected
    noti.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(0, noti);

  }
}


Create Java class NotificationReceiverActivity for display the result activity after the notification pressed

import android.app.Activity;
import android.os.Bundle;

public class NotificationReceiverActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.result);
  }
}


If you face any problem comment here 
     

Sunday, July 14, 2013

Android Simple Splash Screen

It is the very simple android splash screen with xml layout with splash screen background and display it for particular interval of time


1 )Create xml layout main.xml with splash screen background

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/splash">
 </LinearLayout>

2) Create java class Splash.java which is having a thread to display main.xml layout screen for particular interval of time


public class Splash extends Activity {

    @Override
    public void onCreate(Bundle saved .InstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Thread splashTimer =new Thread()
        {
        public void run()
        {
        try{
        sleep(3000);
                 startActivity(new Intent(Splash.this,language.class));
        }
        catch(Exception e)
        {
        Log.e("splash",e.toString());
        }
        finally
        {
        finish();
        }
        }
        };splashTimer.start();
    }

It is very simple android splash screen if you have any doubts comment it 

Saturday, July 13, 2013

Android Splash Screen with Back ground and logo Tutorial

Simple Splash Screen with back Ground and Icon 
 This splash screen displayed using thread by allowing particular interval of time sleep 
  I am writing code for displaying splash screen with background image and logo 

  Note :  put your background image and logo in res-draw-able folder 

1) Create Class Image which extends View
    This class  create the canvas and initiate background image or color and icon in the canvas

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;

import android.view.View;
public class Image extends View {
Bitmap bitmapOrg;

int b, c;

public Image(Context context) {

super(context);

bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.logo);

}

@Override
protected void onDraw(Canvas canvas) {

super.onDraw(canvas);
toHelpDrawing(canvas);
}

private void toHelpDrawing(Canvas canvas) {
b = getWidth();
c = getHeight();
setBackgroundResource(R.drawable.backgrounds) ;
       // setBackgroundColor(Color.GRAY);
canvas.drawBitmap(bitmapOrg, b / 2 - bitmapOrg.getWidth() / 2, c / 2
- bitmapOrg.getHeight() / 2, null);

}
}

2)  Create class Splash which will call Image class and using thread allow display the screen particular interval of time then next activity will appear

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;



public class Splash extends Activity {
//private DataBaseTableCreater dbtc;
//DBAdapter dba=new DBAdapter(this);
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      

        setContentView(new Image(this));
       // dbtc=new DataBaseTableCreater(this);
       // dbtc.createTables();
        //dbtc=null;
        //Constants c = new Constants();
        Thread splashTimer =new Thread()
        {
        public void run()
        {
        try{
        sleep(2000);
                        startActivity(new Intent(Splash.this,LoginDummy.class));
                     } 
        catch(Exception e)
        {
        Log.e("splash",e.toString());
        }
        finally
        {
        finish();
        }
        }
        };splashTimer.start();
    }
}
  
It is the standard splash screen without using xml layout in my next tutorial i will write the splash screen using xml layout 

if you have any doubt comment it 

Sunday, July 7, 2013

Android Sending and Recieving Mail Through a your SMTP Port using AsyncTask

In this tutorial i will describe how to send a mail through your smtp port in your application 
  1) For sending or receiving mail you need three jar files i will mention the link for download at the end of tutorial 
2)create xml layout for send mail it can contain to address filed from address field and subject as well as details field
mail.xml

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:background="@drawable/background" >

      

        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="100px"
            android:text="To" />

        <EditText
            android:id="@+id/to"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:inputType="textEmailAddress"
            
             />

        <TextView
            android:id="@+id/Tex"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Subject" />

        <EditText
            android:id="@+id/subject"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="Enter the Deseas" />

        <TextView
            android:id="@+id/textView5"
            android:layout_width="fill_parent"
            android:layout_height="30dp"
            android:text="body" />

        <EditText
            android:id="@+id/body"
            android:layout_width="fill_parent"
            android:layout_height="100dp"
            android:inputType="textMultiLine"
            android:hint="Enter the details about deseas" />

        <Button
            android:id="@+id/send"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Send" />
    </LinearLayout>


3) Create Package name called com.provider in that package create class JSSEProvider.java it extends provider 

package com.provider;

import java.security.Provider;

import java.security.AccessController;
import java.security.Provider;

public class JSSEProvider extends Provider {
        public JSSEProvider() {
        super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
        AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
            public Void run() {
                put("SSLContext.TLS",
                        "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
                put("Alg.Alias.SSLContext.TLSv1", "TLS");
                put("KeyManagerFactory.X509",
                        "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
                put("TrustManagerFactory.X509",
                        "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
                return null;
            }
        });
    }


4) Create Class GSender in this class add your SMTP domain and 
import javax.activation.DataHandler;

import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;

public class GSender extends javax.mail.Authenticator {
private String mailhost = "mail.yourhost(please give your host name here).com";
private String user;
private String password;
private Session session;

static {
Security.addProvider(new com.provider.JSSEProvider());
}

public GSender(String user, String password) {
this.user = user;
this.password = password;

Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "587");     //Give in the  place of 587 your port number 
props.put("mail.smtp.socketFactory.port", "587");
//props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");

session = Session.getDefaultInstance(props, this);
}

protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}

public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
}

public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;

public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}

public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}

public void setType(String type) {
this.type = type;
}

public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}

public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}

public String getName() {
return "ByteArrayDataSource";
}

public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}


5) Create class SendMail.java 

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

public class SendMail extends Activity{
EditText to,subject,body;
Button send;
String userid = "example@yourdomain.com";
    String password = "your password";    
String from = "example@yourdomain.com";
@Override   
     public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.mail);
             final EditText to = (EditText) this.findViewById(R.id.to);
             final EditText subject = (EditText) this.findViewById(R.id.subject);
             final EditText body = (EditText) this.findViewById(R.id.body);
             send = (Button)findViewById(R.id.send);
             send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
 final GSender sender = new GSender(userid, password);
  new AsyncTask<Void, Void, Void>() {
       @Override public Void doInBackground(Void... arg) {
           try {   
            sender.sendMail(subject.getText().toString(), body
                                            .getText().toString(), from.toString(),
                                            to.getText().toString());  
           } catch (Exception e) {   
               Log.e("SendMail", e.getMessage(), e);   
           }
return null;
 
       }
   }.execute();
   }
});
          
         
            
}
}

I have mention the link for download jar files to send mail please find the below link and dowload the files and import into project 


https://code.google.com/p/javamail-android/downloads/list


If you find any difficulty please give a comment  or send me the mail 

Android Update Remote MySql Data Using JSON PHP

This tutorial describes Update remote data in android system from MySql database using PHP and storing that in  layout .

 1)First Create Database and table Update  in mysql
      Update.sql
      Create the fields ID ,Email,Mobile No,Hometel,WorkTel

2)Create Update.php file

<?php
mysql_connect("localhost","MYSQL USERNAME","MYSQL PASSWORD");
mysql_select_db("DATABASE NAME");
//$sql=mysql_query("update rcmyinfo set email ='".$_REQUEST['e_mail']."'  where medno = '".$_REQUEST['medical_no']."'");
$sql=mysql_query("update rcmyinfo set email ='".$_REQUEST['e_mail']."',worktel = '".$_REQUEST['wk_no']."' ,hometel = '".$_REQUEST['hm_no']."', mobno = '".$_REQUEST[mob_no]."'  where medno = '".$_REQUEST['medical_no']."'");
$r=mysql_query($sql);
if(!$r)
echo "Error in query: ".mysql_error();
mysql_close();
?>

3) Create XML File
 
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   
    android:orientation="vertical" >
   
<LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#971317" >

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/back"
            android:background="#00000000"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="50dp"
         
            android:textSize="20dp"
            android:textColor="#ffffffff" />
    </LinearLayout>
<LinearLayout android:layout_height="wrap_content"
     android:layout_width="fill_parent"
     android:orientation="horizontal"
     android:layout_marginTop="10dp">
  <TextView android:layout_height="25dp"
      android:layout_width="wrap_content"
      android:text="Medno"
      android:textStyle="bold"
      android:gravity="center"
      android:textSize="15dp"

      android:layout_marginLeft="45dp"
      />
  <EditText android:layout_height="35dp"
      android:layout_width="fill_parent"
      android:background="#b22222"
      android:id="@+id/editmed"
      android:layout_marginLeft="30dp"/>
  </LinearLayout>

 <LinearLayout android:layout_height="wrap_content"
     android:layout_width="fill_parent"
     android:orientation="horizontal"
     android:layout_marginTop="10dp">
  <TextView android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:text="Email"
      android:textStyle="bold"
      android:gravity="center"
      android:textSize="15dp"

      android:layout_marginLeft="45dp"
      />
  <EditText android:layout_height="35dp"
      android:layout_width="fill_parent"
      android:background="#b22222"
      android:id="@+id/edit1"
      android:layout_marginLeft="40dp"/>
  </LinearLayout>
  <LinearLayout android:layout_height="wrap_content"
     android:layout_width="fill_parent"
     android:orientation="horizontal"
     android:layout_marginTop="10dp">
  <TextView android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:text="Mobile No"
      android:textStyle="bold"
      android:gravity="center"
      android:textSize="15dp"
      android:layout_marginLeft="30dp"
      />
  <EditText android:layout_height="35dp"
      android:layout_width="fill_parent"
      android:background="#b22222"
      android:id="@+id/edit2"
      android:layout_marginLeft="25dp"/>
  </LinearLayout>
  <LinearLayout android:layout_height="wrap_content"
     android:layout_width="fill_parent"
     android:orientation="horizontal"
     android:layout_marginTop="10dp">
  <TextView android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:text="Home Tel:"
      android:textStyle="bold"
      android:gravity="center"
      android:textSize="15dp"
      android:layout_marginLeft="30dp"
      />
  <EditText android:layout_height="35dp"
      android:layout_width="fill_parent"
      android:id="@+id/edit3"
      android:background="#b22222"
      android:layout_marginLeft="25dp"/>
 
  </LinearLayout>
  <LinearLayout android:layout_height="wrap_content"
     android:layout_width="fill_parent"
     android:orientation="horizontal"
     android:layout_marginTop="10dp">
  <TextView android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:text="Work Tel:"
      android:textStyle="bold"
      android:gravity="center"
      android:textSize="15dp"
      android:layout_marginLeft="30dp"
      />
  <EditText android:layout_height="35dp"
      android:layout_width="fill_parent"
      android:id="@+id/edit4"
      android:background="#b22222"
      android:layout_marginLeft="30dp"/>
 
  </LinearLayout>
 
  <Button
      android:layout_marginTop="20dp"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="center"
      android:id="@+id/save"
      android:text="Save"/>
 
  <TextView android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/lblResult"
      android:textColor="#ff000000"/>
  <LinearLayout android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:background="#ff000000"
    android:layout_marginTop="160dp">
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#971317"
        android:text="Personal"
        android:id="@+id/info"
        android:drawableTop="@drawable/profile"
        android:textColor="#ffffffff"/>
    <Button android:layout_width="wrap_content"
       android:layout_height="wrap_content"
        android:background="#971317"
        android:text="Medical"
        android:id="@+id/medical"
        android:textColor="#ffffffff"
        android:drawableTop="@drawable/gish"
        android:layout_marginLeft="0.1dp"/>
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#971317"
        android:text="Update"
        android:id="@+id/update"
         android:drawableTop="@drawable/info"
        android:textColor="#ffffffff"
        android:layout_marginLeft="0.1dp"/>
    <Button android:layout_width="wrap_content"
         android:layout_height="wrap_content"
        android:background="#971317"
        android:textColor="#ffffffff"
        android:text="Family"
        android:id="@+id/family"
        android:drawableTop="@drawable/gish"
        android:layout_marginLeft="0.1dp"/>
    <Button android:layout_width="fill_parent"
         android:layout_height="wrap_content"
        android:background="#971317"
        android:text="Other"
        android:textColor="#ffffffff"
        android:id="@+id/other"
        android:drawableTop="@drawable/update"
        android:layout_marginLeft="0.1dp"/>
</LinearLayout>

</LinearLayout>
</ScrollView>

4)Create Java Class Updateinfonew.java in android project to update data


import java.io.InputStream;
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 android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Updateinfonew extends Activity
{
EditText email,mobile,home,work,medino;
         Button save;
 public void onCreate(Bundle savedInstanceState)
   {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.update);
   
      save = (Button)findViewById(R.id.save);
      save.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new task1().execute();
}
});
}
class task1 extends  AsyncTask<String, String, Void>
   {

String em,mob,hmtel,wktel,medical;
InputStream is = null ;
    protected void onPreExecute()
{
email = (EditText)findViewById(R.id.edit1);
   mobile = (EditText)findViewById(R.id.edit2);
   home = (EditText)findViewById(R.id.edit3);
   work = (EditText)findViewById(R.id.edit4);
   medino = (EditText)findViewById(R.id.editmed);

   lblResult = (TextView)findViewById(R.id.lblResult);
   em = email.getText().toString();
   mob = mobile.getText().toString();
   hmtel = home.getText().toString();
wktel = work.getText().toString();
   medical = medino.getText().toString();
}
    @Override
      protected Void doInBackground(String... params)
           {
       try
     {
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("e_mail",em));
       nameValuePairs.add(new BasicNameValuePair("mob_no",mob));
       nameValuePairs.add(new BasicNameValuePair("hm_no",hmtel));
       nameValuePairs.add(new BasicNameValuePair("wk_no",wktel));
       nameValuePairs.add(new BasicNameValuePair("medical_no",medical));
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.esarmobile.com/newhosp/update.php");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
         }
       catch(Exception e){
    Log.e("log_tag", "Error in http connection"+e.toString());
    }
     
    return null;
 }
protected void postExecute(Void v)
{
lblResult.setText("updation successfull");
Toast.makeText(getBaseContext(), "Updation Successfull", Toast.LENGTH_LONG).show();



//medical = (Button)findViewById(R.id.medical);
//family = (Button)findViewById(R.id.family);


}
}
@Override
public void onBackPressed() {
Intent home = new Intent(getApplicationContext(),Dashboard.class);
   startActivity(home);
 }
}


I have done application using ASYNCTASK so that it will support all android device if you find problem please comment

Saturday, July 6, 2013

Android Remote Database Accessing using AsyncTask

Android Access Remote Database Using AsyncTask


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 

Android Tutorial For Remote Mysql data storing in a table Layout

This tutorial describes fetching remote data from MySql database using PHP and storing that in table layout .

This task done with 5 steps
1) Create mysql database
2) PHP script for fetching data from remote database and echo it as JSON Format
3)Create XML table layout
5) Create JSONPARSER class to parse JSON Data
4) Convert JSON encoded data and store it in JSON parsed array .Extract value from JSON parsed array and store it in table



 1)First Create Database and table Example  in mysql
      Example.sql

CREATE TABLE `Example` (
  `COURSE` varchar(10) COLLATE latin1_general_ci NOT NULL,
  `COURSE_NAME` varchar(25) COLLATE latin1_general_ci NOT NULL,
  `CR` varchar(10) COLLATE latin1_general_ci NOT NULL,
  `CT` varchar(10) COLLATE latin1_general_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;



2)Create PHP script for fetch data from database and echo it as JSON format  
     example.php
<?php
mysql_connect("localhost","MYSQL USERNAME","MYSQL PASSWORD");
mysql_select_db("DATABASE NAME");
$response = array();
$sql = mysql_query("SELECT *FROM Example") or die(mysql_error());
// check for empty result
if (mysql_num_rows($sql) > 0) {
    // looping through all results
    // products node
    $response["Assessments1"] = array();
    while ($row = mysql_fetch_array($sql)) {
        // temp user array
        $Assessments12 = array();
        $Assessments12["COURSE"] = $row["COURSE"];
        $Assessments12["COURSE_NAME"] = $row["COURSE_NAME"];
        $Assessments12["CR"] = $row["CR"];
        $Assessments12["CT"] = $row["CT"];
        
        // push single product into final response array
        array_push($response["Assessments1"], $Assessments12);
    }
    // success
    $response["success"] = 1;
    // echoing JSON response
    echo json_encode($response);
} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No products found";
    // echo no users JSON
    echo json_encode($response);
}
?>




3)Table layout for data to be store here only layout is specified and the TableRow and columns are in java code 
    tablemain.xml
   <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:background="#3b3b3b">
    
    <HorizontalScrollView
  android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
> 
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:stretchColumns="0,1"
                    android:id="@+id/main_table" 
                    android:layout_weight="1" 
                    android:layout_height="wrap_content" 
                    android:layout_width="fill_parent"
        >
       
            </TableLayout>
</HorizontalScrollView>
</LinearLayout>


4) Java code for fetch the JSON array and parse JSON array into JSON Object and store it in table layout
   4.1)Create JSONPARSER class to parse json data later this class will be called for parsing json data throughout the application

JSONParser.java

   import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}
}


4.2) Create class parse json data by calling JSONparser class and display it in table 
example.java
   public class example extends Activity {
    /** Called when the activity is first created. */
private static String url = "http://nissarcs.net78.net/android/example.php";
private static final String TAG_Assessments = "Assessments1";
private static final String TAG_CODE = "COURSE";
private static final String TAG_CNH = "COURSE_NAME";
private static final String TAG_CR = "CR";
private static final String TAG_CT = "CT";
JSONArray degree = null;
 tl.addView(tr_head, new TableLayout.LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
        Integer count=0;
        ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
        JSONParser jParser = new JSONParser();
        JSONObject json = jParser.getJSONFromUrl(url);
        try {
// Getting Array of Contacts
        degree = json.getJSONArray(TAG_Assessments);
// looping through All Contacts
for(int i = 0; i < degree.length(); i++){
JSONObject c = degree.getJSONObject(i);
// Storing each json item in variable
   
    String code = c.getString(TAG_CODE);
    String name = c.getString(TAG_CNH);
    String cr = c.getString(TAG_CR);
    String ct = c.getString(TAG_CT);
   
TableRow tr = new TableRow(this);
      if(count%2!=0) tr.setBackgroundColor(Color.BLACK);
      tr.setPadding(0, 0, 0, 2);
      tr.setId(100+count);
      tr.setLayoutParams(new LayoutParams(
      LayoutParams.WRAP_CONTENT,
      LayoutParams.WRAP_CONTENT));
      //Create two columns to add as table data
        // Create a TextView to add date
       
      TextView labelCR = new TextView(this);
      labelCR.setId(200+count); 
      labelCR.setText(cr);
      labelCR.setPadding(5, 5, 5, 5);
      labelCR.setTextColor(Color.BLACK);
      labelCR.setBackgroundColor(Color.GRAY);
      tr.addView(labelCR);
       
      TextView labelSC = new TextView(this);
      labelSC.setId(200+count);
      labelSC.setText(code.toString());
      labelSC.setPadding(5, 5, 5, 5);
      labelSC.setTextColor(Color.BLACK);
      labelSC.setBackgroundColor(Color.LTGRAY);
      tr.addView(labelSC);
       
      TextView labelACTIVITY = new TextView(this);
      labelACTIVITY.setId(200+count);
      labelACTIVITY.setText(name.toString());
      labelACTIVITY.setPadding(5, 5, 5, 5);
      labelACTIVITY.setTextColor(Color.BLACK);
      labelACTIVITY.setBackgroundColor(Color.GRAY);
      tr.addView(labelACTIVITY);
       
      TextView labelSAT = new TextView(this);
      labelSAT.setId(200+count);
      labelSAT.setText(cr.toString());
      labelSAT.setPadding(5, 5, 5, 5);
      labelSAT.setTextColor(Color.BLACK);
      labelSAT.setBackgroundColor(Color.LTGRAY);
      tr.addView(labelSAT);
    // finally add this to the table row
      tl.addView(tr, new TableLayout.LayoutParams(
                          LayoutParams.FILL_PARENT,
                          LayoutParams.WRAP_CONTENT));
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CODE, code);
map.put(TAG_CNH, name);
map.put(TAG_CR, cr);
map.put(TAG_CT,ct);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
 }
}
Output Will be like this 


Please leave the comment if you find any problem with this tutorial