When i press in "addnew" button, the app crash.
The problem is in this part of code:
Boton cbt = new Boton(bt, "","");
listBts.add(cbt);
SharedPreferences sharedPreferences = getSharedPreferences("Array", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
Type type = new TypeToken<BotonClass>() {
}.getType();
String json = gson.toJson(listBts);
editor.remove("Botones").commit();
editor.putString("Botones", json);
editor.commit();
ALL THE CODE:
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
String Tag;
FlexboxLayout fl;
int w;
int h;
ImageView im;
Button curBt;
Boolean delete;
class Boton{
Button bt;
String path;
String fname;
Boton(Button bt, String path, String fname){
this.bt = bt;
this.path = path;
this.fname = fname;
}
}
ArrayList<Boton> listBts;
ArrayList<BotonClass> listClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Chequear_Permisos();
listBts = new ArrayList<>();
listClass = new ArrayList<>();
fl = findViewById(R.id.fl);
DisplayMetrics dm = this.getResources().getDisplayMetrics();
w = Math.round(dm.widthPixels);
h = Math.round(dm.heightPixels);
cargar_bts_agregados();
im = findViewById(R.id.im);
im.getLayoutParams().width = w;
im.getLayoutParams().height = w/3;
}
void cargar_bts_agregados() {
SharedPreferences sharedPreferences = getSharedPreferences("Array", MODE_PRIVATE);
class Boton{
Button bt;
String path;
String fname;
}
Type type = new TypeToken<List<Boton>>() {
}.getType();
String json = sharedPreferences.getString("Botones", "");
Gson gson = new Gson();
if(gson.fromJson(json,type)!= null)
listBts = gson.fromJson(json, type);
if (listBts != null)
for (int i = 0; i < listBts.size(); i++) {
}
}
void Chequear_Permisos(){
if(ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
if(ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.MANAGE_DOCUMENTS) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.MANAGE_DOCUMENTS}, 1);
}
void config_bt(Button bt, String path, String fname){
bt.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
cargar_cancion(v);
return true;
}
});
bt.getLayoutParams().width = w/2;
bt.getLayoutParams().height = (w/2)/2;
if(fname != "")
bt.setText(fname);
}
public void cargar_cancion(View v){
Tag = v.getTag().toString();
curBt = (Button)v;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent,"Select file or dir"), 1);
setResult(Activity.RESULT_OK);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
class Boton{
Button bt;
String path;
String fname;
}
String path = data.getDataString();
String fname = getFileName(Uri.parse(path));
curBt.setText(fname);
Boton b = new Boton();
/*
b.bt = curBt;
b.path = path;
b.fname = fname;*/
//////lb.get(curBt.getId()).path = path;
//////lb.get(curBt.getId()).fname = fname;
SharedPreferences sharedPreferences = getSharedPreferences("Array", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(listBts);
editor.putString("Botones", json);
editor.commit();
}
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void play(View v){
/*if(Integer.parseInt(v.getTag().toString()) > 8 && delete == true){
String pos = v.getTag().toString();
SharedPreferences shPaths = getSharedPreferences("Paths", MODE_PRIVATE);
SharedPreferences.Editor editPath = shPaths.edit();
SharedPreferences shBts = getSharedPreferences("BtNames", MODE_PRIVATE);
SharedPreferences.Editor editorBts = shBts.edit();
editPath.putString(pos, "deleted");
editorBts.putString(pos, "deleted");
editorBts.commit();
editPath.commit();
Log.d("MESAJE", v.getTag().toString());
Log.d("MESAJE", shPaths.getString(String.valueOf(v.getTag().toString()), "_"));
FlexboxLayout fl = findViewById(R.id.fl);
fl.removeView(v);
delete = false;
}*/
SharedPreferences sharedPreferences = getSharedPreferences("Paths", MODE_PRIVATE);
String filePath = sharedPreferences.getString(v.getTag().toString(), "");
Uri uri = Uri.parse(filePath);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(getRealPathFromURI_API19(this, Uri.parse(filePath)));
mediaPlayer.prepare();
mediaPlayer.start();
Button bt = (Button) v;
bt.setText(getFileName(uri));
} catch (IOException e) {
e.printStackTrace();
//Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
catch (Exception e){
//Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
public String getFileName(Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf('/');
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static String getRealPathFromURI_API19(Context context, Uri uri) {
String filePath = "";
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
} else {
if (Build.VERSION.SDK_INT > 20) {
//getExternalMediaDirs() added in API 21
File extenal[] = context.getExternalMediaDirs();
if (extenal.length > 1) {
filePath = extenal[1].getAbsolutePath();
filePath = filePath.substring(0, filePath.indexOf("Android")) + split[1];
}
}else{
filePath = "/storage/" + type + "/" + split[1];
}
return filePath;
}
} else if (isDownloadsDocument(uri)) {
// DownloadsProvider
final String id = DocumentsContract.getDocumentId(uri);
//final Uri contentUri = ContentUris.withAppendedId(
// Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
String result = cursor.getString(index);
cursor.close();
return result;
}
} finally {
if (cursor != null)
cursor.close();
}
} else if (DocumentsContract.isDocumentUri(context, uri)) {
// MediaProvider
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String[] ids = wholeID.split(":");
String id;
String type;
if (ids.length > 1) {
id = ids[1];
type = ids[0];
} else {
id = ids[0];
type = ids[0];
}
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{id};
final String column = "_data";
final String[] projection = {column};
Cursor cursor = context.getContentResolver().query(contentUri,
projection, selection, selectionArgs, null);
if (cursor != null) {
int columnIndex = cursor.getColumnIndex(column);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
}
return filePath;
} else {
String[] proj = {MediaStore.Audio.Media.DATA};
Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
if (cursor.moveToFirst())
filePath = cursor.getString(column_index);
cursor.close();
}
return filePath;
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public void addnew(Button bt, String fname, String path) {
fl.addView(bt);
config_bt(bt, fname, path);
}
public void addnew(View v){
if(listBts == null)
Log.d("MESAJE", "MMMMMMM");
final Button bt = new Button(this);
bt.setText("Cargar");
bt.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void onClick(View v) {
play(bt);
}
});
bt.setTag(contar_bts());
fl.addView(bt);
/*
BotonClass bbc = new BotonClass(bt, "","");
listClass.add(bbc);
listClass.get(0);
cbt.bt = bt;
cbt.path = "";
cbt.fname = "";*/
Boton cbt = new Boton(bt, "","");
listBts.add(cbt);
SharedPreferences sharedPreferences = getSharedPreferences("Array", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
Type type = new TypeToken<BotonClass>() {
}.getType();
String json = gson.toJson(listBts);
editor.remove("Botones").commit();
editor.putString("Botones", json);
editor.commit();
config_bt(bt,"","");
}
public int contar_bts(){
if(listBts == null || listBts.size() == 0)
return 0;
int c =Integer.parseInt(listBts.get(listBts.size()-1).bt.getTag().toString());
return c;
}
public void Elimnar_bt(View v){
delete = true;
}
}
Related
I want to implement file chooser with camera option.When we select Camera images should be captured and the path of captured image should displayed on textview.and file chooser should be with pdf,word,png and jpeg validation. I tired fileChhoser only but I dont Understand how to implement camera option in that.
The code i have used
ActivityResultLauncher<Intent> sActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#SuppressLint("Range")
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode()== Activity.RESULT_OK){
Intent data = result.getData();
Intent data1 = result.getData();
Uri uri = data.getData();
Uri uri1 = data1.getData();
String uriString = uri.toString();
String uriString1 = uri1.toString();
File myFile = new File(uriString1);
String path = myFile.getAbsolutePath();
String displayName = null;
String displayName1= null;
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = getApplicationContext().getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
// displayName1 = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Log.i("displayname",""+displayName);
fileidname.setText(displayName);
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
// displayName1= myFile.getName();
Log.i("displayname1",""+displayName);
fileidname.setText(displayName);
}
}
}
}
);
ActivityResultLauncher<Intent> sActivityResultLauncher1 = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#SuppressLint("Range")
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode()== Activity.RESULT_OK){
//Intent data = result.getData();
Intent data1 = result.getData();
// Uri uri = data.getData();
Uri uri1 = data1.getData();
// String uriString = uri.toString();
String uriString1 = uri1.toString();
File myFile = new File(uriString1);
String path = myFile.getAbsolutePath();
String displayName = null;
String displayName1= null;
if (uriString1.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = getApplicationContext().getContentResolver().query(uri1, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
// displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
displayName1 = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Log.i("displayname",""+displayName);
fileidname1.setText(displayName1);
}
} finally {
cursor.close();
}
} else if (uriString1.startsWith("file://")) {
//displayName = myFile.getName();
displayName1= myFile.getName();
Log.i("displayname1",""+displayName);
fileidname1.setText(displayName1);
}
}
}
}
);
public void OpenfileDialog(View view) {
Intent data = new Intent(Intent.ACTION_OPEN_DOCUMENT);
data.setType("*/*");
String[] mimeTypes = {"image/*","application/pdf"};
data.putExtra(Intent.EXTRA_MIME_TYPES,mimeTypes);
data = Intent.createChooser(data,"Choose a file");
sActivityResultLauncher.launch(data);
}
public void OpenfileDialog1(View view) {
Intent data = new Intent(Intent.ACTION_OPEN_DOCUMENT);
data.setType("*/*");
String[] mimeTypes = {"image/*","application/pdf"};
data.putExtra(Intent.EXTRA_MIME_TYPES,mimeTypes);
data = Intent.createChooser(data,"Choose a file");
sActivityResultLauncher1.launch(data);
}
public static String getRealPath(Uri uri, Context context) {
File file = new File(uri.getPath());
String[] filePath = file.getPath().split(":");
String fileId = filePath[filePath.length - 1];
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null,
MediaStore.Images.Media._ID + " = ? ",
new String[]{fileId},
null);
if (cursor != null) {
cursor.moveToNext();
int columnIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DATA);
String realPath = cursor.getString(columnIndex);
cursor.close();
return realPath;
}
return null;
}
this is My code ( uri to path )
When bringing up an image, it brings the absolute path well. But when I call the file, I can't call it.
When i called file Like this..
Intent fileChoose = new Intent(Intent.ACTION_OPEN_DOCUMENT);
fileChoose.setType("*/*");
fileChoose.setAction(Intent.ACTION_GET_CONTENT);
fileLauncher.launch(fileChoose);
and Receive Like this..
private final ActivityResultLauncher<Intent> fileLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result != null) {
if (result.getData() != null) {
File file = new File(Objects.requireNonNull(CommFunc.getRealPath(result.getData().getData(), FileChooserActivity.this)));
}
}
}
});
and i called Image Like this..
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
setResult(RESULT_OK, galleryIntent);
galleryLauncher.launch(Intent.createChooser(galleryIntent, "Select Picture"));
i try many way but intent not return path that i want , how can i get absolute path ?
this is which i retrieved
/document/image:29163
code for intent
binding.buttonSetVoiceGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 0);
}
});
when activityresult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {
Log.d(TAG,data.getData().getPath());
}
}
Try this code for getting absolute path:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {
Log.d(TAG,data.getData().getPath());
Object objImg = data.getExtras().get("path");
Log.e("Selected", "" + objImg.toString());
/*--getting image uri from object--*/
Uri selectedImage = Uri.parse(String.valueOf(objImg));
Log.e("Selected Image", "" + selectedImage);
/*--create file object using uri--*/
File myFile = new File(selectedImage.getPath());
String path = myFile.getAbsolutePath();
Log.e("AbsolutePath---", ""+path);
}
}
binding.buttonSetVoiceGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
launcher.launch(intent);
}
});
ActivityResultLauncher<Intent> launcher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK ) {
Intent data = result.getData();
Uri uri= data.getData();
File file = new File(FileMyutils.getPath(getContext(),uri));
}
}
});
public class FileMyutils {
private static final String TAG = "FileUtils";
#WorkerThread
#Nullable
public static String getReadablePathFromUri(Context context, Uri uri) {
String path = null;
if ("file".equalsIgnoreCase(uri.getScheme())) {
path = uri.getPath();
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
path = getPath(context, uri);
}
if (TextUtils.isEmpty(path)) {
return path;
}
Log.d(TAG, "get path from uri: " + path);
if (!isReadablePath(path)) {
int index = path.lastIndexOf("/");
String name = path.substring(index + 1);
String dstPath = context.getCacheDir().getAbsolutePath() + File.separator + name;
if (copyFile(context, uri, dstPath)) {
path = dstPath;
Log.d(TAG, "copy file success: " + path);
} else {
Log.d(TAG, "copy file fail!");
}
}
return path;
}
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
Log.d("External Storage", docId);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
} else if (isDownloadsDocument(uri)) {
String dstPath = context.getCacheDir().getAbsolutePath() + File.separator + getFileName(context,uri);
if (copyFile(context, uri, dstPath)) {
Log.d(TAG, "copy file success: " + dstPath);
return dstPath;
} else {
Log.d(TAG, "copy file fail!");
}
} else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getFileName(Context context, Uri uri) {
Cursor cursor = context.getContentResolver().query(uri,null,null,null,null);
int nameindex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
cursor.moveToFirst();
return cursor.getString(nameindex);
}
private static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
private static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
private static boolean isReadablePath(#Nullable String path) {
if (TextUtils.isEmpty(path)) {
return false;
}
boolean isLocalPath;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (!TextUtils.isEmpty(path)) {
File localFile = new File(path);
isLocalPath = localFile.exists() && localFile.canRead();
} else {
isLocalPath = false;
}
} else {
isLocalPath = path.startsWith(File.separator);
}
return isLocalPath;
}
private static boolean copyFile(Context context, Uri uri, String dstPath) {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = context.getContentResolver().openInputStream(uri);
outputStream = new FileOutputStream(dstPath);
byte[] buff = new byte[100 * 1024];
int len;
while ((len = inputStream.read(buff)) != -1) {
outputStream.write(buff, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return true;
}
}
I'm trying to add a font to a textView. I have the following code-snippet, but I'm not sure how to adapt it to my code below. Can someone help me?
Code snippet I want to integrate into my program:
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/Xcelsion.ttf"); // getActivity().getAssets()
TextView myTextView = (TextView)findViewById(R.id.text_view);
myTextView.setTypeface(myTypeface); //
Program I want to add the font to:
public class ListRingtonesAdapter extends ArrayAdapter<SongInfo> {
private ArrayList<SongInfo> items;
private Context context;
private ArrayList<ViewHolder> listHolder = new ArrayList<ListRingtonesAdapter.ViewHolder>();
private int curPosition = 0;
private RingtonesSharedPreferences pref;
private boolean inRingtones;
static final String TAG = "LOG";
private static final int DEFAULT_RINGTONE = 1;
private static final int ASSIGN_TO_CONTACT = 2;
private static final int DEFAULT_NOTIFICATION = 3;
private static final int DEFAULT_ALARM = 4;
private static final int DELETE_RINGTONE = 5;
public static final String ALARM_PATH = "/media/audio/alarms/";
public static final String ALARM_TYPE = "Alarm";
public static final String NOTIFICATION_PATH = "/media/audio/notifications/";
public static final String NOTIFICATION_TYPE = "Notification";
public static final String RINGTONE_PATH = "/media/audio/ringtones/";
public static final String RINGTONE_TYPE = "Ringtone";
public ListRingtonesAdapter(Context context, int viewResourceId,
ArrayList<SongInfo> objects, boolean inRingtones) {
super(context, viewResourceId, objects);
// TODO Auto-generated constructor stub
this.context = context;
this.items = objects;
this.pref = new RingtonesSharedPreferences(context);
this.inRingtones = inRingtones;
if(Main.mp.isPlaying()){
Main.mp.stop();
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ActionItem defRingtone = new ActionItem(DEFAULT_RINGTONE,
"Default Ringtone", context.getResources().getDrawable(
R.drawable.icon_ringtone));
ActionItem assign = new ActionItem(ASSIGN_TO_CONTACT,
"Contact Ringtone", context.getResources().getDrawable(
R.drawable.icon_contact));
ActionItem defNotifi = new ActionItem(DEFAULT_NOTIFICATION,
"Default Notification", context.getResources().getDrawable(
R.drawable.icon_notify));
ActionItem defAlarm = new ActionItem(DEFAULT_ALARM, "Default Alarm",
context.getResources().getDrawable(R.drawable.icon_alarm));
final QuickAction mQuickAction = new QuickAction(context);
mQuickAction.addActionItem(defRingtone);
mQuickAction.addActionItem(assign);
mQuickAction.addActionItem(defNotifi);
mQuickAction.addActionItem(defAlarm);
// setup the action item click listener
mQuickAction
.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
#Override
public void onItemClick(QuickAction quickAction, int pos,
int actionId) {
switch (actionId) {
case DEFAULT_RINGTONE:
setDefaultRingtone(items.get(curPosition));
Toast.makeText(context,
"Ringtone set successfully",
Toast.LENGTH_LONG).show();
break;
case ASSIGN_TO_CONTACT:
Intent intent = new Intent(context,
SelectContactActivity.class);
intent.putExtra("position", curPosition);
context.startActivity(intent);
break;
case DEFAULT_ALARM:
setDefaultAlarm(items.get(curPosition));
Toast.makeText(context,
"Alarm set successfully",
Toast.LENGTH_LONG).show();
break;
case DEFAULT_NOTIFICATION:
setDefaultNotice(items.get(curPosition));
Toast.makeText(context,
"Notification set successfully",
Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
});
// setup on dismiss listener, set the icon back to normal
mQuickAction.setOnDismissListener(new PopupWindow.OnDismissListener() {
#Override
public void onDismiss() {
}
});
View view = null;
if (convertView == null) {
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.listelement, null);
final ViewHolder holder = new ViewHolder();
holder.txtName = (TextView) view.findViewById(R.id.txtSongName);
holder.btnFavorite = (ImageView) view.findViewById(R.id.btnFavorite);
holder.btnPlayPause = (ImageView) view.findViewById(R.id.btnPlayPause);
view.setTag(holder);
} else {
view = convertView;
// holder = (ViewHolder) view.getTag();
}
final SongInfo item = items.get(position);
if (item != null) {
final ViewHolder holder = (ViewHolder) view.getTag();
holder.txtName.setText(item.getName())
;
if (item.isFavorite()) {
holder.btnFavorite.setBackgroundResource(R.drawable.icon_favorite);
} else {
holder.btnFavorite.setBackgroundResource(R.drawable.icon_favorite_off);
}
if (!item.isPlaying()) {
holder.btnPlayPause.setBackgroundResource(R.drawable.icon_play);
} else {
holder.btnPlayPause.setBackgroundResource(R.drawable.icon_pause);
}
holder.btnPlayPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (Main.mp.isPlaying()) {
Main.mp.stop();
}
for(int i = 0; i < items.size(); i++){
if(items.get(i) != item)
items.get(i).setPlaying(false);
}
for(int i = 0; i < listHolder.size(); i++){
listHolder.get(i).btnPlayPause.setBackgroundResource(R.drawable.icon_play);
}
if (item.isPlaying()) {
holder.btnPlayPause.setBackgroundResource(R.drawable.icon_play);
item.setPlaying(false);
items.get(position).setPlaying(false);
if (Main.mp.isPlaying()) {
Main.mp.stop();
}
} else {
curPosition = position;
playAudio(context, item.getAudioResource());
holder.btnPlayPause.setBackgroundResource(R.drawable.icon_pause);
item.setPlaying(true);
items.get(position).setPlaying(true);
}
for (ViewHolder object : listHolder) {
if (object != holder) {
object.btnPlayPause.setBackgroundResource(R.drawable.icon_play);
}
}
}
});
holder.btnFavorite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (item.isFavorite()) {
holder.btnFavorite
.setBackgroundResource(R.drawable.icon_favorite_off);
item.setFavorite(false);
pref.setString(item.getFileName(), false);
if (!inRingtones) {
Intent broadcast = new Intent();
broadcast.setAction("REMOVE_SONG");
context.sendBroadcast(broadcast);
}
} else {
holder.btnFavorite
.setBackgroundResource(R.drawable.icon_favorite);
item.setFavorite(true);
pref.setString(item.getFileName(), true);
}
}
});
listHolder.add(holder);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mQuickAction.show(v);
curPosition = position;
}
});
}
return view;
}
private Object getAssets() {
// TODO Auto-generated method stub
return null;
}
private TextView findViewById(int txtsongname)
{
// TODO Auto-generated method stub
return null;
}
static class ViewHolder {
private TextView txtName;
private ImageView btnFavorite;
private ImageView btnPlayPause;
}
private void playAudio(Context context, int id) {
if (Main.mp.isPlaying()) {
Main.mp.stop();
}
Main.mp = MediaPlayer.create(context, id);
Main.mp.setOnCompletionListener(playCompletionListener);
Main.mp.start();
onRingtonePlay.onPlay();
}
private OnCompletionListener playCompletionListener = new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
for(int i = 0; i < items.size(); i++){
items.get(i).setPlaying(false);
}
for(int i = 0; i < listHolder.size(); i++){
listHolder.get(i).btnPlayPause
.setBackgroundResource(R.drawable.icon_play);
}
}
};
private void setRingtone(SongInfo info, boolean ringtone, boolean alarm,
boolean music, boolean notification) {
File dir = null;
String what = null;
if (ringtone) {
what = "Ringtones";
}else if(alarm){
what = "alarms";
}else if(notification){
what = "notifications";
}else{
what = "Ringtones";
}
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),what);
} else {
dir = context.getCacheDir();
}
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, info.getFileName());
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
InputStream inputStream = context.getResources()
.openRawResource(info.getAudioResource());
OutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
Uri uri = MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath());
String[] projection = new String[] { MediaStore.MediaColumns.DATA,
MediaStore.Audio.Media.IS_RINGTONE,
MediaStore.Audio.Media.IS_ALARM,
MediaStore.Audio.Media.IS_MUSIC,
MediaStore.Audio.Media.IS_NOTIFICATION
};
Cursor c = context.getContentResolver().query(uri,projection,MediaStore.MediaColumns.DATA + " = \"" + file.getAbsolutePath()+ "\"", null, null);
String strRingtone = null, strAlarm = null, strNotifi = null, strMusic = null;
while (c.moveToNext()) {
strRingtone = c.getString(c
.getColumnIndex(MediaStore.Audio.Media.IS_RINGTONE));
strAlarm = c.getString(c
.getColumnIndex(MediaStore.Audio.Media.IS_ALARM));
strNotifi = c.getString(c
.getColumnIndex(MediaStore.Audio.Media.IS_NOTIFICATION));
strMusic = c.getString(c
.getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));
}
if (ringtone) {
if ((strAlarm != null) && (strAlarm.equals("1")))
alarm = true;
if ((strNotifi != null) && (strNotifi.equals("1")))
notification = true;
if ((strMusic != null) && (strMusic.equals("1")))
music = true;
} else if (notification) {
if ((strAlarm != null) && (strAlarm.equals("1")))
alarm = true;
if ((strRingtone != null) && (strRingtone.equals("1")))
ringtone = true;
if ((strMusic != null) && (strMusic.equals("1")))
music = true;
} else if (alarm) {
if ((strNotifi != null) && (strNotifi.equals("1")))
notification = true;
if ((strRingtone != null) && (strRingtone.equals("1")))
ringtone = true;
if ((strMusic != null) && (strMusic.equals("1")))
music = true;
} else if (music) {
if ((strNotifi != null) && (strNotifi.equals("1")))
notification = true;
if ((strRingtone != null) && (strRingtone.equals("1")))
ringtone = true;
if ((strAlarm != null) && (strAlarm.equals("1")))
alarm = true;
}
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, info.getName());
values.put(MediaStore.MediaColumns.SIZE, file.length());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
if (ringtone) {
values.put(MediaStore.Audio.Media.IS_RINGTONE, ringtone);
} else if (notification) {
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, notification);
} else if (alarm) {
values.put(MediaStore.Audio.Media.IS_ALARM, alarm);
} else if (music) {
values.put(MediaStore.Audio.Media.IS_MUSIC, music);
}
context.getContentResolver().delete(uri,MediaStore.MediaColumns.DATA + " = \"" + file.getAbsolutePath() + "\"", null);
Uri newUri = context.getContentResolver().insert(uri, values);
int type = RingtoneManager.TYPE_ALL;
if (ringtone)
type = RingtoneManager.TYPE_RINGTONE;
if (alarm)
type = RingtoneManager.TYPE_ALARM;
if (notification)
type = RingtoneManager.TYPE_NOTIFICATION;
RingtoneManager.setActualDefaultRingtoneUri(context, type, newUri);
}
private void setDefaultRingtone(SongInfo info) {
File dir = null;
String what = "Ringtones";
Uri newUri = null;
ContentValues values = new ContentValues();
boolean isRingTone = false;
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),what);
} else {
dir = context.getCacheDir();
}
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, info.getFileName());
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
InputStream inputStream = context.getResources()
.openRawResource(info.getAudioResource());
OutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
String[] columns = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.IS_RINGTONE
};
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, MediaStore.Audio.Media.DATA+" = '"+file.getAbsolutePath()+"'",null, null);
if (cursor!=null) {
int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
int fileColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
int ringtoneColumn = cursor.getColumnIndex(MediaStore.Audio.Media.IS_RINGTONE);
while (cursor.moveToNext()) {
String audioFilePath = cursor.getString(fileColumn);
if (cursor.getString(ringtoneColumn)!=null && cursor.getString(ringtoneColumn).equals("1")) {
Uri hasUri = MediaStore.Audio.Media.getContentUriForPath(audioFilePath);
newUri = Uri.withAppendedPath(hasUri, cursor.getString(idColumn));
isRingTone = true;
}
}
cursor.close();
}
if (isRingTone) {
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);
}else{
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, info.getName());
values.put(MediaStore.MediaColumns.SIZE, file.length());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
newUri = context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);
}
}
private void setDefaultAlarm(SongInfo info) {
File dir = null;
String what = "alarms";
Uri newUri = null;
ContentValues values = new ContentValues();
boolean isRingTone = false;
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),what);
} else {
dir = context.getCacheDir();
}
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, info.getFileName());
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
InputStream inputStream = context.getResources()
.openRawResource(info.getAudioResource());
OutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
String[] columns = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.IS_ALARM
};
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, MediaStore.Audio.Media.DATA+" = '"+file.getAbsolutePath()+"'",null, null);
if (cursor!=null) {
int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
int fileColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
int ringtoneColumn = cursor.getColumnIndex(MediaStore.Audio.Media.IS_ALARM);
while (cursor.moveToNext()) {
String audioFilePath = cursor.getString(fileColumn);
if (cursor.getString(ringtoneColumn)!=null && cursor.getString(ringtoneColumn).equals("1")) {
Uri hasUri = MediaStore.Audio.Media.getContentUriForPath(audioFilePath);
newUri = Uri.withAppendedPath(hasUri, cursor.getString(idColumn));
isRingTone = true;
}
}
cursor.close();
}
if (isRingTone) {
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM, newUri);
}else{
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, info.getName());
values.put(MediaStore.MediaColumns.SIZE, file.length());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.IS_ALARM, true);
newUri = context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM, newUri);
}
}
private void setDefaultNotice(SongInfo info) {
File dir = null;
String what = "notifications";
Uri newUri = null;
ContentValues values = new ContentValues();
boolean isRingTone = false;
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),what);
} else {
dir = context.getCacheDir();
}
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, info.getFileName());
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
InputStream inputStream = context.getResources()
.openRawResource(info.getAudioResource());
OutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
String[] columns = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.IS_NOTIFICATION
};
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, MediaStore.Audio.Media.DATA+" = '"+file.getAbsolutePath()+"'",null, null);
if (cursor!=null) {
int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
int fileColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
int ringtoneColumn = cursor.getColumnIndex(MediaStore.Audio.Media.IS_NOTIFICATION);
while (cursor.moveToNext()) {
String audioFilePath = cursor.getString(fileColumn);
if (cursor.getString(ringtoneColumn)!=null && cursor.getString(ringtoneColumn).equals("1")) {
Uri hasUri = MediaStore.Audio.Media.getContentUriForPath(audioFilePath);
newUri = Uri.withAppendedPath(hasUri, cursor.getString(idColumn));
isRingTone = true;
}
}
cursor.close();
}
if (isRingTone) {
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, newUri);
}else{
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, info.getName());
values.put(MediaStore.MediaColumns.SIZE, file.length());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
newUri = context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, newUri);
}
}
private void deleteRingtone(SongInfo info) {
File dir = null;
if (Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),
"Ringtones");
} else {
dir = context.getCacheDir();
}
if (!dir.exists()) {
dir.mkdirs();
}
Log.d(TAG, "dir:"+dir.getPath());
File file = new File(dir, info.getFileName());
Log.d(TAG, "file name:"+info.getFileName());
Uri uri = MediaStore.Audio.Media.getContentUriForPath(file
.getAbsolutePath());
context.getContentResolver().delete(
uri,
MediaStore.MediaColumns.DATA + " = \"" + file.getAbsolutePath()
+ "\"", null);
if (file.exists()) {
file.delete();
}
}
OnRingtonePlay onRingtonePlay;
/**
* #param onRingtonePlay the onRingtonePlay to set
*/
public void setOnRingtonePlay(OnRingtonePlay onRingtonePlay) {
this.onRingtonePlay = onRingtonePlay;
}
interface OnRingtonePlay{
public void onPlay();
}
}
/* Set Font Method */
public static void overrideFonts(final Context context, final View v) {
try {
if (v instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) v;
for (int i = 0; i < vg.getChildCount(); i++) {
View child = vg.getChildAt(i);
overrideFonts(context, child);
}
} else if (v instanceof TextView) {
((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/Xcelsion.ttf"));
}
} catch (Exception ignored) {
}
}
/* And use this method as below */
overrideFonts(context, myTextView);
Put typeface coding in getView(final int position, View convertView, ViewGroup parent) method in this part of your code
View view = null;
if (convertView == null) {
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.listelement, null);
final ViewHolder holder = new ViewHolder();
holder.txtName = (TextView) view.findViewById(R.id.txtSongName);
holder.btnFavorite = (ImageView) view.findViewById(R.id.btnFavorite);
holder.btnPlayPause = (ImageView) view.findViewById(R.id.btnPlayPause);
Typeface myTypeface = Typeface.createFromAsset(context.getAssets(), "fonts/Xcelsion.ttf");
holder.txtName.setTypeface(myTypeface);
view.setTag(holder);
} else {
view = convertView;
// holder = (ViewHolder) view.getTag();
}
i found a code about gallery picker and it pick photos from google images. But i want to pick photos from normal gallery. Here is the code :
public class ImageCrop {
private static final String TAG = "ImageCrop";
private static final boolean REMOVE_TEMP_FILE = true;
private static final boolean DEBUG = false;
Context context;
public static final int PICK_FROM_CAMERA = 0;
public static final int PICK_FROM_ALBUM = 1;
public static final int PERMISSION_FROM_CAMERA = 3;
private static final int PHOTO_SIZE = 1000;
private static final String ACTIVITY_NAME_PHOTOS = "com.google.android.apps.photos";
private static final String ACTIVITY_NAME_PLUS = "com.google.android.apps.plus";
private static boolean mUseActivityPhoto = false;
private static boolean mUseActivityPlus = false;
private static Uri mImageCaptureUri;
private static Bitmap mCropBitmap;
private static String mTempImagePath;
private static int mLastAction = PICK_FROM_CAMERA;
private static final String CAMERA_TEMP_PREFIX = "camera_";
private static final String CROP_TEMP_PREFIX = "crop_";
private static final String IMAGE_EXT = ".png";
public static void checkPackages(Activity context, Intent intentPhoto) {
final PackageManager pm = context.getPackageManager();
final Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
mUseActivityPhoto = false;
mUseActivityPlus = false;
final List<ResolveInfo> infos = pm.queryIntentActivities(intent, PackageManager.MATCH_ALL);
for (ResolveInfo info : infos) {
if(info.activityInfo.packageName.equals(ACTIVITY_NAME_PHOTOS)) {
final List<ResolveInfo> photoInfos = pm.queryIntentActivities(intentPhoto, PackageManager.MATCH_ALL);
for (ResolveInfo photoInfo : photoInfos) {
if(photoInfo.activityInfo.packageName.equals(ACTIVITY_NAME_PHOTOS)) {
Log.d(TAG,"mUseActivityPhoto TRUE");
mUseActivityPhoto = true;
break;
}
}
}
else if(info.activityInfo.packageName.equals(ACTIVITY_NAME_PLUS)) {
final List<ResolveInfo> photoInfos = pm.queryIntentActivities(intentPhoto, PackageManager.MATCH_ALL);
for (ResolveInfo photoInfo : photoInfos) {
if(photoInfo.activityInfo.packageName.equals(ACTIVITY_NAME_PLUS)) {
Log.d(TAG,"mUseActivityPlus TRUE");
mUseActivityPlus = true;
break;
}
}
}
}
}
public static void takeCameraAction(Activity context) {
if(DEBUG)
Log.d(TAG, "takeCameraAction");
if (ImageCrop.checkPermissions(context)) {
ImageCrop.doTakeCameraAction(context);
} else {
mLastAction = ImageCrop.PICK_FROM_CAMERA;
}
}
public static void takeAlbumAction(Activity context) {
if(DEBUG)
Log.d(TAG, "takeAlbumAction");
if(ImageCrop.checkPermissions(context)) {
ImageCrop.doTakeAlbumAction(context);
}
else {
mLastAction = ImageCrop.PICK_FROM_ALBUM;
}
}
private static void doTakeCameraAction(Activity context) {
if(DEBUG)
Log.d(TAG, "doTakeCameraAction");
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final String url = CAMERA_TEMP_PREFIX + String.valueOf(System.currentTimeMillis()) + IMAGE_EXT;
final File file = new File(Environment.getExternalStorageDirectory(), url);
mTempImagePath = file.getAbsolutePath();
mImageCaptureUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
context.startActivityForResult(intent, PICK_FROM_CAMERA);
}
private static void doTakeAlbumAction(Activity context) {
if(DEBUG)
Log.d(TAG, "doTakeAlbumAction");
final Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(MediaStore.Images.Media.CONTENT_TYPE);
checkPackages(context, intent);
if(mUseActivityPhoto) {
if(DEBUG)
Log.d(TAG, "doTakeAlbumAction setPackage ACTIVITY_NAME_PHOTOS");
intent.setPackage(ACTIVITY_NAME_PHOTOS);
}
else if(mUseActivityPlus) {
if(DEBUG)
Log.d(TAG, "doTakeAlbumAction setPackage ACTIVITY_NAME_PLUS");
intent.setPackage(ACTIVITY_NAME_PLUS);
}
context.startActivityForResult(intent, ImageCrop.PICK_FROM_ALBUM);
}
private static void removeTempFile() {
// 캡쳐 파일 삭제
if(mImageCaptureUri != null) {
final String capturePath = mImageCaptureUri.getPath();
if(capturePath != null) {
Log.w(TAG, "removeTempFile capturePath=" + capturePath);
final File captureFile = new File(capturePath);
if(captureFile != null) {
if (captureFile.getAbsoluteFile().exists()) {
captureFile.delete();
}
}
}
}
if(mTempImagePath != null) {
Log.w(TAG, "removeTempFile mTempImagePath=" + mTempImagePath);
final File tempFile = new File(mTempImagePath);
if(tempFile != null) {
if(tempFile.getAbsoluteFile().exists()) {
tempFile.delete();
}
}
}
}
private static void removeDataFile(Intent data) {
if(data == null) {
Log.w(TAG, "removeDataFile data == null");
return;
}
if(data.getData() == null) {
Log.w(TAG, "removeDataFile data.getData() == null");
return;
}
final String dataPath = data.getData().getPath();
if(dataPath == null) {
Log.w(TAG, "removeDataFile dataPath == null");
return;
}
Log.w(TAG, "removeDataFile dataPath=" + dataPath);
final File dataFile = new File(dataPath);
if(dataFile == null) {
Log.w(TAG, "removeDataFile dataFile == null");
return;
}
if(dataFile.getAbsoluteFile().exists()) {
dataFile.delete();
}
}
private static File cropFileFromPhotoData(Activity context, Intent data) {
if(DEBUG)
Log.d(TAG, "cropFileFromPhotoData");
if(data.getData() == null) {
Log.e(TAG, "cropFileFromPhotoData data.getData() == null");
return null;
}
final String dataPath = data.getData().getPath();
if (dataPath == null) {
Log.e(TAG, "cropFileFromPhotoData dataPath == null");
return null;
}
File dataFile = null;
if(dataPath.startsWith("/external")) {
final Uri dataUri = Uri.parse("content://media"+dataPath);
final String dataFilePath = getRealPathFromURI(context, dataUri);
dataFile = new File(dataFilePath);
boolean exist = dataFile.exists();
long length = dataFile.length();
if(DEBUG)
Log.d(TAG, "cropFileFromPhotoData dataFilePath=" + dataFilePath + " exist="+exist + " length=" +length);
}
else {
dataFile = new File(dataPath);
boolean exist = dataFile.exists();
long length = dataFile.length();
if(DEBUG)
Log.d(TAG, "cropFileFromPhotoData dataPath=" + dataPath + " exist="+exist + " length=" +length);
}
return dataFile;
}
public static void pickFromCamera(Activity context, Intent data) {
if(DEBUG)
Log.d(TAG, "pickFromCamera => launchCropActivity");
if(mTempImagePath == null || mTempImagePath.isEmpty()) {
Log.e(TAG, "pickFromCamera mTempImagePath error");
return;
}
}
public static String getRealPathFromURI(Activity context, Uri contentUri) {
Cursor cursor = null;
final String[] proj = { MediaStore.Images.Media.DATA };
String ret = null;
try {
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
final int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
ret = cursor.getString(column_index);
}
catch(Exception e) {
Log.e(TAG, "getRealPathFromURI exception");
return null;
}
if (cursor != null) {
cursor.close();
}
return ret;
}
if(readEnable && writeEnable && cameraEnable) {
switch(mLastAction) {
case ImageCrop.PICK_FROM_CAMERA:
if(DEBUG)
Log.d(TAG, "doTakeCameraAction");
ImageCrop.doTakeCameraAction(context);
break;
case ImageCrop.PICK_FROM_ALBUM:
if(DEBUG)
Log.d(TAG, "doTakeAlbumAction");
ImageCrop.doTakeAlbumAction(context);
break;
}
}
}
}
I want to use this way to pick photos:
private void selectCover() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, getText(R.string.label_select_img)), SELECT_COVER);
}
But i can't convert this to normal gallery. How to solve this? Thanks
You can use this, it will open only Gallery :
public void handleGallery(){
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, REQUEST_CODE_GALLERY);
}
public void handleCamera(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
} catch (Exception e) {
Log.d("error", "cannot take picture", e);
}
}
Then onActivityResult :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
Bitmap bitmap;
switch (requestCode) {
case REQUEST_CODE_GALLERY:
try {
Uri uri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
Bitmap bitmapScaled = Bitmap.createScaledBitmap(bitmap, 800, 800, true);
Drawable drawable=new BitmapDrawable(bitmapScaled);
mImage.setImageDrawable(drawable);
mImage.setVisibility(View.VISIBLE);
mImageString=HelperUtils.encodeTobase64(bitmap);
} catch (IOException e) {
Log.v("galeri", "hata var : "+e.getMessage());
}
} catch (Exception e) {
Log.v("kamera", "hata var : "+e.getMessage());
}
break;
case REQUEST_CODE_TAKE_PICTURE:
bitmap = (Bitmap) data.getExtras().get("data");
mImage.setImageBitmap(bitmap);
mImage.setVisibility(View.VISIBLE);
mImageString=HelperUtils.encodeTobase64(bitmap);
break;
}
super.onActivityResult(requestCode, resultCode, data);
}