org.maikelwever.droidpile.SendMailActivity.java Source code

Java tutorial

Introduction

Here is the source code for org.maikelwever.droidpile.SendMailActivity.java

Source

/*
 * This file is part of Droidpile: a Mailpile client for Android.
 *
 * You should have recieved a copy of the LICENSE file along with Droidpile.
 * If not: see <https://github.com/maikelwever/droidpile/blob/master/LICENSE>
 */
package org.maikelwever.droidpile;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import org.apache.http.message.BasicNameValuePair;
import org.maikelwever.droidpile.backend.ApiConnecter;
import org.maikelwever.droidpile.backend.ApiConnecterFactory;
import org.maikelwever.droidpile.helpers.ContactsCompletionView;
import org.maikelwever.droidpile.helpers.ContextToSettings;
import org.maikelwever.droidpile.models.AutocompleteContact;
import org.maikelwever.droidpile.models.ParsedMailpileMessage;

import java.util.ArrayList;
import java.util.List;

public class SendMailActivity extends SherlockActivity {
    ContactsCompletionView addressView;
    ContactsCompletionView ccView;
    //ContactsCompletionView bccView;

    Context context;
    //AutocompleteContact[] contacts;
    ArrayList<AutocompleteContact> contacts;
    ArrayAdapter<AutocompleteContact> adapter;
    ProgressDialog progressDialog = null;

    private String draftMessageId = "";

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

        this.context = getApplicationContext();

        addressView = (ContactsCompletionView) findViewById(R.id.sendViewAdresses);
        ccView = (ContactsCompletionView) findViewById(R.id.sendViewCC);
        //bccView = (ContactsCompletionView) findViewById(R.id.sendViewBCC);
        //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle(R.string.title_activity_send_mail);

        String savedMid;
        try {
            Bundle bundle = getIntent().getExtras();
            savedMid = bundle.getString("draft-mid");
        } catch (Exception e) {
            savedMid = "";
        }

        if (!savedMid.isEmpty()) {
            progressDialog = ProgressDialog.show(SendMailActivity.this, "",
                    getString(R.string.download_please_wait), true);
            new FetchDraft().execute(savedMid);
        }

        if (contacts == null) {
            new FetchContactsTask().execute("not needed?");
        }
    }

    /*
    @Override
    public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Do you want to save this draft?")
            .setTitle("Unsaved changes")
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    NavUtils.navigateUpFromSameTask(SendMailActivity.this);
                }
            })
            .setPositiveButton("Yes please!", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    new LeavingSaveDraftTask().execute();
                }
            });
    AlertDialog dialog = builder.create();
    dialog.show();
    }
    */

    public String getSubject() {
        TextView v = (TextView) findViewById(R.id.sendViewSubject);
        return v.getText().toString();
    }

    public String getBody() {
        TextView v = (TextView) findViewById(R.id.sendViewMessage);
        return v.getText().toString();
    }

    public String combineAddresses(String viewType) {
        ContactsCompletionView v;
        if (viewType.equals("to")) {
            v = (ContactsCompletionView) findViewById(R.id.sendViewAdresses);
        } else if (viewType.equals("cc")) {
            v = (ContactsCompletionView) findViewById(R.id.sendViewCC);
            //        } else if (viewType.equals("bcc")) {
            //            v = (ContactsCompletionView) findViewById(R.id.sendViewBCC);
        } else {
            return "";
        }

        List<Object> l = v.getObjects();
        String s = "";
        for (Object o : l) {
            AutocompleteContact c = (AutocompleteContact) o;
            s += c.toString() + ", ";
        }
        if (s.length() > 2) {
            s = s.substring(0, s.length() - 2);
        }
        return s;
    }

    public class FetchContactsTask extends AsyncTask<String, Integer, ArrayList<AutocompleteContact>> {
        @Override
        protected ArrayList<AutocompleteContact> doInBackground(String... params) {
            return getContacts();
        }

        @Override
        protected void onPostExecute(ArrayList<AutocompleteContact> contacts) {
            setAdapters(contacts);
        }
    }

    public ArrayList<AutocompleteContact> getContacts() {
        ArrayList<AutocompleteContact> alContacts = new ArrayList<AutocompleteContact>();
        ContentResolver contResv = getApplication().getContentResolver();
        Cursor cursor = contResv.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                String name = cursor
                        .getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

                AutocompleteContact contact = new AutocompleteContact(id, name);

                Cursor emails = contResv.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contact.id, null, null);
                while (emails.moveToNext()) {
                    contact.addEmail(
                            emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)));
                    break;
                }
                emails.close();

                alContacts.add(contact);

            } while (cursor.moveToNext());
        }

        cursor.close();
        return alContacts;
    }

    public void setAdapters(ArrayList<AutocompleteContact> contacts) {
        this.contacts = contacts;
        adapter = new ArrayAdapter<AutocompleteContact>(this, android.R.layout.simple_list_item_1, contacts);

        addressView.setAdapter(adapter);
        ccView.setAdapter(adapter);
        //bccView.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getSupportMenuInflater().inflate(R.menu.send_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_send) {
            sendEmail();
            return true;
        } else if (id == R.id.action_save) {
            saveDraft();
            return true;
        } else if (id == android.R.id.home) {
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void sendEmail() {
        if (draftMessageId.isEmpty()) {
            final String baseUrl = ContextToSettings.contextToApiSettings(getApplicationContext());
            new CreateDraft().execute(baseUrl, "send");
        } else {
            realSendEmail();
        }
    }

    public void realSendEmail() {
        final String baseUrl = ContextToSettings.contextToApiSettings(getApplicationContext());
        new SendMessage().execute(baseUrl, combineAddresses("to"), combineAddresses("cc"), getSubject(), getBody());
    }

    public void saveDraft() {
        if (draftMessageId.isEmpty()) {
            final String baseUrl = ContextToSettings.contextToApiSettings(getApplicationContext());
            new CreateDraft().execute(baseUrl, "save");
        } else {
            realSaveDraft();
        }
    }

    public void realSaveDraft() {
        final String baseUrl = ContextToSettings.contextToApiSettings(getApplicationContext());
        new SaveDraft().execute(baseUrl, combineAddresses("to"), combineAddresses("cc"), getSubject(), getBody());
    }

    private class CreateDraft extends AsyncTask<String, Integer, BasicNameValuePair> {
        @Override
        protected BasicNameValuePair doInBackground(String... params) {
            String json = "";
            try {
                ApiConnecter api = ApiConnecterFactory.getApiConnecter(getApplicationContext());
                String response = api.createDraft();
                return new BasicNameValuePair(params[1], response);

            } catch (Exception e) {
                e.printStackTrace();
                Log.d("droidpile", json);
                return new BasicNameValuePair(params[1], "");
            }
        }

        @Override
        protected void onPostExecute(BasicNameValuePair result) {
            if (!result.getValue().isEmpty()) {
                if (result.getName().equals("save")) {
                    draftMessageId = result.getValue();
                    realSaveDraft();
                } else if (result.getName().equals("send")) {
                    draftMessageId = result.getValue();
                    realSendEmail();
                }
            } else {
                Toast.makeText(getApplicationContext(), "Failed to " + result.getName() + " message.",
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    private class SaveDraft extends AsyncTask<String, Integer, Boolean> {
        @Override
        protected Boolean doInBackground(String... params) {
            ApiConnecter api = ApiConnecterFactory.getApiConnecter(getApplicationContext());
            return api.saveDraft(draftMessageId, params[1], params[2], params[3], params[4]);
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                Toast.makeText(getApplicationContext(), "Draft was saved on remote.", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "Error saving draft", Toast.LENGTH_LONG).show();
            }
        }
    }

    private class LeavingSaveDraftTask extends SaveDraft {
        @Override
        protected void onPostExecute(Boolean result) {
            NavUtils.navigateUpFromSameTask(SendMailActivity.this);
        }
    }

    private class SendMessage extends AsyncTask<String, Integer, Boolean> {
        @Override
        protected Boolean doInBackground(String... params) {
            ApiConnecter api = ApiConnecterFactory.getApiConnecter(getApplicationContext());
            return api.sendDraft(draftMessageId, params[1], params[2], params[3], params[4]);
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                Toast.makeText(getApplicationContext(), "Message sent!", Toast.LENGTH_SHORT).show();
                onBackPressed();
            } else {
                Toast.makeText(getApplicationContext(), "Error sending message.", Toast.LENGTH_LONG).show();
            }
        }
    }

    private class FetchDraft extends AsyncTask<String, Integer, ParsedMailpileMessage> {
        @Override
        protected ParsedMailpileMessage doInBackground(String... params) {
            ApiConnecter api = ApiConnecterFactory.getApiConnecter(getApplicationContext());
            return api.getMessage(params[0]);
        }

        @Override
        protected void onPostExecute(ParsedMailpileMessage result) {
            importExistingDraft(result);
        }
    }

    private void importExistingDraft(ParsedMailpileMessage data) {
        if (data.toString.length() > 0) {
            for (String address : data.toString.substring(4).split(", ")) {
                if (!address.isEmpty()) {
                    addressView.addObject(new AutocompleteContact("-1", address), address);
                }
            }
        }

        if (data.ccString.length() > 0) {
            for (String address : data.ccString.substring(4).split(",")) {
                if (!address.isEmpty()) {
                    ccView.addObject(new AutocompleteContact("-1", address), address);
                }
            }
        }

        TextView subject = (TextView) findViewById(R.id.sendViewSubject);
        TextView body = (TextView) findViewById(R.id.sendViewMessage);

        subject.setText(data.metaData.title);
        body.setText("\n\n\n" + data.plainText.replace("<br>", "\n"));

        if (this.progressDialog != null) {
            this.progressDialog.dismiss();
            this.progressDialog = null;
        }
    }
}