Get Context from Android Activiy - android

I have implemented an Image Gallery using a GridView displaying thumbnails of images and a Fullscreen Activity which will display each of the images in fullscreen mode. The file paths are passed using Intents (putExtra) to the GridView Activity to display different GridViews depending on folder name in SDCARD.Now the problem I have is that I cannot pass those file paths to the Fullscreen Activity in order to view every image separately.
Below are my Classes ;
MainActivity.java
package info.androidhive.imageslider;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private Button btn1, btn2;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
setOnClickListeners();
}
public void setOnClickListeners(){
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.button1:
Toast.makeText(getApplicationContext(), "Loading Gridview 1", Toast.LENGTH_LONG).show();
intent = new Intent(MainActivity.this, GridViewActivity.class);
intent.putExtra("folder", "folder1");
startActivity(intent);
break;
case R.id.button2:
Toast.makeText(getApplicationContext(), "Loading Gridview 2", Toast.LENGTH_LONG).show();
intent = new Intent(MainActivity.this, GridViewActivity.class);
intent.putExtra("folder", "folder2");
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;
}
}
So in this activity am passing different folder names for each button clicks.
GridViewActivity.java
This class will receive the intent parameters for the folder names and it will list all image thumbnails for that specific folder. Until here everything is fine and I can view the images for each different folder depending on the button clicked.
package info.androidhive.imageslider;
import info.androidhive.imageslider.adapter.GridViewImageAdapter;
import info.androidhive.imageslider.helper.AppConstant;
import info.androidhive.imageslider.helper.Utils;
import java.io.File;
import java.util.ArrayList;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Display;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.Toast;
public class GridViewActivity extends Activity {
private Utils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private GridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
//Utils
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid_view);
gridView = (GridView) findViewById(R.id.grid_view);
//utils = new Utils(this);
mContext = this;
// Initilizing Grid View
InitilizeGridLayout();
// loading all image paths from SD card
imagePaths = getFilePaths();
// Gridview adapter
adapter = new GridViewImageAdapter(GridViewActivity.this, imagePaths,
columnWidth);
// setting grid view adapter
gridView.setAdapter(adapter);
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppConstant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((getScreenWidth() - ((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding,
(int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
}
/*
* Reading file paths from SDCard // Utils
*/
public ArrayList<String> getFilePaths() {
ArrayList<String> filePaths = new ArrayList<String>();
String folder = getIntent().getStringExtra("folder");
File directory = new File(
android.os.Environment.getExternalStorageDirectory()
+ File.separator + folder);
// check for directory
if (directory.isDirectory()) {
// getting list of file paths
File[] listFiles = directory.listFiles();
// Check for count
if (listFiles.length > 0) {
// loop through all files
for (int i = 0; i < listFiles.length; i++) {
// get file path
String filePath = listFiles[i].getAbsolutePath();
// check for supported file extension
if (IsSupportedFile(filePath)) {
// Add image path to array list
filePaths.add(filePath);
}
}
} else {
// image directory is empty
Toast.makeText(
mContext,
folder
+ " is empty. Please load some images in it !",
Toast.LENGTH_LONG).show();
}
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(mContext);
alert.setTitle("Error!");
alert.setMessage(folder
+ " directory path is not valid! Please set the image directory name AppConstant.java class");
alert.setPositiveButton("OK", null);
alert.show();
}
return filePaths;
}
/*
* Check supported file extensions
*
* #returns boolean
*/
private boolean IsSupportedFile(String filePath) {
String ext = filePath.substring((filePath.lastIndexOf(".") + 1),
filePath.length());
if (AppConstant.FILE_EXTN
.contains(ext.toLowerCase(Locale.getDefault())))
return true;
else
return false;
}
/*
* getting screen width
*/
#SuppressLint("NewApi")
public int getScreenWidth() {
int columnWidth;
WindowManager wm = (WindowManager) mContext
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
final Point point = new Point();
try {
display.getSize(point);
} catch (java.lang.NoSuchMethodError ignore) { // Older device
point.x = display.getWidth();
point.y = display.getHeight();
}
columnWidth = point.x;
return columnWidth;
}
}
Now Once I click on an image thumbnail my (FullScreenView Activity) cannot pickup the folder names so I can display the Image in Fullscreen mode.
FullScreenViewActivity.java
package info.androidhive.imageslider;
import info.androidhive.imageslider.adapter.FullScreenImageAdapter;
//import info.androidhive.imageslider.helper.Utils;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
public class FullScreenViewActivity extends Activity{
private GridViewActivity gv;
private FullScreenImageAdapter adapter;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_view);
viewPager = (ViewPager) findViewById(R.id.pager);
//utils = new GridViewActivity(getApplicationContext());
Intent i = getIntent();
int position = i.getIntExtra("position", 0);
adapter = new FullScreenImageAdapter(FullScreenViewActivity.this,
gv.getFilePaths());
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(position);
}
}
I want to know how can I receive the file parameters in my FullScreenActivity?

You can use
intent.putStringArrayListExtra("paths", getFilePaths());
when you go from GridViewActivity to FullScreenViewActivity and in onCreate of FullScreenViewActivity you can do
ArrayList<String> paths = getIntent().getStringArrayListExtra("paths");
which will give you the paths of the images

Related

how to show at top last saved photo?

how to show at first (top) of last saved photo ?
i want to show last saved photo as first in custom gallery
i am using universal image loader library
java file
i able to get all images but cant able to get last image as first
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.pmb.lovephotoframe.R;
import java.io.File;
import java.util.ArrayList;
public class CustomGallery extends ActionBarActivity {
ArrayList<String> f = new ArrayList<String>();// list of file paths
File[] listFile;
String applicationname = "Love Photo Frame";
ImageView backmain, backhome;
DisplayImageOptions options;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_gallery);
getSupportActionBar().setTitle("Greeting Cards");
final android.support.v7.app.ActionBar actionBar1 = getSupportActionBar();
final android.support.v7.app.ActionBar actionBar = getSupportActionBar();
actionBar.setCustomView(R.layout.custom_gallry_actionbar);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ed145b")));
applicationname = "Love Photo Frame";
// getFromSdcard();
initImageLoader(getApplicationContext());
options = new DisplayImageOptions.Builder()
.showImageOnLoading(Color.TRANSPARENT)
.showImageForEmptyUri(Color.GREEN).showImageOnFail(Color.BLACK)
.cacheInMemory(true).cacheOnDisc(true)
.bitmapConfig(Bitmap.Config.RGB_565).build();
GridView imagegrid = (GridView) findViewById(R.id.gridView1);
CustomAdapter adapter = new CustomAdapter(this, getfromcard());
imagegrid.setAdapter(adapter);
DisplayImage.grid = imagegrid;
imagegrid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent i = new Intent(getApplicationContext(), DisplayImage.class);
CustomAdapter c = new CustomAdapter(getApplicationContext(), getfromcard());
i.putExtra("imageID", c.getItem(position));
startActivity(i);
finish();
}
});
backmain = (ImageView) findViewById(R.id.back_main);
backhome = (ImageView) findViewById(R.id.back_home);
backmain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent b1 = new Intent(getApplicationContext(), MainActivity.class);
b1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(b1);
}
});
backhome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent b1 = new Intent(getApplicationContext(), MainActivity.class);
b1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(b1);
}
});
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent b1 = new Intent(getApplicationContext(), MainActivity.class);
b1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(b1);
}
#SuppressWarnings("deprecation")
public static void initImageLoader(Context context) {
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
context).threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO).build();
ImageLoader.getInstance().init(config);
}
public ArrayList<String> getfromcard() {
Toast.makeText(getApplicationContext(), "Method Called", Toast.LENGTH_LONG).show();
File file = new File(
android.os.Environment.getExternalStorageDirectory(),
applicationname);
File[] sortedByDate = file.listFiles();
if (sortedByDate != null && sortedByDate.length > 1) {
Arrays.sort(sortedByDate, new Comparator<File>() {
#Override
public int compare(File object1, File object2) {
return (int) ((object1.lastModified() > object2.lastModified()) ? object1.lastModified() : object2.lastModified());
}
});
sortedByDate = file.listFiles();
for (int i = 0; i < sortedByDate.length; i++) {
f1.add(sortedByDate[i].getAbsolutePath());
}
}
return f1;
}
/*
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.custom_gallery, 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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}*/
}

Bitmap value inside Fragment class

I am trying to get the bitmap of my mImageView in a Fragment class.
I notices that I can see the correct drawables, but bitmap is only created sometimes, while most often is Null.
Here is the code:
package com.example.android.displayingbitmaps.ui;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.android.displayingbitmaps.R;
import com.example.android.displayingbitmaps.util.ImageFetcher;
import com.example.android.displayingbitmaps.util.ImageWorker;
import com.example.android.displayingbitmaps.util.Utils;
/**
* This fragment will populate the children of the ViewPager from {#link ImageDetailActivity}.
*/
public class ImageDetailFragment extends Fragment {
private static final String IMAGE_DATA_EXTRA = "extra_image_data";
private String mImageUrl;
private ImageView mImageView;
private ImageFetcher mImageFetcher;
/**
* Factory method to generate a new instance of the fragment given an image number.
*
* #param imageUrl The image url to load
* #return A new instance of ImageDetailFragment with imageNum extras
*/
public static ImageDetailFragment newInstance(String imageUrl) {
final ImageDetailFragment f = new ImageDetailFragment();
final Bundle args = new Bundle();
args.putString(IMAGE_DATA_EXTRA, imageUrl);
f.setArguments(args);
return f;
}
/**
* Empty constructor as per the Fragment documentation
*/
public ImageDetailFragment() {}
/**
* Populate image using a url from extras, use the convenience factory method
* {#link ImageDetailFragment#newInstance(String)} to create this fragment.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mImageUrl = getArguments() != null ? getArguments().getString(IMAGE_DATA_EXTRA) : null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate and locate the main ImageView
final View v = inflater.inflate(R.layout.image_detail_fragment, container, false);
mImageView = (ImageView) v.findViewById(R.id.imageView);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Use the parent activity to load the image asynchronously into the ImageView (so a single
// cache can be used over all pages in the ViewPager
if (ImageDetailActivity.class.isInstance(getActivity())) {
mImageFetcher = ((ImageDetailActivity) getActivity()).getImageFetcher();
mImageFetcher.loadImage(mImageUrl, mImageView);
BitmapDrawable drawable = (BitmapDrawable) mImageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
Toast.makeText(getActivity(), "Drawable is: "+drawable,Toast.LENGTH_SHORT).show(); }
// Pass clicks on the ImageView to the parent activity to handle
if (OnClickListener.class.isInstance(getActivity()) && Utils.hasHoneycomb()) {
mImageView.setOnClickListener((OnClickListener) getActivity());
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mImageView != null) {
// Cancel any pending image work
ImageWorker.cancelWork(mImageView);
mImageView.setImageDrawable(null);
}
}
}
FragmentActivity class
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.android.displayingbitmaps.BuildConfig;
import com.example.android.displayingbitmaps.R;
import com.example.android.displayingbitmaps.provider.Images;
import com.example.android.displayingbitmaps.util.ImageCache;
import com.example.android.displayingbitmaps.util.ImageFetcher;
import com.example.android.displayingbitmaps.util.Utils;
public class ImageDetailActivity extends FragmentActivity implements OnClickListener {
private static final String IMAGE_CACHE_DIR = "images";
public static final String EXTRA_IMAGE = "extra_image";
private ImagePagerAdapter mAdapter;
private ImageFetcher mImageFetcher;
private ViewPager mPager;
private ImageView mImageView;
#TargetApi(VERSION_CODES.HONEYCOMB)
#Override
public void onCreate(Bundle savedInstanceState) {
if (BuildConfig.DEBUG) {
Utils.enableStrictMode();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.image_detail_pager);
// Fetch screen height and width, to use as our max size when loading images as this
// activity runs full screen
final DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
final int height = displayMetrics.heightPixels;
final int width = displayMetrics.widthPixels;
// For this sample we'll use half of the longest width to resize our images. As the
// image scaling ensures the image is larger than this, we should be left with a
// resolution that is appropriate for both portrait and landscape. For best image quality
// we shouldn't divide by 2, but this will use more memory and require a larger memory
// cache.
final int longest = (height > width ? height : width) / 2;
ImageCache.ImageCacheParams cacheParams =
new ImageCache.ImageCacheParams(this, IMAGE_CACHE_DIR);
cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 25% of app memory
// The ImageFetcher takes care of loading images into our ImageView children asynchronously
mImageFetcher = new ImageFetcher(this, longest);
mImageFetcher.addImageCache(getSupportFragmentManager(), cacheParams);
mImageFetcher.setImageFadeIn(false);
// Set up ViewPager and backing adapter
mAdapter = new ImagePagerAdapter(getSupportFragmentManager(), Images.imageUrls.length);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.setPageMargin((int) getResources().getDimension(R.dimen.horizontal_page_margin));
mPager.setOffscreenPageLimit(2);
// Set up activity to go full screen
getWindow().addFlags(LayoutParams.FLAG_FULLSCREEN);
// Enable some additional newer visibility and ActionBar features to create a more
// immersive photo viewing experience
if (Utils.hasHoneycomb()) {
final ActionBar actionBar = getActionBar();
// Hide title text and set home as up
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
// Hide and show the ActionBar as the visibility changes
mPager.setOnSystemUiVisibilityChangeListener(
new View.OnSystemUiVisibilityChangeListener() {
#Override
public void onSystemUiVisibilityChange(int vis) {
if ((vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
actionBar.hide();
} else {
actionBar.show();
}
}
});
// Start low profile mode and hide ActionBar
mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
actionBar.hide();
}
// Set the current item based on the extra passed in to this activity
final int extraCurrentItem = getIntent().getIntExtra(EXTRA_IMAGE, -1);
if (extraCurrentItem != -1) {
mPager.setCurrentItem(extraCurrentItem);
}
}
#Override
public void onResume() {
super.onResume();
mImageFetcher.setExitTasksEarly(false);
}
#Override
protected void onPause() {
super.onPause();
mImageFetcher.setExitTasksEarly(true);
mImageFetcher.flushCache();
}
#Override
protected void onDestroy() {
super.onDestroy();
mImageFetcher.closeCache();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.clear_cache:
mImageFetcher.clearCache();
Toast.makeText(
this, R.string.clear_cache_complete_toast,Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
/**
* Called by the ViewPager child fragments to load images via the one ImageFetcher
*/
public ImageFetcher getImageFetcher() {
return mImageFetcher;
}
/**
* The main adapter that backs the ViewPager. A subclass of FragmentStatePagerAdapter as there
* could be a large number of items in the ViewPager and we don't want to retain them all in
* memory at once but create/destroy them on the fly.
*/
private class ImagePagerAdapter extends FragmentStatePagerAdapter {
private final int mSize;
public ImagePagerAdapter(FragmentManager fm, int size) {
super(fm);
mSize = size;
}
#Override
public int getCount() {
return mSize;
}
#Override
public Fragment getItem(int position) {
return ImageDetailFragment.newInstance(Images.imageUrls[position]);
}
}
/**
* Set on the ImageView in the ViewPager children fragments, to enable/disable low profile mode
* when the ImageView is touched.
*/
#TargetApi(VERSION_CODES.HONEYCOMB)
#Override
public void onClick(View v) {
final int vis = mPager.getSystemUiVisibility();
//Toast.makeText(this, "Value is: " + ,Toast.LENGTH_SHORT).show();
if ((vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
} else {
mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
}
}
}
As you can see I put a Toast that show me this:
When Toast is Drawable:
When Toast is Bitmap, shows bitmap null sometimes for same image (as I swipe back and forward through the gallery):
Bitmap not null on same image:
I am using an AVD image of Android M 6.0

AppCompatCallback error on setSupportActionBar

In this activity I have an implementaion with AppCompatCallback and a delegate who set my toolbar , I have this thing for other 2 activitys and works fine , but here i get an error to the line delegate1.setSupportActionBar(toolbar).. I don't understand why...
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatCallback;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
public class AlbumActivity extends Activity implements AppCompatCallback {
private final int REQUEST_CODE_CAMERA_IMAGE = 1000;
private final int REQUEST_CODE_EXTERNAL_IMAGE = 2000;
private AppCompatDelegate delegate1;
String nameAlbum;
// Declare variables
private String[] FilePathStrings;
private String[] FileNameStrings;
private File[] listFile;
GridView grid;
GridViewAdapter adapter;
File file;
boolean deleted;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
delegate1 = AppCompatDelegate.create(this, this);
//call the onCreate() of the AppCompatDelegate
delegate1.onCreate(savedInstanceState);
//use the delegate to inflate the layout
delegate1.setContentView(R.layout.album_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.mytoolbarr);
delegate1.setSupportActionBar(toolbar);
delegate1.setTitle("Your Pictures");
Button btnChoosePicture = (Button) findViewById(R.id.addimage);
Intent intent = getIntent();
nameAlbum = intent.getStringExtra("nameAlbum");
// Check for SD Card
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Toast.makeText(this, "Error! No SDCARD Found!", Toast.LENGTH_LONG)
.show();
} else {
// Locate the image folder in your SD Card
file = new File(Environment.getExternalStorageDirectory()
+ File.separator + nameAlbum);
if (file.isDirectory()) {
listFile = file.listFiles();
// Create a String array for FilePathStrings
FilePathStrings = new String[listFile.length];
// Create a String array for FileNameStrings
FileNameStrings = new String[listFile.length];
for (int i = 0; i < listFile.length; i++) {
// Get the path of the image file
FilePathStrings[i] = listFile[i].getAbsolutePath();
// Get the name image file
FileNameStrings[i] = listFile[i].getName();
}
}
// Locate the GridView in gridview_main.xml
grid = (GridView) findViewById(R.id.gridview);
// Pass String arrays to LazyAdapter Class
adapter = new GridViewAdapter(this, FilePathStrings, FileNameStrings);
// Set the LazyAdapter to the GridView
grid.setAdapter(adapter);
// Capture gridview item click
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(AlbumActivity.this, ViewImage.class);
// Pass String arrays FilePathStrings
i.putExtra("filepath", FilePathStrings);
// Pass String arrays FileNameStrings
i.putExtra("filename", FileNameStrings);
// Pass click position
i.putExtra("position", position);
startActivity(i);
}
});
grid.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, final View view, final int position, final long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(AlbumActivity.this);
builder.setCancelable(true);
builder.setMessage("Are you sure you want to delete this picture ?");
builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
File filepath = Environment.getExternalStorageDirectory();
File dir5 = new File(filepath.getAbsolutePath()
+ nameAlbum+FileNameStrings[position]);
File file3 = new File(String.valueOf(dir5));
deleted = file3.delete();
adapter.notifyDataSetChanged();
finish();
startActivity(getIntent());
dialog.dismiss();
}
});
builder.setTitle("Delete Picture");
AlertDialog dialog = builder.create();
dialog.show();
return true;
}
});
}
//select picture from external storage
btnChoosePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// choose picture from gallery
Intent PhotoPickerIntent = new Intent(
Intent.ACTION_PICK);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureDirectoryPath = pictureDirectory.getPath();
Uri data = Uri.parse(pictureDirectoryPath);
PhotoPickerIntent.setDataAndType(data, "image/*");
startActivityForResult(PhotoPickerIntent,
REQUEST_CODE_EXTERNAL_IMAGE);
}
});
}
#Override
but here i get an error to the line delegate1.setSupportActionBar(toolbar)
It can be two differents things :
You've imported android.widget.Toolbar instead of android.support.v7.widget.Toolbar
Your Activity has to extends AppCompatActivity if you want to use setSupportActionBar(toolbar)
If you extends AppCompatActivity you have to use Theme.AppCompat.Light.NoActionBar
#Skizo here everything works fine and extends Activity...
public class EnterDataActivity extends Activity implements AppCompatCallback {
private AppCompatDelegate delegate;
EditText editTextPersonName;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
delegate = AppCompatDelegate.create(this, this);
//call the onCreate() of the AppCompatDelegate
delegate.onCreate(savedInstanceState);
//use the delegate to inflate the layout
delegate.setContentView(R.layout.enter_data);
editTextPersonName = (EditText) findViewById(R.id.et_person_name);
Toolbar toolbar= (Toolbar) findViewById(R.id.mytoolbar2);
delegate.setSupportActionBar(toolbar);
delegate.setTitle("Enter Album Name");
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}else if(id==android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
public void onClickAdd (View btnAdd) {
String personName = editTextPersonName.getText().toString();
if ( personName.length() != 0 ) {
Intent newIntent = getIntent();
newIntent.putExtra("tag_person_name", personName);
this.setResult(RESULT_OK, newIntent);
finish();
}
}
#Override
public void onSupportActionModeStarted(ActionMode mode) {
}
#Override
public void onSupportActionModeFinished(ActionMode mode) {
}
#Nullable
#Override
public ActionMode onWindowStartingSupportActionMode(ActionMode.Callback callback) {
return null;
}
}
I did solved my issue , I had to include my toolbar layout in my activity layout... Thank you everyone for interest in solving my issue!!

Display files on listview with MetaDataRetriver Android

The activity below has an edittext and a search button for the files of Downloads directory,
when I click the button shows me the mp3 files by title in a listview. Now the promblem is that I don't need the edittext and the search button, I want only the listview to show on activity launch. How can I achieve that.
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class DirMusic extends Activity {
ListView listSongs;
ArrayList<Song> songs;
EditText editTitle;
File musicFolder;
LinearLayout songsView;
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// search for songs on restore
searchSongs(null);
}
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_dir_music);
// get the list of files and place them in ListView
listSongs = (ListView) this.findViewById(R.id.listSongs);
editTitle = (EditText) this.findViewById(R.id.editTitle);
songsView = (LinearLayout) this.findViewById(R.id.songsView);
// songsView.setVisibility(View.INVISIBLE);
// songsView.setVisibility(View.VISIBLE);
musicFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
listSongs.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> view, View item,
int position, long id) {
// Play song using built-in audio player
String filename = songs.get(position).getFilename();
Uri audio = Uri.parse("file://" + musicFolder + "/" + filename);
Intent intent = new Intent( Intent.ACTION_VIEW);
intent.setDataAndType(audio, "audio/*");
startActivity(intent);
}
});
}
public void searchSongs(View v) {
bindSongsToListView(musicFolder, editTitle.getText().toString());
if ( songs.size() > 0 )
songsView.setVisibility(View.VISIBLE);
else
songsView.setVisibility(View.INVISIBLE);
}
private void bindSongsToListView(File musicFolder, String title) {
songs = new ArrayList<Song>();
ArrayList<Map<String,String>> songsMap = new ArrayList<Map<String,String>>();
for (File f : musicFolder.listFiles()) {
// get MediaMetaData
MediaMetadataRetriever md = new MediaMetadataRetriever();
md.setDataSource(musicFolder + "/" + f.getName());
int secs = Integer.parseInt(md.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)) / 1000;
int mins= secs / 60;
secs = secs % 60;
String singer = md.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
if ( singer == null || singer.equals(""))
singer = "getSinger";
String songtitle = md.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
if ( songtitle == null )
songtitle = f.getName();
String duration = String.format("%02d:%02d", mins,secs);
if (songtitle.toUpperCase().contains(title.toUpperCase())) {
Song s = new Song();
s.setTitle(songtitle);
s.setFilename(f.getName());
s.setDuration(duration);
s.setSinger(singer);
songs.add(s);
Map<String, String> mapobject = convertSongToMap(s);
songsMap.add(mapobject);
}
}
SimpleAdapter adapter = new SimpleAdapter(this, songsMap, R.layout.song,
new String[] { "title","duration","singer"},
new int[] { R.id.textTitle, R.id.textDuration, R.id.textSinger} );
listSongs.setAdapter(adapter);
}
public Map<String,String> convertSongToMap(Song s) {
HashMap<String, String> map = new HashMap<String,String>();
map.put("title", s.getTitle());
map.put("duration", s.getDuration());
map.put("singer", s.getSinger());
return map;
}
}

Intent to play a video always plays the same one

I am creating an intent to play videos stored in the sdcard. It happens that I play the first one, everything is OK. But when I play another one, it just plays everytime the first one I played. Here is my code:
package com.remote;
import java.io.File;
import java.io.IOException;
import com.remote.R.drawable;
import android.app.Activity;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.VideoView;
public class MyVideos extends Activity{
private String path="/sdcard/Movies/Telmex";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.myvideos);
createLinks(new File(path));
}
public void createLinks(File path)
{
LinearLayout layout = (LinearLayout) findViewById(R.id.myvideoslayout);
if( path.exists() ) {
File[] files = path.listFiles();
for(int i=0; i<files.length; i++)
{
if(files[i].getName().toString().charAt(0)!='.')
{
String videoName;
Button video=new Button(this);
video.setBackgroundColor(2);
video.setTextSize(23);
video.setCompoundDrawablesWithIntrinsicBounds(0,0,drawable.videoicon,0);
videoName=new String(files[i].getName());
video.setText(videoName);
createListener(video,videoName);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
layout.addView(video,p);
}
}
}
}
public void createListener(Button video, final String name)
{
video.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
videoPlayer(path,name,true);
}
});
}
public void videoPlayer(String path, String fileName, boolean autoplay)
{
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
Uri data = Uri.parse(path+"/"+fileName);
intent.setDataAndType(data, "video/mp4");
startActivity(intent);
}
}
Rewrite
I did some digging and wrote the code below, if this has the same problem then it is your external video player not you app.
public class ExampleActivity extends Activity {
// Change this path
private final String path = Environment.getExternalStorageDirectory() + "/android/data/com.example/files/";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File dir = new File(path);
List<String> files = new ArrayList<String>();
Collections.addAll(files, dir.list());
Collections.sort(files);
while(files.get(0).startsWith("."))
files.remove(0);
ListView listView = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, files);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String uri = path + ((TextView) view).getText().toString();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(uri), "video/*");
startActivity(intent);
}
});
}
}
Addition
I'm glad the internal video player works. The reason why it resets is that every time you change orientation the OS destroys and rebuilds your app from scratch... It's the same as if you exited the app by pressing the back button and ran it again. If you are using the tutorial from below, you need to save the video's location in onDestroy() to a class variable and in your onCreate() check to see if that variable has a valid location or just start at the beginning of the video.

Categories

Resources