com.app.swaedes.swaedes.OtherSitePage.java Source code

Java tutorial

Introduction

Here is the source code for com.app.swaedes.swaedes.OtherSitePage.java

Source

/*  Swaedes version 1.0, Copyright (C) 2016 Franz CERIL, David COUDRIN,
Sbastien HUTINET, Andra LARPENT, Florian LEFEBVRE.
    
This file is part of Swaedes. Swaedes is an app destined to monitor
mosquitoes proliferation in dense urban areas.
    
Swaedes is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
    
Swaedes is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
    
You should have received a copy of the GNU General Public License
along with Swaedes.  If not, see <http://www.gnu.org/licenses/>.
*/

package com.app.swaedes.swaedes;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

import org.apache.commons.io.FileUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by david on 27/04/16
 */
public class OtherSitePage extends Activity implements View.OnClickListener {

    private static final int MEDIA_TYPE_AUDIO = 1;

    //Feature information
    private String encoded_string_image, image_name, encoded_string_audio = "", name, comment, address, keyword,
            user, audio_path, audio_name;
    private int nb_boxes, nb_clothes;
    private boolean water, larvae, bool_audio = false;
    private double latitude, longitude;

    //views (widgets)
    private Spinner spinner_keyword;
    private EditText et_site_name, et_comment, et_address, et_nb_boxes, et_nb_clothes;
    private CheckBox cb_water, cb_larvae;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other_comment_page);

        //Fetching user email from shared preferences
        SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
        user = sharedPreferences.getString(Config.SHARED_PREF_EMAIL, "Not Available");

        //Getting information from the last activity
        image_name = getIntent().getStringExtra("image_name");
        latitude = getIntent().getDoubleExtra("latitude", 0.00);
        longitude = getIntent().getDoubleExtra("longitude", 0.00);

        //getting all the views (widgets)
        et_site_name = (EditText) findViewById(R.id.editText_name_other);
        et_comment = (EditText) findViewById(R.id.editText_comment_other2);
        et_address = (EditText) findViewById(R.id.editText_address2);
        spinner_keyword = (Spinner) findViewById(R.id.spinner_other);
        et_nb_boxes = (EditText) findViewById(R.id.boxes_nb2);
        et_nb_clothes = (EditText) findViewById(R.id.clothes_nb2);
        cb_water = (CheckBox) findViewById(R.id.checkBox_water2);
        cb_larvae = (CheckBox) findViewById(R.id.checkBox_larvae2);

        Button record = (Button) findViewById(R.id.button_record2);
        Button send = (Button) findViewById(R.id.button_send2);

        record.setOnClickListener(this);
        send.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.button_send2) {

            //getting values from the views (filled by the user)
            String check_boxes = et_nb_boxes.getText().toString();
            String check_clothes = et_nb_clothes.getText().toString();
            name = et_site_name.getText().toString();
            comment = et_comment.getText().toString();
            address = et_address.getText().toString();

            //check if no information is missing
            if (check_boxes.equals("") || check_clothes.equals("") || name.equals("") || comment.equals("")
                    || address.equals("")) {

                Toast.makeText(OtherSitePage.this, "Please fill all values", Toast.LENGTH_SHORT).show();
            } else {

                /** casting number of boxes and clothes as an integer
                 * and getting the rest of the values
                 */
                keyword = spinner_keyword.getSelectedItem().toString();
                nb_boxes = Integer.parseInt(check_boxes);
                nb_clothes = Integer.parseInt(check_clothes);
                water = cb_water.isChecked();
                larvae = cb_larvae.isChecked();

                new ImageAndAudioEncoded().execute();
            }
        }

        else if (view.getId() == R.id.button_record2) {
            //launch a new activity to record an audio comment
            Intent intent = new Intent(this, AudioComment.class);

            /** Getting the audio path (the beginning of the String starts with file://
             * so it must be replaced by "" in order to be retrieved
             */
            audio_path = getOutputAudioFileUri(MEDIA_TYPE_AUDIO).toString().replace("file://", "");
            intent.putExtra("audio_uri", audio_path);

            //set a boolean to true when the user launches the activity
            bool_audio = true;

            startActivity(intent);
        }
    }

    //Get the audio record Uri
    public Uri getOutputAudioFileUri(int type) {
        return Uri.fromFile(getOutputAudioFile(type));
    }

    //Creates a file where the audio will be stored
    public File getOutputAudioFile(int type) {

        //Create folder if it doesn't exist
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC),
                Config.APP_DIRECTORY_NAME);

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(Config.APP_DIRECTORY_NAME,
                        "Oops! Failed to create" + Config.APP_DIRECTORY_NAME + "directory");
                return null;
            }
        }

        //Audio title will be a timestamp to be unique
        audio_name = "REC_" + Config.timeStamp() + ".3gp";
        File audioFile;
        if (type == MEDIA_TYPE_AUDIO) {
            audioFile = new File(mediaStorageDir + File.separator + audio_name);
        } else {
            return null;
        }
        return audioFile;
    }

    private void makeRequest() {

        //Creating JSON Object where data will be stored
        JSONObject feature = new JSONObject();
        JSONObject site = new JSONObject();

        try {

            //if the user made an audio comment, it will be put with the rest of the data
            if (bool_audio) {
                feature.put(Config.KEY_AUDIO, encoded_string_audio);
                feature.put(Config.KEY_AUDIO_NAME, audio_name);
            }

            //Storing data in JSON Object
            feature.put(Config.KEY_WATER, water);
            feature.put(Config.KEY_LARVAE, larvae);
            feature.put(Config.KEY_COMMENT, comment);
            feature.put(Config.KEY_CLOTHES, nb_clothes);
            feature.put(Config.KEY_BOXES, nb_boxes);
            feature.put(Config.KEY_LATITUDE, latitude);
            feature.put(Config.KEY_LONGITUDE, longitude);
            feature.put(Config.KEY_IMAGE, encoded_string_image);
            feature.put(Config.KEY_USER, user);
            feature.put(Config.KEY_IMAGE_NAME, image_name);

            site.put(Config.KEY_ADDRESS, address);
            site.put(Config.KEY_SITE_NAME, name);
            site.put(Config.KEY_BOOL_CONSTRUCTION_SITE, true);
            site.put(Config.KEY_SITE_TYPE, keyword);

            feature.putOpt(Config.KEY_SITE, site);

            Log.d("Swaedes", feature.toString());

            //Creating a new JSON Object request to be sent
            JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, Config.UPLOAD_URL, feature,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            //if the response is success, launches the main menu
                            if (response.toString().contains(Config.UPLOAD_SUCCESS)) {
                                Intent intent = new Intent(OtherSitePage.this, MainMenuPage.class);
                                startActivity(intent);
                            } else {
                                Toast.makeText(OtherSitePage.this, "Error, try again", Toast.LENGTH_LONG).show();
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    }) {
                //setting the headers of the request
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<>();
                    headers.put("Content-Type", "application/json; charset=utf-8");
                    return headers;
                }
            };

            //Getting the request queue of the app, adding the request to it
            Swaedes swaedes = (Swaedes) getApplication();
            RequestQueue mVolleyRequestQueue = swaedes.getVolleyRequestQueue();
            mVolleyRequestQueue.add(request);
        } catch (JSONException e) {
            Log.e("Swaedes", "Could not parse malformed JSON: \"" + feature + "\"");
        }
    }

    private class ImageAndAudioEncoded extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... voids) {

            //Check if the an audio comment was done and encode it in Base64 String
            if (bool_audio) {
                try {
                    File audio = new File(audio_path);
                    byte[] bytes = FileUtils.readFileToByteArray(audio);
                    encoded_string_audio = Base64.encodeToString(bytes, Base64.NO_WRAP);

                } catch (IOException e) {
                    Log.e("Swaedes", "Could not make malformed string: \"" + encoded_string_audio + "\"");
                }
            }

            //Encode image in Base64 String
            String image_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                    + Config.APP_DIRECTORY_NAME + File.separator + image_name;
            Bitmap bitmap = BitmapFactory.decodeFile(image_path);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            byte[] array = stream.toByteArray();
            encoded_string_image = Base64.encodeToString(array, Base64.DEFAULT);
            return null;
        }

        //After the encoding, data will be sent in HTTP request
        @Override
        protected void onPostExecute(Void aVoid) {
            makeRequest();
        }
    }

}