Building a To Do List Android Mobile App – Part 2

In the first part of the simple android mobile app (toDoList) tutorial series, you covered the basics of setting environment and user interface.

In this second and final part of the tutorial series, we’ll cover API integration for each activity classes.

We’ll start where we left off last tutorial, so open your project from last time, or go through the previous tutorial first. http://intellij.my/2016/08/11/building-a-to-do-list-android-mobile-app-part-1/

Create a new java class. Right click on my.intellij.androidtodolist package > New >Activity > Java Class.

Create a new java class.

Create a new java class.

Name it as App and click Ok.

Create New Class

Create New Class

Then replace with this code in App.java.

package my.intellij.androidtodolist;

public class App {

    public static final String URL_CREATE="http://demo.revivalx.com/todolist-api/create_task.php";
    public static final String URL_GET_ALL = "http://demo.revivalx.com/todolist-api/get_all_tasks.php";
    public static final String URL_GET_DETAIL = "http://demo.revivalx.com/todolist-api/get_task_details.php?taskId=";
    public static final String URL_UPDATE = "http://demo.revivalx.com/todolist-api/update_task.php?taskId=";
    public static final String URL_DELETE = "http://demo.revivalx.com/todolist-api/delete_task.php?taskId=";

    public static final String KEY_ID = "taskId";
    public static final String KEY_NAME = "name";
    public static final String KEY_DESCRIPTION = "description";

    public static final String TAG_JSON_ARRAY="tasks";
    public static final String TAG_JSON_DETAIL="task";
    public static final String TAG_ID = "taskId";
    public static final String TAG_NAME = "name";
    public static final String TAG_DESCRIPTION = "description";

    public static final String ID = "taskId";
}

Create another java class. Right click on my.intellij.androidtodolist package > New >Activity > Java Class name it as RequestHandler. After that replace with this code.

package my.intellij.androidtodolist;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

public class RequestHandler {

    //Method to send httpPostRequest
    //This method is taking two arguments
    //First argument is the URL of the script to which we will send the request
    //Other is an HashMap with name value pairs containing the data to be send with the request
    public String sendPostRequest(String requestURL,
                                  HashMap<String, String> postDataParams) {
        URL url;

        //StringBuilder object to store the message retrieved from the server
        StringBuilder sb = new StringBuilder();
        try {
            //Initializing Url
            url = new URL(requestURL);

            //Creating an httmlurl connection
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            //Configuring connection properties
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            //Creating an output stream
            OutputStream os = conn.getOutputStream();

            //Writing parameters to the request
            //We are using a method getPostDataString which is defined below
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            int responseCode = conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {

                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                sb = new StringBuilder();
                String response;
                //Reading server response
                while ((response = br.readLine()) != null){
                    sb.append(response);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public String sendGetRequest(String requestURL){
        StringBuilder sb =new StringBuilder();
        try {
            URL url = new URL(requestURL);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String s;
            while((s=bufferedReader.readLine())!=null){
                sb.append(s+"\n");
            }
        }catch(Exception e){
        }
        return sb.toString();
    }

    public String sendGetRequestParam(String requestURL, String id){
        StringBuilder sb =new StringBuilder();
        try {
            URL url = new URL(requestURL+id);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String s;
            while((s=bufferedReader.readLine())!=null){
                sb.append(s+"\n");
            }
        }catch(Exception e){
        }
        return sb.toString();
    }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String, String>entry : params.entrySet()) {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }
}

Open activity_list.xml in app > layout >activity_list.xml. Update activity_list.xml with this one.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="my.intellij.androidtodolist.ListActivity">

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Create Task"
        android:id="@+id/btnCreate"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lv_task"
        android:layout_below="@+id/btnCreate"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

ListActivity.java

package my.intellij.androidtodolist;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

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

import java.util.ArrayList;
import java.util.HashMap;

public class ListActivity extends AppCompatActivity implements ListView.OnItemClickListener {

    private ListView listView;

    private String JSON_STRING;

    private Button buttonAdd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        listView = (ListView) findViewById(R.id.lv_task);
        listView.setOnItemClickListener(this);
        getJSON();

        buttonAdd = (Button) findViewById(R.id.btnCreate);
        buttonAdd.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {

                Intent createActivity = new Intent(getApplicationContext(), CreateActivity.class);
                startActivity(createActivity);

            }
        });
    }


    private void showTask(){
        JSONObject jsonObject = null;
        ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
        try {
            jsonObject = new JSONObject(JSON_STRING);
            JSONArray result = jsonObject.getJSONArray(App.TAG_JSON_ARRAY);

            for(int i = 0; i<result.length(); i++){
                JSONObject jo = result.getJSONObject(i);
                String id = jo.getString(App.TAG_ID);
                String name = jo.getString(App.TAG_NAME);

                HashMap<String,String> tasks = new HashMap<>();
                tasks.put(App.TAG_ID,id);
                tasks.put(App.TAG_NAME,name);
                list.add(tasks);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        ListAdapter adapter = new SimpleAdapter(
                ListActivity.this, list, R.layout.list_item,
                new String[]{App.TAG_NAME},
                new int[]{R.id.name});

        listView.setAdapter(adapter);
    }

    private void getJSON(){
        class GetJSON extends AsyncTask<Void,Void,String> {

            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(ListActivity.this,"Fetching Data","Wait...",false,false);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                JSON_STRING = s;
                showTask();
            }

            @Override
            protected String doInBackground(Void... params) {
                RequestHandler rh = new RequestHandler();
                String s = rh.sendGetRequest(App.URL_GET_ALL);
                return s;
            }
        }
        GetJSON gj = new GetJSON();
        gj.execute();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this, UpdateActivity.class);
        HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);
        String taskId = map.get(App.TAG_ID).toString();
        intent.putExtra(App.ID,taskId);
        startActivity(intent);
    }
}

CreateActivity.java

package my.intellij.androidtodolist;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.HashMap;

public class CreateActivity extends AppCompatActivity implements View.OnClickListener{

    //Defining views
    private EditText editTextName;
    private EditText editTextDesription;

    private Button buttonAdd;
    private Button buttonView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create);

        //Initializing views
        editTextName = (EditText) findViewById(R.id.txtName);
        editTextDesription = (EditText) findViewById(R.id.txtDescription);

        buttonAdd = (Button) findViewById(R.id.btnCreate);
        buttonView = (Button) findViewById(R.id.btnBack);

        //Setting listeners to button
        buttonAdd.setOnClickListener(this);
        buttonView.setOnClickListener(this);
    }


    //Adding a task
    private void addTask(){

        final String name = editTextName.getText().toString().trim();
        final String description = editTextDesription.getText().toString().trim();

        class AddTask extends AsyncTask<Void,Void,String> {

            ProgressDialog loading;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(CreateActivity.this,"Adding...","Wait...",false,false);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                Toast.makeText(CreateActivity.this,s,Toast.LENGTH_LONG).show();
            }

            @Override
            protected String doInBackground(Void... v) {
                HashMap<String,String> params = new HashMap<>();
                params.put(App.KEY_NAME,name);
                params.put(App.KEY_DESCRIPTION,description);

                RequestHandler rh = new RequestHandler();
                String res = rh.sendPostRequest(App.URL_CREATE, params);
                return res;
            }
        }

        AddTask ae = new AddTask();
        ae.execute();
    }

    @Override
    public void onClick(View v) {
        if(v == buttonAdd){
            addTask();
            startActivity(new Intent(CreateActivity.this,ListActivity.class));
        }

        if(v == buttonView){
            startActivity(new Intent(this,ListActivity.class));
        }
    }
}

Open activity_update.xml in app > layout >activity_update.xml. Update activity_update.xml with this one.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="my.intellij.androidtodolist.UpdateActivity">

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtName"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:hint="Name"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtDescription"
        android:layout_below="@+id/txtName"
        android:layout_centerHorizontal="true"
        android:hint="Description"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Update Task"
        android:id="@+id/btnUpdate"
        android:layout_below="@+id/txtDescription"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Delete Task"
        android:id="@+id/btnDelete"
        android:layout_below="@+id/btnUpdate"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Back"
        android:id="@+id/btnBack"
        android:layout_below="@+id/btnDelete"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

UpdateActivity.java

package my.intellij.androidtodolist;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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

import java.util.HashMap;

public class UpdateActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText editTextName;
    private EditText editTextDescription;

    private Button buttonUpdate;
    private Button buttonDelete;
    private Button buttonView;

    private String id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update);

        Intent intent = getIntent();

        id = getIntent().getExtras().getString(App.ID);

        editTextName = (EditText) findViewById(R.id.txtName);
        editTextDescription = (EditText) findViewById(R.id.txtDescription);

        buttonUpdate = (Button) findViewById(R.id.btnUpdate);
        buttonDelete = (Button) findViewById(R.id.btnDelete);
        buttonView = (Button) findViewById(R.id.btnBack);

        buttonUpdate.setOnClickListener(this);
        buttonDelete.setOnClickListener(this);
        buttonView.setOnClickListener(this);

        getTask();
    }

    private void getTask(){
        class GetTask extends AsyncTask<Void,Void,String> {
            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(UpdateActivity.this,"Fetching...","Wait...",false,false);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                showTask(s);
            }

            @Override
            protected String doInBackground(Void... params) {
                RequestHandler rh = new RequestHandler();
                String s = rh.sendGetRequestParam(App.URL_GET_DETAIL,id);
                return s;
            }
        }
        GetTask gt = new GetTask();
        gt.execute();
    }

    private void showTask(String json){
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONArray result = jsonObject.getJSONArray(App.TAG_JSON_DETAIL);
            JSONObject c = result.getJSONObject(0);
            String name = c.getString(App.TAG_NAME);
            String description = c.getString(App.TAG_DESCRIPTION);

            editTextName.setText(name);
            editTextDescription.setText(description);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private void updateTask(){
        final String name = editTextName.getText().toString().trim();
        final String description = editTextDescription.getText().toString().trim();

        class UpdateTask extends AsyncTask<Void,Void,String>{
            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(UpdateActivity.this,"Updating...","Wait...",false,false);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                Toast.makeText(UpdateActivity.this,s,Toast.LENGTH_LONG).show();
            }

            @Override
            protected String doInBackground(Void... params) {
                HashMap<String,String> hashMap = new HashMap<>();
                hashMap.put(App.KEY_ID,id);
                hashMap.put(App.KEY_NAME,name);
                hashMap.put(App.KEY_DESCRIPTION,description);

                RequestHandler rh = new RequestHandler();

                String s = rh.sendPostRequest(App.URL_UPDATE,hashMap);

                return s;
            }
        }

        UpdateTask ut = new UpdateTask();
        ut.execute();
    }

    private void deleteTask(){
        class DeleteTask extends AsyncTask<Void,Void,String> {
            ProgressDialog loading;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(UpdateActivity.this, "Updating...", "Wait...", false, false);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                Toast.makeText(UpdateActivity.this, s, Toast.LENGTH_LONG).show();
            }

            @Override
            protected String doInBackground(Void... params) {
                RequestHandler rh = new RequestHandler();
                String s = rh.sendGetRequestParam(App.URL_DELETE, id);
                return s;
            }
        }

        DeleteTask dt = new DeleteTask();
        dt.execute();
    }

    private void confirmDeleteTask(){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("Are you sure you want to delete this task?");

        alertDialogBuilder.setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        deleteTask();
                        startActivity(new Intent(UpdateActivity.this,ListActivity.class));
                    }
                });

        alertDialogBuilder.setNegativeButton("No",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {

                    }
                });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    @Override
    public void onClick(View v) {
        if(v == buttonUpdate){
            updateTask();
        }

        if(v == buttonDelete){
            confirmDeleteTask();
        }

        if(v == buttonView){
            startActivity(new Intent(this,ListActivity.class));
        }
    }
}

Now try running your application.

One thought on “Building a To Do List Android Mobile App – Part 2

Leave a Reply

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