Showing posts with label android database. Show all posts
Showing posts with label android database. Show all posts

Wednesday, 4 February 2015

android-client-server-database-with-php

Android Application Development With PHP and MySql DataBase

Hi Reader, 
Welcome Back in my new Post with very exiting an useful topic in android application development, when we going to create an Web Base Android Application, or such application that  data base required to share with several user then we have to create our application on live server.

Today  i am going to explain android client server architecture.
In This Scenario our application store in PHONE ie is client and our database store on server, and client have to send a reqest to server  and on behalf of that request server return response.  if response is null then we not connetct to server or some internet issue.
   try{
 HttpClient httpclient = new DefaultHttpClient();
           HttpPost httppost = new HttpPost("http://www.apsmind.com/foodcorner/fetchfeedback.php");
                
           
            HttpResponse response = httpclient.execute(httppost);
            if(response!=null)
            System.out.println("Connection created");
            HttpEntity entity = response.getEntity();
            InputStream isr = entity.getContent();
}
catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
    }
            
By writing these code you got your response in your InputStream Object. Now you have to convert in to text.
 //convert response to string
   try{
    InputStreamReader isre= new InputStreamReader(isr,"iso-8859-1");
           BufferedReader reader = new BufferedReader(isre,8);
           StringBuilder sb = new StringBuilder();
           String line = null;
           while ((line = reader.readLine()) != null) {
                   sb.append(line + "\n");
           }
           isr.close();
        String    result=sb.toString();
         //  tv.setText(result);
   }catch(Exception e){
           Log.e("log_tag", "Error converting result "+e.toString());
   }
By writing these code you got your response in your String object. But if your data in json format like this

[{"comment":"good","name":"ravikant","Rating":"3"},{"comment":"Nice app","name":"Akshu","Rating":"5"},{"comment":"nice","name":"Ravi","Rating":"5"},{"comment":"interesting","name":"amit","Rating":"5"},{"comment":"Awesum App","name":"Shobha","Rating":"5"}]

then you have to parse it.
try{
    String record1 = " ";
        JSONArray    jArray = new JSONArray(result);
        for(int i=0;i
        {
        JSONObject json = jArray.getJSONObject(i);
        record1 = record1+"\n" +" Name : "+json.getString("name")+
        "Rating: "+json.getInt("Rating")+"\n" +" Comment : "+json.getString("comment");
        tv.setText(record1);
        }
   }catch(JSONException e){
           Log.e("log_tag", "Error parsing data "+e.toString());
   }
    
    }

How To Create Complete Project:-

1. Install XAMPP Server if not install yet.

2.start apache and mysql.



3. click on Mysql Admin Button :

  1.        create an database name APSMINDTECHNOLOGY


   2.   create an table name courses with these field 

C_IDC_NameC_DurC_Fee
   3. then enter some record:


C_IDC_NameC_DurC_Fee
EditDelete1Java3 Month5000
EditDelete2Android3 Month7500
EditDelete3php++48500
EditDelete5Phonegap3 Month12000
EditDelete6Webdesigning3 Month8500
EditDelete7ccna3 Month9000
EditDelete8CLOUD3 Month10000
EditDelete9CLOUD3 Month10000
EditDelete10c12000
EditDelete11Java2.5 month5000
EditDelete15Oractle3month8000
EditDelete13Oractle3month8000
EditDelete14Oractle3month8000

4.create an php file and save within c://XAMPP/htdocs/project/fetch.php

$server= mysql_connect("localhost","root","") or die("could not connect");
$db = mysql_select_db("APSMINDTECHNOLOGY",$server); 
                         $result = mysql_query("select * from courses");
                        while($row= mysql_fetch_assoc($result))
                {
                             $output[]=$row;
                }
                         print(json_encode($output));
                         mysql_close($db);
5. Check your PhP code by this way : 
open web browser and open this url http://localhost/project/fetch.php
you got result like this:

[{"C_ID":"1","C_Name":"Java","C_Dur":"3 Month","C_Fee":"5000"},{"C_ID":"2","C_Name":"Android","C_Dur":"3 Month","C_Fee":"7500"},{"C_ID":"3","C_Name":"php++","C_Dur":"4","C_Fee":"8500"},{"C_ID":"5","C_Name":"Phonegap","C_Dur":"3 Month","C_Fee":"12000"},{"C_ID":"6","C_Name":"Webdesigning","C_Dur":"3 Month","C_Fee":"8500"},{"C_ID":"7","C_Name":"ccna","C_Dur":"3 Month","C_Fee":"9000"},{"C_ID":"8","C_Name":"CLOUD","C_Dur":"3 Month","C_Fee":"10000"},{"C_ID":"9","C_Name":"CLOUD","C_Dur":"3 Month","C_Fee":"10000"},{"C_ID":"10","C_Name":"c","C_Dur":"1","C_Fee":"2000"},{"C_ID":"11","C_Name":"Java","C_Dur":"2.5 month","C_Fee":"5000"},{"C_ID":"15","C_Name":"Oractle","C_Dur":"3month","C_Fee":"8000"},{"C_ID":"13","C_Name":"Oractle","C_Dur":"3month","C_Fee":"8000"},{"C_ID":"14","C_Name":"Oractle","C_Dur":"3month","C_Fee":"8000"}]

6. Now you have to create an Android Application name ExternalDataBaseTest
            i.   open MainActivity.java file

package com.example.externaldatabasetest;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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.os.AsyncTask;
import android.os.Bundle;


import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
TextView tv;
String record1 = " ";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView)findViewById(R.id.textView2);
       
   new Asy().execute();
    }
    class Asy extends AsyncTask
    {
    @Override
    protected Void doInBackground(Void... params) {
    // TODO Auto-generated method stub
    getData();
    return null;
    }
    @Override
    protected void onPostExecute(Void result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
    tv.setText(record1);
    }
    }
    public void getData()
    {
    String result = " ";
    InputStream isr = null;
    // To getting Data
    try
    {
     HttpClient httpclient = new DefaultHttpClient();
           HttpPost httppost = new HttpPost("http://10.0.2.2/androidtrainer.netne.net/courselist.php");
                
           
            HttpResponse response = httpclient.execute(httppost);
            if(response!=null)
            System.out.println("Connection created");
            HttpEntity entity = response.getEntity();
            isr = entity.getContent();
           

    }
    catch(Exception e)
    {
    Log.i("Error",e.toString());
    // tv.setText("Connection not created");
    }
     //convert response to string
   try{
    InputStreamReader isre= new InputStreamReader(isr,"iso-8859-1");
           BufferedReader reader = new BufferedReader(isre,8);
           StringBuilder sb = new StringBuilder();
           String line = null;
           while ((line = reader.readLine()) != null) {
                   sb.append(line + "\n");
           }
           isr.close();
           result=sb.toString();
           System.out.println(sb);
         //  tv.setText(result);
   }catch(Exception e){
           Log.e("log_tag", "Error converting result "+e.toString());
   }
  try{
   
        JSONArray    jArray = new JSONArray(result);
        for(int i=0;i
        {
        JSONObject json = jArray.getJSONObject(i);
        record1 = record1+"\n" +i+" Name : "+json.getString("C_Name")+
        " Fee: "+json.getString("C_Fee");
        // tv.setText(record1);
        }
        System.out.println(record1);
   }catch(JSONException e){
           Log.e("log_tag", "Error parsing data "+e.toString());
   }
    
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}


ii. one activity_main.xml file


    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

   
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

       
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

           
                android:id="@+id/textView1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge" />

           
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Large Text"
                android:textAppearance="?android:attr/textAppearanceLarge" />

       
   


iii. add internet permission in AndroidManifest.xml
uses-permission android:name="android.permission.INTERNET"
iv. 
Now you test your application in emulator or bluestack.






Tuesday, 14 October 2014

android-database-example

Android Data Base 

In Android Device sqlite database is use to store information. i am going to  give very example to maintain all crucial operation on database like database creation table creation record insertion, deletion, updation and view.

Code for activity_main.xml file


- <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scrollView1" android:layout_width="fill_parent" android:layout_height="fill_parent">
- <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
  <TextView android:id="@+id/textView1" android:layout_width="195dp" android:layout_height="wrap_content" android:text="Plz Fill This Form" android:textAppearance="?android:attr/textAppearanceLarge" />
- <EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="name" android:inputType="textPersonName">
  <requestFocus />
  </EditText>
  <EditText android:id="@+id/editText2" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="phno" android:inputType="phone" />
  <EditText android:id="@+id/editText3" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="emailid" android:inputType="textEmailAddress" android:text="" />
  <EditText android:id="@+id/editText4" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="add" android:inputType="textPostalAddress" />
  <Button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Register New Record" />
  <Button android:id="@+id/button2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="View All Record" />
  <Button android:id="@+id/button5" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="UPDATE YOUR EXisting Record" />
- <TableRow android:id="@+id/tableRow1" android:layout_width="match_parent" android:layout_height="wrap_content">
  <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Delete By ID" />
  <EditText android:id="@+id/editText5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint="Enter Id to Update and Delete Record" android:inputType="number" />
  </TableRow>
  <Button android:id="@+id/button4" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Get By Id" />
  </LinearLayout>
  </ScrollView>

Source code for MainActivity.java file:



package com.apsmind.ddbconnect;

import android.os.Bundle;
import android.provider.BaseColumns;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.InputFilter.LengthFilter;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
EditText n1,phno,e1,add,edit;
Button b1,b2,b3,b4,b5;

TextView t1;
Record record=new Record(MainActivity.this);;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=(TextView)findViewById(R.id.textView1);
n1=(EditText)findViewById(R.id.editText1);
phno=(EditText)findViewById(R.id.editText2);
e1=(EditText)findViewById(R.id.editText3);
add=(EditText)findViewById(R.id.editText4);
b1=(Button)findViewById(R.id.button1);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.button3);
b4=(Button)findViewById(R.id.button4);
b5=(Button)findViewById(R.id.button5);
edit=(EditText)findViewById(R.id.editText5);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name=n1.getText().toString();
String phone=phno.getText().toString();
String email=e1.getText().toString();
String address=add.getText().toString();
SQLiteDatabase db=record.getWritableDatabase();/*to open database in writable format*/
ContentValues values= new ContentValues();/*a class whoese object helps to insert values in table*/
values.put(Record.Col1_name, name);
values.put(Record.Col3_password, phone);
values.put(Record.Col2_email,email );
values.put(Record.Col4_address, address);
db.insert(Record.Table_name, null, values);//null stands for null hacker(insert null for not defined positions
n1.setText("");
phno.setText("");
e1.setText("");
add.setText("");
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,Activity1.class);
startActivity(i);
}
});
//get by id
b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String id= edit.getText().toString();
SQLiteDatabase db=record.getWritableDatabase();
try{
db.delete(Record.Table_name, BaseColumns._ID+"="+id, null);
}
catch(Exception e)
{
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
Toast.makeText(MainActivity.this,"deleted", Toast.LENGTH_SHORT).show();
}
});
b5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String id= edit.getText().toString();
String name=n1.getText().toString();
String phone=phno.getText().toString();
String email=e1.getText().toString();
String address=add.getText().toString();
try{
SQLiteDatabase db=record.getWritableDatabase();/*to open database in writable format*/
ContentValues values= new ContentValues();/*a class whoese object helps to insert values in table*/
values.put(Record.Col1_name, name);
values.put(Record.Col3_password, phone);
values.put(Record.Col2_email,email );
values.put(Record.Col4_address, address);
db.update(Record.Table_name, values, BaseColumns._ID+"="+id, null);
}
catch(Exception e)
{
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
});
b4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String id= edit.getText().toString();
try{
SQLiteDatabase db=record.getReadableDatabase();
Cursor mCursor =
               db.query( Record.Table_name,null, BaseColumns._ID+"="+id, null,
               null, null, null, null);
       if (mCursor != null) {
          while(mCursor.moveToNext())
          {
           n1.setText(mCursor.getString(1));
           phno.setText(mCursor.getString(2));
           e1.setText(mCursor.getString(3));
           add.setText(mCursor.getString(4));
          }
       }
}
catch(Exception e)
{
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
});
}

@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;
}

}

Create another Record.java file.

package com.apsmind.ddbconnect;


import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.provider.OpenableColumns;
import android.util.Log;

public class Record extends SQLiteOpenHelper
{

public static final String DB_name = "Student.db";
public static final int DB_version =2;
public static final String Table_name ="Info";
public static final String Col1_name = "Name";
public static final String Col2_email ="Email";
public static final String Col3_password ="Password";
public static final String Col4_address = "Address";
String query;


public Record(Context context) 
{
super(context, DB_name, null, DB_version);/*null being cursor position*/
}
@Override
public void onCreate(SQLiteDatabase db) 
{
query =  "CREATE TABLE " + Table_name + "( " + BaseColumns._ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + Col1_name + " TEXT, "
+ Col2_email + " TEXT," +Col3_password+ " not null," +Col4_address+ " text not null );";
Log.d("Eventsdata", "onCreate"  +query);
db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
{
{
if (oldVersion >= newVersion)
return;/*code to apply if database is sent from one version to another*/

String sql = null;
if (oldVersion == 1) 
sql = "alter table " + Table_name + " add note text;";
if (oldVersion == 2)
sql = "";

Log.d("EventsData", "onUpgrade : " + sql);
if (sql != null)
db.execSQL(sql);
}
}


}




Create Another Activity for view all record:-

source code for .xml file:
- <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scrollView1" android:layout_width="fill_parent" android:layout_height="fill_parent">
- <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
  <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Medium Text" android:textAppearance="?android:attr/textAppearanceMedium" />
  </LinearLayout>
  </ScrollView>




package com.apsmind.ddbconnect;

import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.widget.TextView;
public class Activity1 extends Activity {


TextView t1;
Record eventsdata;
@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_activity1);
 t1=(TextView)findViewById(R.id.textView1);
 eventsdata =new Record(this);
 SQLiteDatabase db=eventsdata.getReadableDatabase();//event is an entry of database table
 Cursor cursor=db.query(Record.Table_name, null, null, null, null, null, null);
 StringBuilder stb=new StringBuilder("Saved Events :\n\n");
while(cursor.moveToNext())
{
 long id=cursor.getLong(0);
 String name=cursor.getString(1);
 String email=cursor.getString(2);
 String password=cursor.getString(3);
 String address=cursor.getString(4);
  stb.append(id +": name--: " + name +",\n"+ " email--:" + email +",\n"+ " password--:" + password +",\n"+ " address--:" + address + "\n\n");
}
 t1.setText(stb);
 
 
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity1, menu);
return true;
}

}

Today's Pageviews