Home Android PHP MySQL Android MySQL : Insert From EditText,CheckBox,Spinner – Part 2 [Java Code]

Android MySQL : Insert From EditText,CheckBox,Spinner – Part 2 [Java Code]

Android MySQL : Insert From EditText,CheckBox,Spinner – Part 2 [Java Code]


Rating : 5/5 (1)


Series

  1. Part 1 - Introduction.
  2. Part 2 - Java Code
  3. Part 3 - XML Layouts.
  4. Part 4 - PHP Code

 

 

SECTION 1 : Our Dependencies and Manifest.xml

 

Build.Gradle

  • Android Studio has added for us dependencies for AppCompat and Design support libraries.
  • Note we are subclassing AppCompatActivity to make our MainActivity class an activity.
  • We are using Android Networking library so we need to fetch it from the jcenter.
  • Add the it in your build.gradle.

 

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.1"

    defaultConfig {
        applicationId "com.tutorials.hp.mysql_datatypes_save"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile 'com.android.support:design:24.2.0'
    compile 'com.amitshekhar.android:android-networking:0.2.0'

}

 

 

AndroidManifest.xml

 

  • Add Pernmission for making internet connection as we have added below in our manifest.

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tutorials.hp.mysql_datatypes_save">

    <uses-permission android:name="android.permission.INTERNET"/>


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

 

 

 

SECTION 2 : Data Model

Spacecraft class.

Main Responsibility : HOLD INFORMATION OF A SINGLE SPACECRAFT

  • Is our data object.
  • Shall contain properties for a spacecraft.
  • Exposes these through public getters and setters.

 

 

package com.tutorials.hp.mysql_datatypes_save;

/**
 * Created by Oclemy on 10/11/2016 for ProgrammingWizards Channel and http://www.camposha.com.
 */
public class Spacecraft {


    /*
    INSTANCE FIELDS
     */
    private int id;
    private String name;
    private String propellant;
    private int technologyExists;

    /*
    GETTERS AND SETTERS
     */
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPropellant() {
        return propellant;
    }

    public void setPropellant(String propellant) {
        this.propellant = propellant;
    }

    public int getTechnologyExists() {
        return technologyExists;
    }

    public void setTechnologyExists(int technologyExists) {
        this.technologyExists = technologyExists;
    }




    /*
    TOSTRING
     */
    @Override
    public String toString() {
        return name;
    }
}

 

 

 

SECTION 3 : HTTP Client

MySQL Client class.

Main Responsibility : TALKS TO OUR MYSQL VIA PHP

  • Is our http client class.
  • Shall make HTTP POST Requests.
  • We shall attach the data from our views as body parameters to be sent to the server.
  • Once we send data,we receive a response in terms of json array if success or error.
  • Also specifies a static constant which is our api url.

 

 

package com.tutorials.hp.mysql_datatypes_save;

import android.content.Context;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONArrayRequestListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by Oclemy on 10/11/2016 for ProgrammingWizards Channel and http://www.camposha.com.
 */
public class MySQLClient {

    //SAVE/RETRIEVE URLS
    private static final String DATA_INSERT_URL="http://10.0.2.2/android/Columbia/crud.php";

    //INSTANCE FIELDS
    private final Context c;

    public MySQLClient(Context c) {
        this.c = c;

    }
    /*
    SAVE/INSERT
     */
    public void add(Spacecraft s, final View...inputViews)
    {
        if(s==null)
        {
            Toast.makeText(c, "No Data To Save", Toast.LENGTH_SHORT).show();
        }
        else
        {
            AndroidNetworking.post(DATA_INSERT_URL)
                    .addBodyParameter("action","save")
                    .addBodyParameter("name",s.getName())
                    .addBodyParameter("propellant",s.getPropellant())
                    .addBodyParameter("technologyexists",String.valueOf(s.getTechnologyExists()))
                    .setTag("TAG_ADD")
                    .build()
                    .getAsJSONArray(new JSONArrayRequestListener() {
                        @Override
                        public void onResponse(JSONArray response) {

                            if(response != null)
                                try {
                                    //SHOW RESPONSE FROM SERVER
                                    String responseString = response.get(0).toString();
                                    Toast.makeText(c, "PHP SERVER RESPONSE : " + responseString, Toast.LENGTH_SHORT).show();

                                    if (responseString.equalsIgnoreCase("Success")) {
                                        //RESET VIEWS
                                        EditText nameTxt = (EditText) inputViews[0];
                                        Spinner spPropellant = (Spinner) inputViews[1];

                                        nameTxt.setText("");
                                        spPropellant.setSelection(0);
                                    }else
                                    {
                                        Toast.makeText(c, "PHP WASN'T SUCCESSFUL. ", Toast.LENGTH_SHORT).show();

                                    }


                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    Toast.makeText(c, "GOOD RESPONSE BUT JAVA CAN'T PARSE JSON IT RECEIVED : "+e.getMessage(), Toast.LENGTH_SHORT).show();
                                }

                        }

                        //ERROR
[email protected]
[email protected]rror(ANError anError) {
                            Toast.makeText(c, "UNSUCCESSFUL :  ERROR IS : "+anError.getMessage(), Toast.LENGTH_SHORT).show();
                        }


                    });

        }
    }



}

SECTION 4 : Our Activity

MainActivity class.

Main Responsibility : LAUNCH OUR APP.

  • It extends AppcompatActivity hence is an activity.
  • Activities are the entry point of android applications.This is no exception.
  • It loads our activity layout.
  • It handles all our inputs in this case.
  • Add references to Spinner,EditText and CheckBox.
  • Also add buttons and initialize them.

 

 

package com.tutorials.hp.mysql_datatypes_save;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    //INSTANCE FIELDS
    private TextInputEditText txtName;
    private CheckBox chkTechnologyExists;
    private Spinner spPropellant;
    private Button btnAdd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        //REFERENCE VIEWS
        this.initializeViews();

        populatePropellants();
        //HANDLE EVENTS
        this.handleClickEvents();

    }

    /*
    REFERENCE VIEWS
     */
    private void initializeViews()
    {

        txtName= (TextInputEditText) findViewById(R.id.nameTxt);
        chkTechnologyExists= (CheckBox) findViewById(R.id.techExists);
        spPropellant= (Spinner) findViewById(R.id.sp);

        btnAdd= (Button) findViewById(R.id.addBtn);


    }


    /*
    HANDLE CLICK EVENTS
     */
    private void handleClickEvents()
    {
        //EVENTS : ADD
        btnAdd.setOnClickListener(new View.OnClickListener() {
[email protected]
            public void onClick(View view) {

                //GET VALUES
                String name=txtName.getText().toString();
                String propellant=spPropellant.getSelectedItem().toString();
                Boolean technologyexists=chkTechnologyExists.isChecked();

                //BASIC CLIENT SIDE VALIDATION
                if((name.length()<1 || propellant.length()<1  ))
                {
                    Toast.makeText(MainActivity.this, "Please Enter all Fields", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    //SAVE

                    Spacecraft s=new Spacecraft();
                    s.setName(name);
                    s.setPropellant(propellant);
                    s.setTechnologyExists(technologyexists ? 1 : 0);

                    new MySQLClient(MainActivity.this).add(s,txtName,spPropellant);
                }
            }
        });



    }

    private void populatePropellants()
    {
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item);

        adapter.add("None");
        adapter.add("Chemical Energy");
        adapter.add("Nuclear Energy");
        adapter.add("Laser Beam");
        adapter.add("Anti-Matter");
        adapter.add("Plasma Ions");
        adapter.add("Warp Drive");

        spPropellant.setAdapter(adapter);
        spPropellant.setSelection(0);

    }

}

 

 

 

Rating :

Leave a Reply

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

five × five =

You may also like

6 comments

Tom Van Minnebruggen October 27, 2016 at 7:29 pm

Nice job!!!
Can you pls put the phpcode as well..new on android 😉 THX

Reply
Oclemy October 31, 2016 at 9:10 am

You are welcome.

Reply
Dvl1 November 4, 2016 at 9:50 am

You posted part4 (php code) somewhere? Greetz

Reply
Oclemy November 5, 2016 at 4:17 am

Good.Let me upload a zip version now.

Reply
Tom Van Minnebruggen November 5, 2016 at 7:21 am

Great!!! Big Thanks!

Leave a Comment

12 − eleven =