Badblog

welcome to our blog

We are Learncodz.


Posts

Comments

The Team

Blog Codz Author

Connect With Us

Join To Connect With Us

Portfolio

  • package com.teamtreehouse.ribbit;

    import java.util.Timer;
    import java.util.TimerTask;

    import android.app.Activity;
    import android.net.Uri;
    import android.os.Bundle;
    import android.support.v4.app.NavUtils;
    import android.view.MenuItem;
    import android.widget.ImageView;

    import com.squareup.picasso.Picasso;

    public class ViewImageActivity extends Activity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_view_image);
            // Show the Up button in the action bar.
            setupActionBar();
           
            ImageView imageView = (ImageView)findViewById(R.id.imageView);
           
            Uri imageUri = getIntent().getData();
           
            Picasso.with(this).load(imageUri.toString()).into(imageView);
           
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    finish();
                }
            }, 10*1000);
        }

        /**
         * Set up the {@link android.app.ActionBar}.
         */
        private void setupActionBar() {

            getActionBar().setDisplayHomeAsUpEnabled(true);

        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case android.R.id.home:
                // This ID represents the Home or Up button. In the case of this
                // activity, the Up button is shown. Use NavUtils to allow users
                // to navigate up one level in the application structure. For
                // more details, see the Navigation pattern on Android Design:
                //
                // http://developer.android.com/design/patterns/navigation.html#up-vs-back
                //
                NavUtils.navigateUpFromSameTask(this);
                return true;
            }
            return super.onOptionsItemSelected(item);
        }

    }
  • package com.teamtreehouse.ribbit;

    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.view.Window;
    import android.widget.Button;
    import android.widget.EditText;

    import com.parse.ParseException;
    import com.parse.ParseUser;
    import com.parse.SignUpCallback;

    public class SignUp extends Activity {
       
        protected EditText mUsername;
        protected EditText mPassword;
        protected EditText mEmail;
        protected Button mSignUpButton;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
            setContentView(R.layout.activity_sign_up);
           
            mUsername = (EditText)findViewById(R.id.usernameField);
            mPassword = (EditText)findViewById(R.id.passwordField);
            mEmail = (EditText)findViewById(R.id.emailField);
            mSignUpButton = (Button)findViewById(R.id.signupButton);
            mSignUpButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String username = mUsername.getText().toString();
                    String password = mPassword.getText().toString();
                    String email = mEmail.getText().toString();
                   
                    username = username.trim();
                    password = password.trim();
                    email = email.trim();
                   
                    if (username.isEmpty() || password.isEmpty() || email.isEmpty()) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(SignUp.this);
                        builder.setMessage(R.string.signup_error_message)
                            .setTitle(R.string.signup_error_title)
                            .setPositiveButton(android.R.string.ok, null);
                        AlertDialog dialog = builder.create();
                        dialog.show();
                    }
                    else {
                        // create the new user!
                        setProgressBarIndeterminateVisibility(true);
                       
                        ParseUser newUser = new ParseUser();
                        newUser.setUsername(username);
                        newUser.setPassword(password);
                        newUser.setEmail(email);
                        newUser.signUpInBackground(new SignUpCallback() {
                            @Override
                            public void done(ParseException e) {
                                setProgressBarIndeterminateVisibility(false);
                               
                                if (e == null) {
                                    // Success!
                                    Intent intent = new Intent(SignUp.this, MainActivity.class);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    startActivity(intent);
                                }
                                else {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(SignUp.this);
                                    builder.setMessage(e.getMessage())
                                        .setTitle(R.string.signup_error_title)
                                        .setPositiveButton(android.R.string.ok, null);
                                    AlertDialog dialog = builder.create();
                                    dialog.show();
                                }
                            }
                        });
                    }
                }
            });
        }
    }
  • package com.teamtreehouse.ribbit;

    import android.app.Application;

    import com.parse.Parse;

    public class RibbitApplication extends Application {
        public static final String YOUR_APPLICATION_ID = "AERqqIXGvzH7Nmg45xa5T8zWRRjqT8UmbFQeeI";
        public static final String YOUR_CLIENT_KEY = "8bXPznF5eSLWq0sY9gTUrEF5BJlia7ltmLQFRh";

       
        @Override
        public void onCreate() {
            super.onCreate();
            Parse.initialize(this, "gRa6AFCT9Rj58XMit3ZDca1Lp5prurnsu8aAE1Yi", "lQtfufb1sp6mDSyGzSdzXHEMtgEYG8gWK2uF7rR8");


        }
    }
  • package com.teamtreehouse.ribbit;

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

    import android.app.AlertDialog;
    import android.app.ListActivity;
    import android.net.Uri;
    import android.os.Bundle;
    import android.support.v4.app.NavUtils;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.Window;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import android.widget.Toast;

    import com.parse.FindCallback;
    import com.parse.ParseException;
    import com.parse.ParseFile;
    import com.parse.ParseObject;
    import com.parse.ParseQuery;
    import com.parse.ParseRelation;
    import com.parse.ParseUser;
    import com.parse.SaveCallback;

    public class RecipientsActivity extends ListActivity {

        public static final String TAG = RecipientsActivity.class.getSimpleName();

        protected ParseRelation<ParseUser> mFriendsRelation;
        protected ParseUser mCurrentUser;   
        protected List<ParseUser> mFriends;   
        protected MenuItem mSendMenuItem;
        protected Uri mMediaUri;
        protected String mFileType;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
            setContentView(R.layout.activity_recipients);
            // Show the Up button in the action bar.
            setupActionBar();
           
            getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
           
            mMediaUri = getIntent().getData();
            mFileType = getIntent().getExtras().getString(ParseConstants.KEY_FILE_TYPE);
        }
       
        @Override
        public void onResume() {
            super.onResume();
           
            mCurrentUser = ParseUser.getCurrentUser();
            mFriendsRelation = mCurrentUser.getRelation(ParseConstants.KEY_FRIENDS_RELATION);
           
            setProgressBarIndeterminateVisibility(true);
           
            ParseQuery<ParseUser> query = mFriendsRelation.getQuery();
            query.addAscendingOrder(ParseConstants.KEY_USERNAME);
            query.findInBackground(new FindCallback<ParseUser>() {
                @Override
                public void done(List<ParseUser> friends, ParseException e) {
                    setProgressBarIndeterminateVisibility(false);
                   
                    if (e == null) {
                        mFriends = friends;
                       
                        String[] usernames = new String[mFriends.size()];
                        int i = 0;
                        for(ParseUser user : mFriends) {
                            usernames[i] = user.getUsername();
                            i++;
                        }
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                                getListView().getContext(),
                                android.R.layout.simple_list_item_checked,
                                usernames);
                        setListAdapter(adapter);
                    }
                    else {
                        Log.e(TAG, e.getMessage());
                        AlertDialog.Builder builder = new AlertDialog.Builder(RecipientsActivity.this);
                        builder.setMessage(e.getMessage())
                            .setTitle(R.string.error_title)
                            .setPositiveButton(android.R.string.ok, null);
                        AlertDialog dialog = builder.create();
                        dialog.show();
                    }
                }
            });
        }

        /**
         * Set up the {@link android.app.ActionBar}.
         */
        private void setupActionBar() {

            getActionBar().setDisplayHomeAsUpEnabled(true);

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.recipients, menu);
            mSendMenuItem = menu.getItem(0);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case android.R.id.home:
                // This ID represents the Home or Up button. In the case of this
                // activity, the Up button is shown. Use NavUtils to allow users
                // to navigate up one level in the application structure. For
                // more details, see the Navigation pattern on Android Design:
                //
                // http://developer.android.com/design/patterns/navigation.html#up-vs-back
                //
                NavUtils.navigateUpFromSameTask(this);
                return true;
            case R.id.action_send:
                ParseObject message = createMessage();
                if (message == null) {
                    // error
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setMessage(R.string.error_selecting_file)
                        .setTitle(R.string.error_selecting_file_title)
                        .setPositiveButton(android.R.string.ok, null);
                    AlertDialog dialog = builder.create();
                    dialog.show();
                }
                else {
                    send(message);
                    finish();
                }
                return true;
            }
            return super.onOptionsItemSelected(item);
        }

        @Override
        protected void onListItemClick(ListView l, View v, int position, long id) {
            super.onListItemClick(l, v, position, id);
           
            if (l.getCheckedItemCount() > 0) {
                mSendMenuItem.setVisible(true);
            }
            else {
                mSendMenuItem.setVisible(false);
            }
        }
       
        protected ParseObject createMessage() {
            ParseObject message = new ParseObject(ParseConstants.CLASS_MESSAGES);
            message.put(ParseConstants.KEY_SENDER_ID, ParseUser.getCurrentUser().getObjectId());
            message.put(ParseConstants.KEY_SENDER_NAME, ParseUser.getCurrentUser().getUsername());
            message.put(ParseConstants.KEY_RECIPIENT_IDS, getRecipientIds());
            message.put(ParseConstants.KEY_FILE_TYPE, mFileType);
           
            byte[] fileBytes = FileHelper.getByteArrayFromFile(this, mMediaUri);
           
            if (fileBytes == null) {
                return null;
            }
            else {
                if (mFileType.equals(ParseConstants.TYPE_IMAGE)) {
                    fileBytes = FileHelper.reduceImageForUpload(fileBytes);
                }
               
                String fileName = FileHelper.getFileName(this, mMediaUri, mFileType);
                ParseFile file = new ParseFile(fileName, fileBytes);
                message.put(ParseConstants.KEY_FILE, file);

                return message;
            }
        }
       
        protected ArrayList<String> getRecipientIds() {
            ArrayList<String> recipientIds = new ArrayList<String>();
            for (int i = 0; i < getListView().getCount(); i++) {
                if (getListView().isItemChecked(i)) {
                    recipientIds.add(mFriends.get(i).getObjectId());
                }
            }
            return recipientIds;
        }
       
        protected void send(ParseObject message) {
            message.saveInBackground(new SaveCallback() {
                @Override
                public void done(ParseException e) {
                    if (e == null) {
                        // success!
                        Toast.makeText(RecipientsActivity.this, R.string.success_message, Toast.LENGTH_LONG).show();
                    }
                    else {
                        AlertDialog.Builder builder = new AlertDialog.Builder(RecipientsActivity.this);
                        builder.setMessage(R.string.error_sending_message)
                            .setTitle(R.string.error_selecting_file_title)
                            .setPositiveButton(android.R.string.ok, null);
                        AlertDialog dialog = builder.create();
                        dialog.show();
                    }
                }
            });
        }
    }






  • package com.teamtreehouse.ribbit;

    public final class ParseConstants {
        // Class name
        public static final String CLASS_MESSAGES = "Messages";
       
        // Field names
        public static final String KEY_USERNAME = "username";
        public static final String KEY_FRIENDS_RELATION = "friendsRelation";
        public static final String KEY_RECIPIENT_IDS = "recipientIds";
        public static final String KEY_SENDER_ID = "senderId";
        public static final String KEY_SENDER_NAME = "senderName";
        public static final String KEY_FILE = "file";
        public static final String KEY_FILE_TYPE = "fileType";
        public static final String KEY_CREATED_AT = "createdAt";
       
        public static final String TYPE_IMAGE = "image";
        public static final String TYPE_VIDEO = "video";
    }
  • package com.teamtreehouse.ribbit;

    import java.util.List;

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;

    import com.parse.ParseObject;

    public class MessageAdapter extends ArrayAdapter<ParseObject> {
       
        protected Context mContext;
        protected List<ParseObject> mMessages;
       
        public MessageAdapter(Context context, List<ParseObject> messages) {
            super(context, R.layout.message_item, messages);
            mContext = context;
            mMessages = messages;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
           
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.message_item, null);
                holder = new ViewHolder();
                holder.iconImageView = (ImageView)convertView.findViewById(R.id.messageIcon);
                holder.nameLabel = (TextView)convertView.findViewById(R.id.senderLabel);
                convertView.setTag(holder);
            }
            else {
                holder = (ViewHolder)convertView.getTag();
            }
           
            ParseObject message = mMessages.get(position);
           
            if (message.getString(ParseConstants.KEY_FILE_TYPE).equals(ParseConstants.TYPE_IMAGE)) {
                holder.iconImageView.setImageResource(R.drawable.ic_action_picture);
            }
            else {
                holder.iconImageView.setImageResource(R.drawable.ic_action_play_over_video);
            }
            holder.nameLabel.setText(message.getString(ParseConstants.KEY_SENDER_NAME));
           
            return convertView;
        }
       
        private static class ViewHolder {
            ImageView iconImageView;
            TextView nameLabel;
        }
       
        public void refill(List<ParseObject> messages) {
            mMessages.clear();
            mMessages.addAll(messages);
            notifyDataSetChanged();
        }
    }






  • package com.teamtreehouse.ribbit;

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;

    import android.app.ActionBar;
    import android.app.AlertDialog;
    import android.app.FragmentTransaction;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    import android.provider.MediaStore;
    import android.support.v4.app.FragmentActivity;
    import android.support.v4.view.ViewPager;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.Window;
    import android.widget.Toast;

    import com.parse.ParseAnalytics;
    import com.parse.ParseUser;

    public class MainActivity extends FragmentActivity implements
            ActionBar.TabListener {
       
        public static final String TAG = MainActivity.class.getSimpleName();
       
        public static final int TAKE_PHOTO_REQUEST = 0;
        public static final int TAKE_VIDEO_REQUEST = 1;
        public static final int PICK_PHOTO_REQUEST = 2;
        public static final int PICK_VIDEO_REQUEST = 3;
       
        public static final int MEDIA_TYPE_IMAGE = 4;
        public static final int MEDIA_TYPE_VIDEO = 5;
       
        public static final int FILE_SIZE_LIMIT = 1024*1024*10; // 10 MB
       
        protected Uri mMediaUri;
       
        protected DialogInterface.OnClickListener mDialogListener =
                new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch(which) {
                    case 0: // Take picture
                        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        mMediaUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
                        if (mMediaUri == null) {
                            // display an error
                            Toast.makeText(MainActivity.this, R.string.error_external_storage,
                                    Toast.LENGTH_LONG).show();
                        }
                        else {
                            takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mMediaUri);
                            startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST);
                        }
                        break;
                    case 1: // Take video
                        Intent videoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                        mMediaUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
                        if (mMediaUri == null) {
                            // display an error
                            Toast.makeText(MainActivity.this, R.string.error_external_storage,
                                    Toast.LENGTH_LONG).show();
                        }
                        else {
                            videoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mMediaUri);
                            videoIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
                            videoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0); // 0 = lowest res
                            startActivityForResult(videoIntent, TAKE_VIDEO_REQUEST);
                        }
                        break;
                    case 2: // Choose picture
                        Intent choosePhotoIntent = new Intent(Intent.ACTION_GET_CONTENT);
                        choosePhotoIntent.setType("image/*");
                        startActivityForResult(choosePhotoIntent, PICK_PHOTO_REQUEST);
                        break;
                    case 3: // Choose video
                        Intent chooseVideoIntent = new Intent(Intent.ACTION_GET_CONTENT);
                        chooseVideoIntent.setType("video/*");
                        Toast.makeText(MainActivity.this, R.string.video_file_size_warning, Toast.LENGTH_LONG).show();
                        startActivityForResult(chooseVideoIntent, PICK_VIDEO_REQUEST);
                        break;
                }
            }

            private Uri getOutputMediaFileUri(int mediaType) {
                // To be safe, you should check that the SDCard is mounted
                // using Environment.getExternalStorageState() before doing this.
                if (isExternalStorageAvailable()) {
                    // get the URI
                   
                    // 1. Get the external storage directory
                    String appName = MainActivity.this.getString(R.string.app_name);
                    File mediaStorageDir = new File(
                            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                            appName);
                   
                    // 2. Create our subdirectory
                    if (! mediaStorageDir.exists()) {
                        if (! mediaStorageDir.mkdirs()) {
                            Log.e(TAG, "Failed to create directory.");
                            return null;
                        }
                    }
                   
                    // 3. Create a file name
                    // 4. Create the file
                    File mediaFile;
                    Date now = new Date();
                    String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(now);
                   
                    String path = mediaStorageDir.getPath() + File.separator;
                    if (mediaType == MEDIA_TYPE_IMAGE) {
                        mediaFile = new File(path + "IMG_" + timestamp + ".jpg");
                    }
                    else if (mediaType == MEDIA_TYPE_VIDEO) {
                        mediaFile = new File(path + "VID_" + timestamp + ".mp4");
                    }
                    else {
                        return null;
                    }
                   
                    Log.d(TAG, "File: " + Uri.fromFile(mediaFile));
                   
                    // 5. Return the file's URI               
                    return Uri.fromFile(mediaFile);
                }
                else {
                    return null;
                }
            }
           
            private boolean isExternalStorageAvailable() {
                String state = Environment.getExternalStorageState();
               
                if (state.equals(Environment.MEDIA_MOUNTED)) {
                    return true;
                }
                else {
                    return false;
                }
            }
        };

        /**
         * The {@link android.support.v4.view.PagerAdapter} that will provide
         * fragments for each of the sections. We use a
         * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
         * will keep every loaded fragment in memory. If this becomes too memory
         * intensive, it may be best to switch to a
         * {@link android.support.v4.app.FragmentStatePagerAdapter}.
         */
        SectionsPagerAdapter mSectionsPagerAdapter;

        /**
         * The {@link ViewPager} that will host the section contents.
         */
        ViewPager mViewPager;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
            setContentView(R.layout.activity_main);
           
            ParseAnalytics.trackAppOpened(getIntent());
           
            ParseUser currentUser = ParseUser.getCurrentUser();
            if (currentUser == null) {
                navigateToLogin();
            }
            else {
                Log.i(TAG, currentUser.getUsername());
            }

            // Set up the action bar.
            final ActionBar actionBar = getActionBar();
            actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

            // Create the adapter that will return a fragment for each of the three
            // primary sections of the app.
            mSectionsPagerAdapter = new SectionsPagerAdapter(this,
                    getSupportFragmentManager());

            // Set up the ViewPager with the sections adapter.
            mViewPager = (ViewPager) findViewById(R.id.pager);
            mViewPager.setAdapter(mSectionsPagerAdapter);

            // When swiping between different sections, select the corresponding
            // tab. We can also use ActionBar.Tab#select() to do this if we have
            // a reference to the Tab.
            mViewPager
                    .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                        @Override
                        public void onPageSelected(int position) {
                            actionBar.setSelectedNavigationItem(position);
                        }
                    });

            // For each of the sections in the app, add a tab to the action bar.
            for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
                // Create a tab with text corresponding to the page title defined by
                // the adapter. Also specify this Activity object, which implements
                // the TabListener interface, as the callback (listener) for when
                // this tab is selected.
                actionBar.addTab(actionBar.newTab()
                        .setText(mSectionsPagerAdapter.getPageTitle(i))
                        .setTabListener(this));
            }
        }
       
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
           
            if (resultCode == RESULT_OK) {           
                if (requestCode == PICK_PHOTO_REQUEST || requestCode == PICK_VIDEO_REQUEST) {
                    if (data == null) {
                        Toast.makeText(this, getString(R.string.general_error), Toast.LENGTH_LONG).show();
                    }
                    else {
                        mMediaUri = data.getData();
                    }
                   
                    Log.i(TAG, "Media URI: " + mMediaUri);
                    if (requestCode == PICK_VIDEO_REQUEST) {
                        // make sure the file is less than 10 MB
                        int fileSize = 0;
                        InputStream inputStream = null;
                       
                        try {
                            inputStream = getContentResolver().openInputStream(mMediaUri);
                            fileSize = inputStream.available();
                        }
                        catch (FileNotFoundException e) {
                            Toast.makeText(this, R.string.error_opening_file, Toast.LENGTH_LONG).show();
                            return;
                        }
                        catch (IOException e) {
                            Toast.makeText(this, R.string.error_opening_file, Toast.LENGTH_LONG).show();
                            return;
                        }
                        finally {
                            try {
                                inputStream.close();
                            } catch (IOException e) { /* Intentionally blank */ }
                        }
                       
                        if (fileSize >= FILE_SIZE_LIMIT) {
                            Toast.makeText(this, R.string.error_file_size_too_large, Toast.LENGTH_LONG).show();
                            return;
                        }
                    }
                }
                else {
                    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    mediaScanIntent.setData(mMediaUri);
                    sendBroadcast(mediaScanIntent);
                }
               
                Intent recipientsIntent = new Intent(this, RecipientsActivity.class);
                recipientsIntent.setData(mMediaUri);
               
                String fileType;
                if (requestCode == PICK_PHOTO_REQUEST || requestCode == TAKE_PHOTO_REQUEST) {
                    fileType = ParseConstants.TYPE_IMAGE;
                }
                else {
                    fileType = ParseConstants.TYPE_VIDEO;
                }
               
                recipientsIntent.putExtra(ParseConstants.KEY_FILE_TYPE, fileType);
                startActivity(recipientsIntent);
            }
            else if (resultCode != RESULT_CANCELED) {
                Toast.makeText(this, R.string.general_error, Toast.LENGTH_LONG).show();
            }
        }

        private void navigateToLogin() {
            Intent intent = new Intent(this, Login.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        }

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

       
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int itemId = item.getItemId();
           
            switch(itemId) {
                case R.id.action_logout:
                    ParseUser.logOut();
                    navigateToLogin();
                    break;
                case R.id.action_edit_friends:
                    Intent intent = new Intent(this, Georgians.class);
                    startActivity(intent);
                    break;
                case R.id.action_camera:
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setItems(R.array.camera_choices, mDialogListener);
                    AlertDialog dialog = builder.create();
                    dialog.show();
                    break;
            }
           
            return super.onOptionsItemSelected(item);
        }

        @Override
        public void onTabSelected(ActionBar.Tab tab,
                FragmentTransaction fragmentTransaction) {
            // When the given tab is selected, switch to the corresponding page in
            // the ViewPager.
            mViewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(ActionBar.Tab tab,
                FragmentTransaction fragmentTransaction) {
        }

        @Override
        public void onTabReselected(ActionBar.Tab tab,
                FragmentTransaction fragmentTransaction) {
        }
    }
  • package com.teamtreehouse.ribbit;

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

    import android.content.Intent;
    import android.net.Uri;
    import android.os.Bundle;
    import android.support.v4.app.ListFragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ListView;

    import com.parse.FindCallback;
    import com.parse.ParseException;
    import com.parse.ParseFile;
    import com.parse.ParseObject;
    import com.parse.ParseQuery;
    import com.parse.ParseUser;

    public class InboxFragment extends ListFragment {

        protected List<ParseObject> mMessages;
       
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_inbox,
                    container, false);

            return rootView;
        }

        @Override
        public void onResume() {
            super.onResume();
           
            getActivity().setProgressBarIndeterminateVisibility(true);
           
            ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(ParseConstants.CLASS_MESSAGES);
            query.whereEqualTo(ParseConstants.KEY_RECIPIENT_IDS, ParseUser.getCurrentUser().getObjectId());
            query.addDescendingOrder(ParseConstants.KEY_CREATED_AT);
            query.findInBackground(new FindCallback<ParseObject>() {
                @Override
                public void done(List<ParseObject> messages, ParseException e) {
                    getActivity().setProgressBarIndeterminateVisibility(false);
                   
                    if (e == null) {
                        // We found messages!
                        mMessages = messages;

                        String[] usernames = new String[mMessages.size()];
                        int i = 0;
                        for(ParseObject message : mMessages) {
                            usernames[i] = message.getString(ParseConstants.KEY_SENDER_NAME);
                            i++;
                        }
                        if (getListView().getAdapter() == null) {
                            MessageAdapter adapter = new MessageAdapter(
                                    getListView().getContext(),
                                    mMessages);
                            setListAdapter(adapter);
                        }
                        else {
                            // refill the adapter!
                            ((MessageAdapter)getListView().getAdapter()).refill(mMessages);
                        }
                    }
                }
            });
        }
       
        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
            super.onListItemClick(l, v, position, id);
           
            ParseObject message = mMessages.get(position);
            String messageType = message.getString(ParseConstants.KEY_FILE_TYPE);
            ParseFile file = message.getParseFile(ParseConstants.KEY_FILE);
            Uri fileUri = Uri.parse(file.getUrl());
           
            if (messageType.equals(ParseConstants.TYPE_IMAGE)) {
                // view the image
                Intent intent = new Intent(getActivity(), ViewImageActivity.class);
                intent.setData(fileUri);
                startActivity(intent);
            }
            else {
                // view the video
                Intent intent = new Intent(Intent.ACTION_VIEW, fileUri);
                intent.setDataAndType(fileUri, "video/*");
                startActivity(intent);
            }
           
            // Delete it!
            List<String> ids = message.getList(ParseConstants.KEY_RECIPIENT_IDS);
           
            if (ids.size() == 1) {
                // last recipient - delete the whole thing!
                message.deleteInBackground();
            }
            else {
                // remove the recipient and save
                ids.remove(ParseUser.getCurrentUser().getObjectId());
               
                ArrayList<String> idsToRemove = new ArrayList<String>();
                idsToRemove.add(ParseUser.getCurrentUser().getObjectId());
               
                message.removeAll(ParseConstants.KEY_RECIPIENT_IDS, idsToRemove);
                message.saveInBackground();
            }
        }
    }








  • package com.teamtreehouse.ribbit;

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;

    import android.app.ActionBar;
    import android.app.AlertDialog;
    import android.app.FragmentTransaction;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    import android.provider.MediaStore;
    import android.support.v4.app.FragmentActivity;
    import android.support.v4.view.ViewPager;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.Window;
    import android.widget.Toast;

    import com.parse.ParseAnalytics;
    import com.parse.ParseUser;

    public class MainActivity extends FragmentActivity implements
            ActionBar.TabListener {
       
        public static final String TAG = MainActivity.class.getSimpleName();
       
        public static final int TAKE_PHOTO_REQUEST = 0;
        public static final int TAKE_VIDEO_REQUEST = 1;
        public static final int PICK_PHOTO_REQUEST = 2;
        public static final int PICK_VIDEO_REQUEST = 3;
       
        public static final int MEDIA_TYPE_IMAGE = 4;
        public static final int MEDIA_TYPE_VIDEO = 5;
       
        public static final int FILE_SIZE_LIMIT = 1024*1024*10; // 10 MB
       
        protected Uri mMediaUri;
       
        protected DialogInterface.OnClickListener mDialogListener =
                new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch(which) {
                    case 0: // Take picture
                        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        mMediaUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
                        if (mMediaUri == null) {
                            // display an error
                            Toast.makeText(MainActivity.this, R.string.error_external_storage,
                                    Toast.LENGTH_LONG).show();
                        }
                        else {
                            takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mMediaUri);
                            startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST);
                        }
                        break;
                    case 1: // Take video
                        Intent videoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                        mMediaUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
                        if (mMediaUri == null) {
                            // display an error
                            Toast.makeText(MainActivity.this, R.string.error_external_storage,
                                    Toast.LENGTH_LONG).show();
                        }
                        else {
                            videoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mMediaUri);
                            videoIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
                            videoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0); // 0 = lowest res
                            startActivityForResult(videoIntent, TAKE_VIDEO_REQUEST);
                        }
                        break;
                    case 2: // Choose picture
                        Intent choosePhotoIntent = new Intent(Intent.ACTION_GET_CONTENT);
                        choosePhotoIntent.setType("image/*");
                        startActivityForResult(choosePhotoIntent, PICK_PHOTO_REQUEST);
                        break;
                    case 3: // Choose video
                        Intent chooseVideoIntent = new Intent(Intent.ACTION_GET_CONTENT);
                        chooseVideoIntent.setType("video/*");
                        Toast.makeText(MainActivity.this, R.string.video_file_size_warning, Toast.LENGTH_LONG).show();
                        startActivityForResult(chooseVideoIntent, PICK_VIDEO_REQUEST);
                        break;
                }
            }

            private Uri getOutputMediaFileUri(int mediaType) {
                // To be safe, you should check that the SDCard is mounted
                // using Environment.getExternalStorageState() before doing this.
                if (isExternalStorageAvailable()) {
                    // get the URI
                   
                    // 1. Get the external storage directory
                    String appName = MainActivity.this.getString(R.string.app_name);
                    File mediaStorageDir = new File(
                            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                            appName);
                   
                    // 2. Create our subdirectory
                    if (! mediaStorageDir.exists()) {
                        if (! mediaStorageDir.mkdirs()) {
                            Log.e(TAG, "Failed to create directory.");
                            return null;
                        }
                    }
                   
                    // 3. Create a file name
                    // 4. Create the file
                    File mediaFile;
                    Date now = new Date();
                    String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(now);
                   
                    String path = mediaStorageDir.getPath() + File.separator;
                    if (mediaType == MEDIA_TYPE_IMAGE) {
                        mediaFile = new File(path + "IMG_" + timestamp + ".jpg");
                    }
                    else if (mediaType == MEDIA_TYPE_VIDEO) {
                        mediaFile = new File(path + "VID_" + timestamp + ".mp4");
                    }
                    else {
                        return null;
                    }
                   
                    Log.d(TAG, "File: " + Uri.fromFile(mediaFile));
                   
                    // 5. Return the file's URI               
                    return Uri.fromFile(mediaFile);
                }
                else {
                    return null;
                }
            }
           
            private boolean isExternalStorageAvailable() {
                String state = Environment.getExternalStorageState();
               
                if (state.equals(Environment.MEDIA_MOUNTED)) {
                    return true;
                }
                else {
                    return false;
                }
            }
        };

        /**
         * The {@link android.support.v4.view.PagerAdapter} that will provide
         * fragments for each of the sections. We use a
         * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
         * will keep every loaded fragment in memory. If this becomes too memory
         * intensive, it may be best to switch to a
         * {@link android.support.v4.app.FragmentStatePagerAdapter}.
         */
        SectionsPagerAdapter mSectionsPagerAdapter;

        /**
         * The {@link ViewPager} that will host the section contents.
         */
        ViewPager mViewPager;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
            setContentView(R.layout.activity_main);
           
            ParseAnalytics.trackAppOpened(getIntent());
           
            ParseUser currentUser = ParseUser.getCurrentUser();
            if (currentUser == null) {
                navigateToLogin();
            }
            else {
                Log.i(TAG, currentUser.getUsername());
            }

            // Set up the action bar.
            final ActionBar actionBar = getActionBar();
            actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

            // Create the adapter that will return a fragment for each of the three
            // primary sections of the app.
            mSectionsPagerAdapter = new SectionsPagerAdapter(this,
                    getSupportFragmentManager());

            // Set up the ViewPager with the sections adapter.
            mViewPager = (ViewPager) findViewById(R.id.pager);
            mViewPager.setAdapter(mSectionsPagerAdapter);

            // When swiping between different sections, select the corresponding
            // tab. We can also use ActionBar.Tab#select() to do this if we have
            // a reference to the Tab.
            mViewPager
                    .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                        @Override
                        public void onPageSelected(int position) {
                            actionBar.setSelectedNavigationItem(position);
                        }
                    });

            // For each of the sections in the app, add a tab to the action bar.
            for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
                // Create a tab with text corresponding to the page title defined by
                // the adapter. Also specify this Activity object, which implements
                // the TabListener interface, as the callback (listener) for when
                // this tab is selected.
                actionBar.addTab(actionBar.newTab()
                        .setText(mSectionsPagerAdapter.getPageTitle(i))
                        .setTabListener(this));
            }
        }
       
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
           
            if (resultCode == RESULT_OK) {           
                if (requestCode == PICK_PHOTO_REQUEST || requestCode == PICK_VIDEO_REQUEST) {
                    if (data == null) {
                        Toast.makeText(this, getString(R.string.general_error), Toast.LENGTH_LONG).show();
                    }
                    else {
                        mMediaUri = data.getData();
                    }
                   
                    Log.i(TAG, "Media URI: " + mMediaUri);
                    if (requestCode == PICK_VIDEO_REQUEST) {
                        // make sure the file is less than 10 MB
                        int fileSize = 0;
                        InputStream inputStream = null;
                       
                        try {
                            inputStream = getContentResolver().openInputStream(mMediaUri);
                            fileSize = inputStream.available();
                        }
                        catch (FileNotFoundException e) {
                            Toast.makeText(this, R.string.error_opening_file, Toast.LENGTH_LONG).show();
                            return;
                        }
                        catch (IOException e) {
                            Toast.makeText(this, R.string.error_opening_file, Toast.LENGTH_LONG).show();
                            return;
                        }
                        finally {
                            try {
                                inputStream.close();
                            } catch (IOException e) { /* Intentionally blank */ }
                        }
                       
                        if (fileSize >= FILE_SIZE_LIMIT) {
                            Toast.makeText(this, R.string.error_file_size_too_large, Toast.LENGTH_LONG).show();
                            return;
                        }
                    }
                }
                else {
                    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    mediaScanIntent.setData(mMediaUri);
                    sendBroadcast(mediaScanIntent);
                }
               
                Intent recipientsIntent = new Intent(this, RecipientsActivity.class);
                recipientsIntent.setData(mMediaUri);
               
                String fileType;
                if (requestCode == PICK_PHOTO_REQUEST || requestCode == TAKE_PHOTO_REQUEST) {
                    fileType = ParseConstants.TYPE_IMAGE;
                }
                else {
                    fileType = ParseConstants.TYPE_VIDEO;
                }
               
                recipientsIntent.putExtra(ParseConstants.KEY_FILE_TYPE, fileType);
                startActivity(recipientsIntent);
            }
            else if (resultCode != RESULT_CANCELED) {
                Toast.makeText(this, R.string.general_error, Toast.LENGTH_LONG).show();
            }
        }

        private void navigateToLogin() {
            Intent intent = new Intent(this, Login.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        }

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

       
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int itemId = item.getItemId();
           
            switch(itemId) {
                case R.id.action_logout:
                    ParseUser.logOut();
                    navigateToLogin();
                    break;
                case R.id.action_edit_friends:
                    Intent intent = new Intent(this, Georgians.class);
                    startActivity(intent);
                    break;
                case R.id.action_camera:
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setItems(R.array.camera_choices, mDialogListener);
                    AlertDialog dialog = builder.create();
                    dialog.show();
                    break;
            }
           
            return super.onOptionsItemSelected(item);
        }

        @Override
        public void onTabSelected(ActionBar.Tab tab,
                FragmentTransaction fragmentTransaction) {
            // When the given tab is selected, switch to the corresponding page in
            // the ViewPager.
            mViewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(ActionBar.Tab tab,
                FragmentTransaction fragmentTransaction) {
        }

        @Override
        public void onTabReselected(ActionBar.Tab tab,
                FragmentTransaction fragmentTransaction) {
        }
    }

Comments

The Visitors says
Download Free Software Latest Version