Friday 30 May 2014

Better way to insert in to mysql from android application

I THINK WITH CONFIGURATIONS AND MINOR CHANGES THIS SHOULD HELP YOU



first you need to set up php
//androidmysql is the project folder in your localhost


make sure the php file contains no html tags  for better results
leave it plain
conn.php

<?php
$connect=mysql_connect("localhost","root","");
$mysql_select_db("users",$connect);
?>
dont forget to create database users and table user with username and password

here is the insert.php

<?php
include conn.php
$user=$_POST['username'];
$pass=$_POST['password'];
//these are posted fromandroid application
$sql=mysql_query("insert into user(username,password) values ('$user','$pass')");
//you are done

if($sql)
{
  $output['success']=1;
  json_encode($output);
  print(json_encode($output))
}

if(!$sql)
{
  $output['success']=2;
  json_encode($output);
  print(json_encode($output))
}
?>

Now lets go to android
android manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.anroidmysql"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.anroidmysql.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


main layout

<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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="18dp"
        android:layout_marginTop="22dp"
        android:text="username"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="46dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="48dp"
        android:text="password"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_alignRight="@+id/editText1"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="32dp"
        android:ems="10" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText2"
        android:layout_alignRight="@+id/editText2"
        android:layout_below="@+id/editText2"
        android:layout_marginTop="38dp"
        android:text="register" />

</RelativeLayout>


MainActivity.java
package com.example.anroidmysql;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
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;
import android.widget.Toast;

public class MainActivity extends Activity {
String url="http://10.10.6.124/androidmysql/insert.php";
//androidmysql is the project folder in your localhost

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText username=(EditText)findViewById(R.id.editText1);
final EditText pass=(EditText)findViewById(R.id.editText2);
Button reg=(Button)findViewById(R.id.button1);
reg.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username",username.getText().toString()));
params.add(new BasicNameValuePair("password",pass.getText().toString()));

try {
UrlEncodedFormEntity uefa = new UrlEncodedFormEntity(params);
post.setEntity(uefa);
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
Log.e("feedback", data);
try {
JSONObject object = new JSONObject(data);
int result = object.getInt("success");
if (result == 1) {
Toast.makeText(getApplicationContext(), "registration complete",
Toast.LENGTH_LONG).show();
}

if (result == 2) {
Toast.makeText(getApplicationContext(), "username already taken",
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
});
}

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

}