DEVELOPMENT

Posting data to the server with android.....

post android

The Table

For the demonstrating purpose, i've used three fields f1,f2 and f3 in which the data will be stored directly from the user's android system.

post table


build.gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.example.tut.tut_7_4"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example.tut.tut_7_4" >
<uses-permission android:name="android.permission.INTERNET" />
 <application
 android:allowBackup="true"
 android:icon="@mipmap/ic_launcher"
 android:label="@string/app_name"
 android:theme="@style/AppTheme" >
 <activity
 android:name=".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>

  
MainActivity.java
package com.example.tut.tut_7_4;

        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.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 org.apache.http.util.EntityUtils;
        import android.app.Activity;       
        import android.os.AsyncTask;
        import android.os.Bundle;       
        import android.view.View;
        import android.view.View.OnClickListener;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.ProgressBar;
        import android.widget.Toast;
        import android.widget.Toast;

public class MainActivity extends Activity {

    private EditText f1;
    private EditText f2;
    private EditText f3;
    private Button btn;

    private ProgressBar pb;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        f1 = (EditText) findViewById(R.id.f_1);
        f2 = (EditText) findViewById(R.id.f_2);
        f3 = (EditText) findViewById(R.id.f_3);
        pb = (ProgressBar) findViewById(R.id.progressBar1);
        pb.setVisibility(View.GONE);

        btn = (Button) findViewById(R.id.btn);

        btn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                if (f1.getText().toString().length() < 1 || f2.getText().toString().length() < 1 || f3.getText().toString().length() < 1) {

                    Toast.makeText(getBaseContext(), "Please, Enter all fields", Toast.LENGTH_LONG).show();
                } else {
                    pb.setVisibility(View.VISIBLE);
                    new newAsyncTask().execute(f1.getText().toString(), f2.getText().toString(), f3.getText().toString());
                }

            }
        });

    }

    private class newAsyncTask extends AsyncTask<String, Integer, Double>{

        String responseText="Connection error!!!";
        @Override
        protected Double doInBackground(String... params) {
            postData(params[0],params[1],params[2]);
            return null;
        }

        protected void onPostExecute(Double result){
            pb.setVisibility(View.GONE);
            Toast.makeText(getApplicationContext(), responseText, Toast.LENGTH_LONG).show();
        }
        protected void onProgressUpdate(Integer... progress){
            pb.setProgress(progress[0]);
        }

        public void postData(String f,String s, String t) {

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("/post.php"); //url

            try {

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("f1", f));
                nameValuePairs.add(new BasicNameValuePair("f2",s));
                nameValuePairs.add(new BasicNameValuePair("f3",t));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                responseText = EntityUtils.toString(entity);

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

    }
}


res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:background="#FFFFFF"
 android:orientation="vertical"
 >

 <ProgressBar
 android:id="@+id/progressBar1"
 style="?android:attr/progressBarStyleSmall"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_alignParentTop="true"
 />

 <TextView
 android:id="@+id/tf1"
 android:layout_width="80dp"
 android:layout_height="40dp"
 android:gravity="fill_horizontal|fill_vertical"
 android:text="f1"
 android:textColor="#333333"
 android:layout_below="@+id/progressBar1"/>

 <EditText
 android:id="@+id/f_1"
 android:layout_width="200dp"
 android:layout_height="wrap_content"
 android:layout_toRightOf="@id/tf1"
 android:layout_below="@+id/progressBar1"
 >
 </EditText>

 <TextView
 android:id="@+id/tf2"
 android:layout_width="80dp"
 android:layout_height="40dp"
 android:gravity="fill_horizontal|fill_vertical"
 android:text="f3"
 android:layout_below="@+id/tf1"
 android:textColor="#333333" />

 <EditText
 android:id="@+id/f_2"
 android:layout_width="200dp"
 android:layout_height="wrap_content"
 android:layout_toRightOf="@id/tf2"
 android:layout_below="@+id/f_1"
 />
 <TextView
 android:id="@+id/tf3"
 android:layout_width="80dp"
 android:layout_height="40dp"
 android:gravity="fill_horizontal|fill_vertical"
 android:text="f3"
 android:layout_below="@+id/tf2"
 android:textColor="#333333"/>

 <EditText
 android:id="@+id/f_3"
 android:layout_width="200dp"
 android:layout_height="wrap_content"
 android:layout_below="@+id/f_2"
 android:layout_toRightOf="@id/tf3"
 />

 <Button android:id="@+id/btn"
 android:layout_width="100dp"
 android:layout_height="40dp"
 android:text="POST DATA"
 android:textColor="#FFFFFF"
 android:onClick="onClick"
 android:background="#FF7519"
 android:layout_centerHorizontal="true"
 android:layout_below="@+id/f_3"
 />

</RelativeLayout>
post.php - place this file on your server...
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") 
{

$conn=mysql_connect("","","") or die("ERROR");
$db=mysql_select_db("",$conn) or die("ERROR");
$f1=$_POST["f1"];
$f2=$_POST["f2"];
$f3=$_POST["f3"];
 
$id=rand(1000,9999999);

$sql="insert into record(id,f1,f2,f3) values (\"$id\",\"$f1\",\"$f2\",\"$f3\")";
$res=mysql_query($sql,$conn) or die("ERROR");
if($res)
{
 echo "DATA ADDED"; 
} 
else
{
 echo "ERROR";
}

}

?>




Leave a Comment  
Download Code(30)





All rights reserved, the content is copyrighted to the author.

RELATED POST