Home Android MySQL : Spinner – INSERT,SELECT,SHOW

Android MySQL : Spinner – INSERT,SELECT,SHOW

Android MySQL : Spinner – INSERT,SELECT,SHOW


Language :
Platform :
Type :
Owner :
Main Category :
Sub Category :
License :
Price :


  • Lets see how to perform basic data entry and retrieval into MySQL database from our android app.
  • First we insert multi-column data to MySQL from android.
  • Then we retrieve this data and bind it to our spinner component.
  • We are using Android Networking Library to make our network calls.
  • It shall be returning us JSON responses in form of JSON,hence we can easily parse this data bind to spinner.
  • All network calls happen in the background thread as the library abstracts these for us.

Look,the full source code is available for download above.We have included the PHP code we used.Modfiy things like database name and table name of course and save the PHP in your server’s root directory.We shall then need the url to that PHP code as you shall see in our MySQL client class.

Moreover,if you are stuck,check our video tutorial below.Its detailed and step by step everything.

Lets see our data object,our POJO class.

 

package com.tutorials.hp.spinnermysql.mModel;

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

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

    /*
    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 String getDestination() {
        return destination;
    }

    public void setDestination(String destination) {
        this.destination = destination;
    }

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

 

 

Then we have our most important class,our MySQL Client class.Its where we make calls to our server and perform CRUD activities.Take note of the URLs pointing us to PHP code.

 

package com.tutorials.hp.spinnermysql.mMySQL;

import android.content.Context;
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 com.tutorials.hp.spinnermysql.mModel.Spacecraft;

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

import java.util.ArrayList;

/**
 * Created by Oclemy on 9/30/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/GalacticCity/crud.php";
    private static final String DATA_RETRIEVE_URL="http://10.0.2.2/android/GalacticCity/index.php";

    //INSTANCE FIELDS
    private final Context c;
    private ArrayAdapter<Spacecraft> adapter ;

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

    }
    /*
    SAVE/INSERT
     */
    public void add(Spacecraft s, final EditText...editTexts)
    {
        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("destination",s.getDestination())
                    .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")) {
                                        //CLEAR EDITXTS
                                        EditText nameTxt = editTexts[0];
                                        EditText propTxt = editTexts[1];
                                        EditText destTxt = editTexts[2];

                                        nameTxt.setText("");
                                        propTxt.setText("");
                                        destTxt.setText("");
                                    }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
                        @Override
                        public void onError(ANError anError) {
                            Toast.makeText(c, "UNSUCCESSFUL :  ERROR IS : "+anError.getMessage(), Toast.LENGTH_SHORT).show();
                        }


                    });

        }
    }

    /*
    RETRIEVE/SELECT/REFRESH
     */
    public void retrieve(final Spinner sp)
    {
        final ArrayList<Spacecraft> spacecrafts = new ArrayList<>();

        AndroidNetworking.get(DATA_RETRIEVE_URL)
                .setPriority(Priority.HIGH)
                .build()
                .getAsJSONArray(new JSONArrayRequestListener() {
                    @Override
                    public void onResponse(JSONArray response) {
                        JSONObject jo;
                        Spacecraft s;
                        try
                        {
                            for(int i=0;i<response.length();i++)
                            {
                                jo=response.getJSONObject(i);

                                int id=jo.getInt("id");
                                String name=jo.getString("name");
                                String propellant=jo.getString("propellant");
                                String destination=jo.getString("destination");

                                s=new Spacecraft();
                                s.setId(id);
                                s.setName(name);
                                s.setPropellant(propellant);
                                s.setDestination(destination);

                                spacecrafts.add(s);
                            }

                            //SET TO SPINNER
                            adapter =new ArrayAdapter(c,android.R.layout.simple_list_item_1,spacecrafts);
                            sp.setAdapter(adapter);

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

                        }

                    }

                    //ERROR
                    @Override
                    public void onError(ANError anError) {
                        anError.printStackTrace();
                        Toast.makeText(c, "UNSUCCESSFUL :  ERROR IS : "+anError.getMessage(), Toast.LENGTH_LONG).show();

                    }


                });

    }



}

 

Finally our MainActivity is here :

 

package com.tutorials.hp.spinnermysql;

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

import com.tutorials.hp.spinnermysql.mModel.Spacecraft;
import com.tutorials.hp.spinnermysql.mMySQL.MySQLClient;

public class MainActivity extends AppCompatActivity {

    //INSTANCE FIELDS
    private TextInputEditText txtName,txtPropellant,txtDestination;
    private Spinner sp;
    private Button btnAdd,btnRetrieve;

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

        //REFERENCE VIEWS
        this.initializeViews();

        //HANDLE EVENTS
        this.handleClickEvents();

    }

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

        txtName= (TextInputEditText) findViewById(R.id.nameTxt);
        txtPropellant= (TextInputEditText) findViewById(R.id.propellantTxt);
        txtDestination= (TextInputEditText) findViewById(R.id.destinationTxt);

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

        sp= (Spinner) findViewById(R.id.sp);

    }

    /*
    HANDLE CLICK EVENTS
     */
    private void handleClickEvents()
    {
        //EVENTS : ADD
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //GET VALUES
                String name=txtName.getText().toString();
                String propellant=txtPropellant.getText().toString();
                String destination=txtDestination.getText().toString();

                //BASIC CLIENT SIDE VALIDATION
                if((name.length()<1 || propellant.length()<1 || destination.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.setDestination(destination);

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

        //EVENTS : RETRIEVE
        btnRetrieve.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new MySQLClient(MainActivity.this).retrieve(sp);

            }
        });

    }



}

 

Hey,everything is in source code reference that is well commented and easy to understand and can be downloaded at the top of this page.Moreover,watch our video tutorial for more explanations.And yes,subscribe to the channel.

 

 

Leave a Comment