Android Open Source - EncryptThis Main Activity






From Project

Back to project page EncryptThis.

License

The source code is released under:

GNU General Public License

If you think the Android project EncryptThis listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package gr.tsagi.encryptthis;
//from  w ww.  j a  va 2 s  . c  om
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.dropbox.sync.android.DbxAccountManager;
import com.dropbox.sync.android.DbxFile;
import com.dropbox.sync.android.DbxFileSystem;
import com.dropbox.sync.android.DbxPath;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.ArrayList;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class MainActivity extends ActionBarActivity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks {

    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;

    /**
     * Used to store the last screen title. For use in {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;

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

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));
    }


    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
                .commit();
    }

    public void onSectionAttached(int number) {
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
        ArrayList<String> filesList = new ArrayList<String>();
        try {
            filesList = (ArrayList<String>) ObjectSerializer.
                    deserialize(prefs.getString("fileList",
                    ObjectSerializer.serialize(new ArrayList<String>())));
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(!filesList.isEmpty())
            mTitle = filesList.get(number - 1);

    }

    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.main, menu);
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @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.
        switch (item.getItemId()) {
            case R.id.action_settings:
                return true;
        }
        return super.onOptionsItemSelected(item);
    }



    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        private DbxAccountManager mDbxAcctMgr;
        private TextView mTestOutput;
        private Button mLinkButton;

        private static final int REQUEST_LINK_TO_DBX = 0;

        private String APP_KEY = "hz3jopxufq0zmey";
        private String APP_SECRET = "h5lg3nn7cvnlppu";
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            mDbxAcctMgr = DbxAccountManager.getInstance(getActivity().getApplicationContext(), APP_KEY, APP_SECRET);
            mTestOutput = (TextView) rootView.findViewById(R.id.test_output);
            mLinkButton = (Button) rootView.findViewById(R.id.link_button);

            mLinkButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClickLinkToDropbox();
                }
            });
            return rootView;
        }

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            try{
            ((MainActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }


        @Override
        public void onResume() {
            super.onResume();
            if (mDbxAcctMgr.hasLinkedAccount()) {
                showLinkedView();
                getFromDropbox();
            } else {
                showUnlinkedView();
            }
        }

        private void showLinkedView() {
            mLinkButton.setVisibility(View.GONE);
            mTestOutput.setVisibility(View.VISIBLE);
        }

        private void showUnlinkedView() {
            mLinkButton.setVisibility(View.VISIBLE);
            mTestOutput.setVisibility(View.GONE);
        }

        private void onClickLinkToDropbox() {
            mDbxAcctMgr.startLink(getActivity(), REQUEST_LINK_TO_DBX);
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == REQUEST_LINK_TO_DBX) {
                if (resultCode == Activity.RESULT_OK) {
                    getFromDropbox();
                } else {
                    mTestOutput.setText("Link to Dropbox failed or was cancelled.");
                }
            } else {
                super.onActivityResult(requestCode, resultCode, data);
            }
        }

        private void getFromDropbox() {
            SharedPreferences prefs = PreferenceManager
                    .getDefaultSharedPreferences(getActivity().getApplicationContext());
            ArrayList<String> filesList = new ArrayList<String>();
            try {
                filesList = (ArrayList<String>) ObjectSerializer.
                        deserialize(prefs.getString("fileList",
                                ObjectSerializer.serialize(new ArrayList<String>())));
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                final String FILE_NAME = filesList.get(getArguments().getInt(ARG_SECTION_NUMBER) - 1);
                DbxPath filePath = new DbxPath(DbxPath.ROOT, FILE_NAME);


                // Create DbxFileSystem for synchronized file access.
                DbxFileSystem dbxFs = DbxFileSystem.forAccount(mDbxAcctMgr.getLinkedAccount());

                // Read and print the contents of test file.  Since we're not making
                // any attempt to wait for the latest version, this may print an
                // older cached version.  Use getSyncStatus() and/or a listener to
                // check for a new version.
                if (dbxFs.isFile(filePath)) {
                    String resultData;
                    byte [] data = new byte[4096];
                    DbxFile testFile = dbxFs.open(filePath);
                    BufferedInputStream br = null;
                    try {
                        testFile.getReadStream();
                        br = new BufferedInputStream(testFile.getReadStream());

//                        resultData = testFile.readString();
                    } finally {
                        testFile.close();
                    }
                    mTestOutput.setText("");
                    mTestOutput.append(String.valueOf(br.read(data)));
                } else if (dbxFs.isFolder(filePath)) {
                    Toast.makeText(getActivity().getApplicationContext(),
                            filePath.toString() + "is a folder. I will fix that soon!",Toast.LENGTH_SHORT).show();
                }
            } catch (IOException e) {
                mTestOutput.setText("Dropbox failed: " + e);
            }
        }
        private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] decrypted = cipher.doFinal(encrypted);
            return decrypted;
        }
    }

}




Java Source Code List

gr.tsagi.encryptthis.MainActivity.java
gr.tsagi.encryptthis.NavigationDrawerFragment.java
gr.tsagi.encryptthis.ObjectSerializer.java