Android MySQL : GridView CheckBox – INSERT,SELECT,SHOW

Android RSS : GridView- Download,Parse,Show Headlines With Images and Text
Android RSS : GridView- Downlaod,Parse,Show Headlines With Images and Text
Java MySQL Database Template

Android MySQL : GridView CheckBox – INSERT,SELECT,SHOW







  • Look the aim is to see how to work with Boolean values with MySQL database.
  • We want to insert data to MySQL database first.
  • We are inserting from an edittext,from a spinner as well as from a checkbox.
  • The user checks/unchecks the checkbox if the technology for our fictional spacecraft exists.
  • He selects the propellant from a spinner and enters the spacecraft name in a material checkbox.
  • We then select our data from database.It is strings and booleans.
  • The gridview is custom to hold textviews and checkboxes.
  • In actuality,MySQL doesn't natively support boolean data types.So we shall use a simple integer to represent boolean values to be bound to checkbox.
  • 1 to represent true and 0 to false.The integer is nullable.

 

 

We are using Android Networking Library by Ahmed Shekhar to perform our network calls.These shall happen in the background thread and return us responses in JSON format.The library is fast and easy to use.

Android MySQL Boolean GridView Project Structure

Android MySQL Boolean GridView Project Structure

First take note that the full source code reference is above,download it including the PHP we used.

Here's our MySQL client class,our most important class.

 

package com.tutorials.hp.mysqlgridviewbool.mMySQL;
import android.content.Context;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
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.mysqlgridviewbool.mAdapter.GridViewAdapter;
import com.tutorials.hp.mysqlgridviewbool.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/Aristotle/crud.php";
    private static final String DATA_RETRIEVE_URL="http://10.0.2.2/android/Aristotle/index.php";
    //INSTANCE FIELDS
    private final Context c;
    private GridViewAdapter adapter ;
    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
                        @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 GridView gv)
    {
        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 techExists=jo.getString("technologyexists");
                                s=new Spacecraft();
                                s.setId(id);
                                s.setName(name);
                                s.setPropellant(propellant);
                                s.setTechnologyExists(techExists.equalsIgnoreCase("1") ? 1 : 0);
                                spacecrafts.add(s);
                            }
                            //SET TO SPINNER
                            adapter =new GridViewAdapter(c,spacecrafts);
                            gv.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();
                    }
                });
    }
}

 

 

MySQL Table Structure

MySQL Table Structure

Here's our GridView adapter class.The base class we are deriving from is baseadapter of course.We map our integers to boolean.

 

package com.tutorials.hp.mysqlgridviewbool.mAdapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import com.tutorials.hp.mysqlgridviewbool.R;
import com.tutorials.hp.mysqlgridviewbool.mModel.Spacecraft;
import java.util.ArrayList;
/**
 * Created by Oclemy on 10/14/2016 for ProgrammingWizards Channel and http://www.camposha.com.
 */
public class GridViewAdapter extends BaseAdapter {
    Context c;
    ArrayList<Spacecraft> spacecrafts;
    public GridViewAdapter(Context c, ArrayList<Spacecraft> spacecrafts) {
        this.c = c;
        this.spacecrafts = spacecrafts;
    }
    @Override
    public int getCount() {
        return spacecrafts.size();
    }
    @Override
    public Object getItem(int i) {
        return spacecrafts.get(i);
    }
    @Override
    public long getItemId(int i) {
        return i;
    }
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if(view==null)
        {
            view= LayoutInflater.from(c).inflate(R.layout.model,viewGroup,false);
        }
        TextView txtName = (TextView) view.findViewById(R.id.nameTxt);
        TextView txtPropellant = (TextView) view.findViewById(R.id.txtPropellant);
        CheckBox chkTechExists = (CheckBox) view.findViewById(R.id.chkTechExists);
        final Spacecraft s= (Spacecraft) this.getItem(i);
        txtName.setText(s.getName());
        txtPropellant.setText(s.getPropellant());
        chkTechExists.setChecked( s.getTechnologyExists()==1);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(c, s.getName(), Toast.LENGTH_SHORT).show();
            }
        });
        return view;
    }
}

 

We have data object know as Spacecraft.

 

package com.tutorials.hp.mysqlgridviewbool.mModel;
/**
 * 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;
    }
}

 

Android MySQL Boolean Checked GridView

Android MySQL Boolean Checked GridView

Hey,the full source code is above for download.It contains everything including the PHP code.You cal also watch the video below for step by step explanations.

Android PHP MySQL CRUD Ep.03 - GridView INSERT,SELECT - From CheckBox,Spinner,EditText

 

 

 



    Leave a Reply

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

    seventeen − 15 =

    COMMENTS