How to insert and retrieve data from wamp server database in Android Studio


Hello friends, aaj me apko bataunga ki kese aap apne local database yani wamp server localhost me insert aur retrieve operatation kese perform kar sakte hai. Me apko bahut hi short aur simple code se ye application banana sikhaunga. Kai log pura internet chaan marte hai par unko sahi aur simple code nahi mil pata. Par me apko bahut hi asani se ye aap banana sikha dunga.




Yaha pe is video me aap dekh sakte hai ki apki app kesi dekhegi..

Par yaad rakhiye apko mera code bahut samjhdaari se copy karna hoga, apko pata hona chahiye ki kya copy karna hai aur kya copy nahi karna. Mera code exact copy karne se apki application nahi chalegi, toh apko pata hona chahiye ki kaha change karna  hai.

Is android application ko banane ke liye apko 3 software ki zarurat padegi:

  • Wamp Server
  • Android Studio
  • Genymotion (jo ki humara emulator hoga)

Wamp server ko aap yaha se download kar sakte hai.

Wamp server download aur install karne ke baad apne browser me localhost likhiye.

How to insert and retrieve data from wamp server database in Android Studio

 

fir phpmyadmin pe click kare.

How to insert and retrieve data from wamp server database in Android Studio

phpmyadmin me jane ke baad apko database aur table bana padega.

Mere application me database ka naam dbtest2 hai aur table ka naam persons hai.

Table persons me 3 attributes hai:

  • id
  • name
  • address

How to insert and retrieve data from wamp server database in Android Studio

Table banane ke baad apko 2 php script banani padegi, ek data insert karne ke liye aur dusri data retrieve karne ke liye.

Ye dono php script apko C:\wamp\www directory ke andar banani padegi. Matlab apko wamp folder ke andar jo www wala folder hai uske andar ye dono php file banani padegi.

Sabse pehle aap insert_db.php script banaiye. Iska code niche diya hai.


<?php
  define('HOST','localhost');
  define('USER','root');
  define('PASS','');
  define('DB','dbtest2');
  $con = mysqli_connect(HOST,USER,PASS,DB);
  
  $name = $_POST['name'];
  $address = $_POST['address'];
  
  $sql = "insert into persons (name,address) values ('$name','$address')";
  if(mysqli_query($con,$sql)){
    echo 'success';
  }
  else{
    echo 'failure';
  }
  mysqli_close($con);
?>

Iske baad retrive_db.php banaiye.


<?php
error_reporting(E_ALL ^ E_DEPRECATED);
  //define('HOST','localhost');
  //define('USER','root');
  //define('PASS','');
  //define('DB','dbtest2');
  $con=mysql_connect("localhost","root","");
  mysql_select_db("dbtest2",$con);
  
  $r=mysql_query("select name from persons where 1");
  
  while($row=mysql_fetch_array($r))
  {
	  $out[]=$row;
  }
  print(json_encode($out));
  mysql_close($con);
 ?>

Ye toh ho gaya database se related kaam.

Toh chaliye ab bana lete hai humari android application.

Aap android studio open karke project bana lijiye aur usme aap empty activity select kariye.

Toh me apko MainActivity.java  aur activity_main.xml ka code de raha hu aap usko apni samjhdaari ke hisaab se copy kar lena. 😜

//MainActivity.java

package com.example.karankumarkanathe.demo2;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends ActionBarActivity {

    private EditText editTextName;
    private EditText editTextAdd;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editTextName = (EditText) findViewById(R.id.editTextName);
        editTextAdd = (EditText) findViewById(R.id.editTextAddress);


    }

    public void retrive(View view)
    {
        Intent intent=new Intent(MainActivity.this,Main2Activity.class);
        startActivity(intent);
    }

    public void insert(View view){
        String name = editTextName.getText().toString();
        String add = editTextAdd.getText().toString();

        insertToDatabase(name,add);
    }

    private void insertToDatabase(String name, String add){
        class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... params) {
                String paramUsername = params[0];
                String paramAddress = params[1];


                String name = editTextName.getText().toString();
                String add = editTextAdd.getText().toString();

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("name", name));
                nameValuePairs.add(new BasicNameValuePair("address", add));

                try {
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(
                            "http://10.0.3.2/insert-db.php");
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = httpClient.execute(httpPost);

                    HttpEntity entity = response.getEntity();


                } catch (ClientProtocolException e) {

                } catch (IOException e) {

                }
                return "success";
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);

                Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
                TextView textViewResult = (TextView) findViewById(R.id.textViewResult);
                textViewResult.setText("Inserted");
            }
        }
        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
        sendPostReqAsyncTask.execute(name, add);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

//activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:orientation="vertical"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name"
        android:id="@+id/textView" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextName" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Address"
        android:id="@+id/textView2" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextAddress" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Insert"
        android:onClick="insert"
        android:id="@+id/button" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textViewResult" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Retrive"
        android:id="@+id/button2"
        android:onClick="retrive"/>
</LinearLayout>

Ab apko second activity banani hogi.
Main2Activity.java aur activity_main2.xml dono ka code niche hai. Fir se me apko kahunga apni samjhdari se code copy kar lena.😜

//Main2Activity.java

package com.example.karankumarkanathe.demo2;

import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.google.api.client.http.HttpResponse;

import org.apache.http.HttpEntity;
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.JSONObject;

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

public class Main2Activity extends AppCompatActivity {

    ListView lv;
    String[] names={"abc","xyz","pqr","lmn"};
    InputStream is=null;
    String line=null;
    String result=null;
    String temp="";
    String[] arr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
       lv=(ListView)findViewById(R.id.listView);
      // lv.setAdapter(new ArrayAdapter<String>(Main2Activity.this, android.R.layout.simple_list_item_1, names));

        StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        try {
            HttpClient httpClient= new DefaultHttpClient();
            HttpPost httpPost=new HttpPost("http://10.0.3.2/retrive_db.php");
            org.apache.http.HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            is=entity.getContent();

        }catch (Exception e) {
            System.out.println("Exception 1 caught");
        }

        try {
            BufferedReader reader= new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);

            StringBuilder sb=new StringBuilder();
            while ((line=reader.readLine())!=null)
                sb.append(line+"\n");

            result=sb.toString();
            is.close();

            System.out.println("--------------------Here is my data-----------------");
            System.out.println(result);
            System.out.println("Here is my data");



        }catch (Exception e){
                System.out.println("Exception 2 caught");
        }

        try{
            JSONArray jsonArray = new JSONArray(result);
            int count= jsonArray.length();
            for (int i=0;i<count;i++){
                JSONObject jsonObject=jsonArray.getJSONObject(i);
                temp+=jsonObject.getString("name")+":";
            }
            arr=temp.split(":");
            lv.setAdapter(new ArrayAdapter<String>(Main2Activity.this,android.R.layout.simple_list_item_1,arr));
        }catch (Exception e){
            System.out.println(" I am bored...");
            Log.e("BHAI YAHA"," GALATI HAI:" + e.getMessage());
        }
    }
}

//activity_main2.xml

<?xml version="1.0" encoding="utf-8"?>
<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.karankumarkanathe.demo2.Main2Activity">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="64dp" />
</RelativeLayout>

AndroidMainfest.xml me Internet ki permission lena mat bhulna.
<uses-permission android:name=”android.permission.INTERNET” />

Agar apko koi problem is application se related ho toh comment zaroor karna.



Add a Comment

Your email address will not be published. Required fields are marked *