Android MySQL : ListView CheckBoxes – INSERT,SELECT,SHOW

IDG Contributor Network: The top 5 Java 8 features for developers
Java MySQL Database Template
Android RSS : ListView – Downlaod,Parse,Show Headlines With Images and Text

Android MySQL : ListView CheckBoxes – INSERT,SELECT,SHOW







  • We want to see how to work with Android PHP MySQL and Boolean values and strings.
  • First we want to insert data to MySQL database.
  • The data shall be from a material edittext,a spinner and a checkbox.
  • The user types his favorite spacecraft name in the edittext.Then selects the spacecraft's propellant from a spinner.
  • He then selects if the technology exists yet or not in the checkbox.
  • We shall actually be mapping integers to boolean and vice versa since MySQL doesn't have a native boolean data type.
  • Our adapterview is ListView.It has checkboxes to hold boolean values from MySQL database.

Look the full source code reference is available above.Simply download and extract.The full PHP code is also available.Place it in your server's root dirctory and modify according to your database name,passowrd etc.

 

Android MySQL CheckBox Project Structure

Android MySQL CheckBox Project Structure

 

First we have a data object POJO class as below.

 

package com.tutorials.hp.mysqllistviewbool.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;
    }
}

 

Table Structure

Table Structure

 

Our most important class is our MySQL Client class.It is responsible fro bothh connecting,inserting and retrieving data and handling errors appropriately.We are using the easy to use yet efficient Android Networking Library.

 

package com.tutorials.hp.mysqllistviewbool.mMySQL;
import android.content.Context;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
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.mysqllistviewbool.mAdapter.ListViewAdapter;
import com.tutorials.hp.mysqllistviewbool.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 ListViewAdapter 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 ListView lv)
    {
        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 ListViewAdapter(c,spacecrafts);
                            lv.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();
                    }
                });
    }
}

 

 

We also have our ListView adapter to map our dataset to the adapterview.

package com.tutorials.hp.mysqllistviewbool.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.mysqllistviewbool.R;
import com.tutorials.hp.mysqllistviewbool.mModel.Spacecraft;
import java.util.ArrayList;
/**
 * Created by Oclemy on 10/14/2016 for ProgrammingWizards Channel and http://www.camposha.com.
 */
public class ListViewAdapter extends BaseAdapter {
    Context c;
    ArrayList<Spacecraft> spacecrafts;
    public ListViewAdapter(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;
    }
}

 

Android MySQL Boolean ListView CheckBoxes

Android MySQL Boolean ListView CheckBoxes

 

Hey,given that the source is above,you can download it and use it.Moreover below is our YouTube video step by step expalantion.Make sure you guys subscribe over there.

 

Android PHP MySQL CRUD Ep.04 - ListView INSERT,SELECT - From CheckBox,Spinner,EditText

 

 



    Leave a Reply

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

    fifteen + 16 =

    COMMENTS