Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Lend Kazazi
223 Pointshow to separate two different fragments with similare code
when i try to make a new daily inbox and a normal inbox they get mixed and all the messages for both off them show in both the daily and the inbox fragment.How can i separate them so they both how their own messages?
INBOX FRAGMENT
@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){
//Success
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 Image
Intent intent = new Intent (getActivity(), ViewImageActivity.class);
intent.setData(fileUri);
startActivity(intent);
}else if(messageType.equals(ParseConstants.TYPE_VIDEO)){
Intent intent = new Intent (Intent.ACTION_VIEW, fileUri);
intent.setDataAndType(fileUri, "video/*");
startActivity(intent);
}else if (messageType.equals(ParseConstants.TYPE_TEXT)){
//Toast.makeText(getActivity(), displayMessage, Toast.LENGTH_LONG).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Message from: " + getString(ParseConstants.KEY_SENDER_NAME) + ".");
builder.setMessage(displayMessage);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
List<String> ids = message.getList(ParseConstants.KEY_RECIPIENT_IDS);
if (ids.size() == 1) {
message.deleteInBackground();
}
else{
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();
}
}
private String getString(String keySenderName) {
// TODO Auto-generated method stub
return null;
}
}
DAILY FRAGMENT
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_daily, 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){
//Success
mMessages = messages;
String[] usernames = new String[mMessages.size()];
int i = 0;
for (ParseObject message : mMessages){
usernames[i] = message.getString(ParseConstants.KEY_SENDER_NAME);
i++;
}
MessageAdapter adapter = new MessageAdapter(getListView().getContext(), mMessages);
setListAdapter (adapter);
}
}
});
} @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 Image
Intent intent = new Intent (getActivity(), ViewImageActivity.class);
intent.setData(fileUri);
startActivity(intent);
}
else{
//view Video
Intent intent = new Intent (Intent.ACTION_VIEW, fileUri);
intent.setDataAndType(fileUri, "video/*");
startActivity(intent);
}
}
}
MAIN ACTIVITY
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_PICTURE_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; //10MB
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:
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);
startActivityForResult(videoIntent,TAKE_VIDEO_REQUEST);
}
break;
case 2: //Choose Picture
Intent choosePhotoIntent = new Intent(Intent.ACTION_GET_CONTENT);
choosePhotoIntent.setType("image/*");
startActivityForResult(choosePhotoIntent, PICK_PICTURE_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) {
if (isExternalStorageAvailable()){
//get the URI
return null;
}
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 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.v13.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 activity.
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_PICTURE_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 10MB
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) {
}
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_PICTURE_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, LoginActivity.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, EditFriendsActivity.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;
case R.id.action_daily:
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setItems(R.array.camera_choices, mDialogListener);
AlertDialog dialog1 = builder1.create();
dialog1.show();
break;
case R.id.action_chat:
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Send Message.");
alert.setMessage("Type your message below.");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
Intent recipientsIntent = new Intent(MainActivity.this, RecipientsActivity.class);
recipientsIntent.putExtra(ParseConstants.KEY_MESSAGE, value);
recipientsIntent.putExtra(ParseConstants.KEY_FILE_TYPE, ParseConstants.TYPE_TEXT);
startActivity(recipientsIntent);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.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) {
}
}