How to add a custom font this activity? - android

I have a problem with this activity file I tried to modify I mean to add a custom font this TextView. I tried many code, it doesn't work for me. hope I will find the solution by this Question.
this my activty code:
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 {
}
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();
}
}
i Want to add a font to this "textView"
holder.txtName = (TextView) view.findViewById(R.id.txtSongName);
I tried this but it doesnt work for me:
// give the font path
String fontPath = "font/myfont.otf";
TextView txtName = (TextView) findViewById(R.id.txtSongName);
// get the font face
Typeface tf = Typeface.createFromAsset((AssetManager) getAssets(), fontPath);
// Apply the font
txtName.setTypeface(tf);
// holder = (ViewHolder) view.getTag();
and thank you very Much :)

This is how i add a a custom font,check what did you missed
1.Create an assets folder
Add a separate folder/directory for fonts and name it as fonts
3.Add the fonts to that folder
4.Now i can set my font , this is how i do it
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/Xcelsion.ttf"); // if you are inside a fragment use -> getActivity().getAssets() .....check your path is correct
TextView myTextView = (TextView)findViewById(R.id.text_view);
myTextView.setTypeface(myTypeface); // set that font to the textview you want
Note : If you are in other Class that accept your Activitie's context use yourContextThatYouGot.getAssets() ,if you are in a fragment use getActivity().getAssets() instead of getAssets()

Related

How can I set a music from the software raw folder as the default alarm song?

I use the following code to save a music and select it as alarm music, but it does not work. where is the problem from?
(Files are saved but not selected as ringtone)
holder.btn_alarm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int resId = getMusicId(position, ringTonesDao);
File file = saveMusic(resId);
setForAlarm(file);
}
});
This code receives the music ID in the software.
public int getMusicId(int position, RingTonesDao ringTonesDao) {
long id = ringTonesList.get(position).getId();
String musicAddress = ringTonesDao.checkMusicAddress(id);
int resId = context.getResources().getIdentifier(musicAddress, "raw", context.getPackageName());
return resId;
}
This code, after receiving the music ID, saves it in the internal memory of the mobile and returns the saved file as the output of the method.
public File saveMusic(int resId) {
File dir;
String folderName = "Ringtones";
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(), folderName);
} else {
dir = context.getCacheDir();
}
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, resId + ".mp3");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
}
try {
InputStream inputStream = context.getResources().openRawResource(resId);
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) {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
return file;
}
This code receives the file and sets it as an alert song.
public void setForAlarm(File file) {
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "alarm" + file.getName());
values.put(MediaStore.MediaColumns.SIZE, file.length());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);
values.put(MediaStore.Audio.Media.DURATION, 230);
values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath());
Uri newUri = context.getContentResolver().insert(uri, values);
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));
}
}
cursor.close();
}
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM, newUri);
}

java.lang.IndexOutOfBoundsException: Invalid index 3, size is 2 in viewpager

In my application am using two languages using same adapter, first if user select first language, the data populate in ViewPager, if we swipe two,three pages after that if we change another language data populate in ViewPager, but if we click any button in pager ,it show this
error java.lang.IndexOutOfBoundsException: Invalid index 3, size is 2,
can anyone give solution for this error , thanks in advance.
public class MyCustomAdapter extends PagerAdapter {
Context context1;
LayoutInflater inflater = null;
String title;
public static LinearLayout full_link, containers, language;
public static Uri bmpUri = null;
TextView txtfullstory;
int pStatus = 0;
private Handler handler = new Handler();
public static Bitmap bitmap;
private SharedPreferences.Editor editor;
private SharedPreferences pref;
String user_type_id;
public MyCustomAdapter(Context context1,
ArrayList<String> NewsidArray,
ArrayList<String> NewsdescArray,
ArrayList<String> NewstitleArray,
ArrayList<String> NewsimageArray,
ArrayList<String> NewsdateArray,
ArrayList<String> NewsauthorArray,
ArrayList<String> NewsurlArray) {
this.context1 = context1;
newsidArray = NewsidArray;
newsdescArray = NewsdescArray;
newstitleArray = NewstitleArray;
newsimageArray = NewsimageArray;
newsdateArray = NewsdateArray;
newsauthorArray = NewsauthorArray;
newsurlArray = NewsurlArray;
}
#Override
public int getCount() {
if (newstitleArray == null) {
return 0;
}
return newstitleArray.size();
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public Object instantiateItem(ViewGroup container, final int position) {
final int delPosition = position;
final Holder holder = new Holder();
inflater = (LayoutInflater) context1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View itemView = inflater.inflate(R.layout.fragment_layout, container, false);
holder.date = (TextView) itemView.findViewById(R.id.txtdate);
holder.txttitle = (TextView) itemView.findViewById(R.id.txttitle);
holder.txtdesc = (TextView) itemView.findViewById(R.id.txtdesc);
holder.txtauthor = (TextView) itemView.findViewById(R.id.txtauthor);
holder.imageview = (ImageView) itemView.findViewById(R.id.imageview);
holder.share = (ImageView) itemView.findViewById(R.id.share);
holder.url = (TextView) itemView.findViewById(R.id.url);
holder.reverse = (ImageView) itemView.findViewById(R.id.reverse);
holder.progress = (ProgressBar) itemView.findViewById(R.id.progress);
full_link = (LinearLayout)itemView.findViewById(R.id.line_above);
containers = (LinearLayout)itemView.findViewById(R.id.containers);
language = (LinearLayout)itemView.findViewById(R.id.language);
txtfullstory = (TextView) itemView.findViewById(R.id.txtfullstory);
String date = newsdateArray.get(position).toString();
String image = newsimageArray.get(position).toString();
holder.txtdesc.setText(Html.fromHtml(newsdescArray.get(position).toString()));
holder.txttitle.setText(Html.fromHtml(newstitleArray.get(position).toString()));
holder.txtauthor.setText(Html.fromHtml(newsauthorArray.get(position).toString()));
holder.url.setText(newsurlArray.get(position).toString());
Typeface font = Typeface.createFromAsset(context1.getAssets(), "fonts/Seravek.ttc");
holder.txtdesc.setTypeface(font);
holder.txttitle.setTypeface(font, Typeface.BOLD);
holder.txtauthor.setTypeface(font);
title = newstitleArray.get(position);
pref = context1.getSharedPreferences("MyPref", 0);
editor = pref.edit();
user_type_id = pref.getString("langid", null);
if(user_type_id != null && user_type_id.equals("2")){
txtfullstory.setText(Html.fromHtml("पर पूरी कहानी"));
}else {
txtfullstory.setText(Html.fromHtml("Full story on"));
}
try {
#SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:sss");
Date parsedDate = dateFormat1.parse(date);
long times = parsedDate.getTime();
new Timestamp(times);
String result = (String) DateUtils.getRelativeTimeSpanString(times, System.currentTimeMillis() + 5 * 60 * 1000, 0);
holder.date.setText(result);
} catch (ParseException e) {
Log.d("Error", e.getMessage());
}
if(!(!image.equalsIgnoreCase("") && !image.equalsIgnoreCase(null))) {
holder.imageview.setVisibility(View.INVISIBLE);
}
else{
holder.progress.setVisibility(View.VISIBLE);
holder.imageview.setVisibility(View.INVISIBLE);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (pStatus <= 100) {
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
holder.progress.setProgress(pStatus);
holder.progress.setSecondaryProgress(pStatus + 5);
}
});
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
pStatus++;
}
}
}).start();
holder.imageview.setScaleType(ImageView.ScaleType.FIT_XY);
Picasso.with(context1).load(WebService.WS_ImageOnlineURL + image).fit().centerCrop()
.error(R.drawable.image_loading).transform(new RoundedTransformation(4, 0)).into(holder.imageview, new Callback()
{
#Override
public void onSuccess()
{
holder.progress.setVisibility(View.INVISIBLE);
holder.imageview.setVisibility(View.VISIBLE);
}
#Override
public void onError()
{
}
});
}
itemView.setDrawingCacheEnabled(true);
itemView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
itemView.layout(0, 0, 300, 400);
itemView.buildDrawingCache(true);
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.share.setVisibility(View.INVISIBLE);
holder.reverse.setVisibility(View.VISIBLE);
bitmap = Bitmap.createBitmap(itemView.getWidth(), itemView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
itemView.draw(canvas);
try {
// output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/path/to/file.png");
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
// File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
holder.share.setVisibility(View.VISIBLE);
holder.reverse.setVisibility(View.INVISIBLE);
try {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
sendIntent.putExtra(Intent.EXTRA_TEXT, newstitleArray.get(myCustomPosition) + "\r\n" + "Get odd news only on Oddcast" + "\r\n" + "https://goo.gl/8jeJga");
sendIntent.setType("image/*");
context1.startActivity(sendIntent);
}catch(Exception e) {
e.printStackTrace();
}
}
});
holder.txttitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
holder.share.setVisibility(View.INVISIBLE);
holder.reverse.setVisibility(View.VISIBLE);
bitmap = Bitmap.createBitmap(itemView.getWidth(),itemView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
itemView.draw(canvas);
try {
// output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/path/to/file.png");
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
// File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
holder.share.setVisibility(View.VISIBLE);
holder.reverse.setVisibility(View.INVISIBLE);
Intent i = new Intent(context1, NewsDetailActivity.class);
i.putExtra("url", "" + newsurlArray.get(myCustomPosition));
i.putExtra("title", "" + newstitleArray.get(myCustomPosition));
context1.startActivity(i);
}
});
full_link.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
holder.share.setVisibility(View.INVISIBLE);
holder.reverse.setVisibility(View.VISIBLE);
bitmap = Bitmap.createBitmap(itemView.getWidth(),itemView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
itemView.draw(canvas);
try {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
holder.share.setVisibility(View.VISIBLE);
holder.reverse.setVisibility(View.INVISIBLE);
Intent i = new Intent(context1, NewsDetailActivity.class);
i.putExtra("url", "" + newsurlArray.get(myCustomPosition));
i.putExtra("title", "" + newstitleArray.get(myCustomPosition));
context1.startActivity(i);
}
});
language.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("newstitleArray", String.valueOf(newstitleArray.size()));
Intent language = new Intent(context1, UserPreferedLanguage.class);
context1.startActivity(language);
Activity activity = (Activity) context1;
activity.overridePendingTransition(R.anim.left_in, R.anim.right_out);
}
});
container.addView(itemView);
return itemView;
}
public class Holder {
TextView date,txtauthor,txttitle,txtdesc,url; //Initialize TextView variable
ImageView imageview,share,reverse;
ProgressBar progress;
}
public void destroyItem(ViewGroup container, int position, Object object) {
((LinearLayout) object).removeView(container);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
Execeptions
java.lang.IndexOutOfBoundsException: Invalid index 3, size is 2
java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
java.util.ArrayList.get(ArrayList.java:308)
oddcast.jetlabs.com.oddcast.adapter.MyCustomAdapter$3.onClick(MyCustomAdapter.java:267)
android.view.View.performClick(View.java:4761)
android.view.View$PerformClick.run(View.java:19767)
android.os.Handler.handleCallback(Handler.java:739)
android.os.Handler.dispatchMessage(Handler.java:95)
android.os.Looper.loop(Looper.java:135)
android.app.ActivityThread.main(ActivityThread.java:5312)
java.lang.reflect.Method.invoke(Native Method)
java.lang.reflect.Method.invoke(Method.java:372)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)

How can I make this MP3 work in the background?

This is the utils code, the MP3 work only when the app is open, once you click in the back or the home button it stops.
How can I put it in the background?
public class Util {
public ArrayList<Contact> getAllContact(Context context) {
ArrayList<Contact> contacts = new ArrayList<Contact>();
Cursor cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME);
if(cursor != null) {
while (cursor.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String aaaa = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.CUSTOM_RINGTONE));
if (phone!=null && phone.equals("1")) {
Contact contact = new Contact();
contact.setId(Integer.parseInt(id));
contact.setName(name);
contacts.add(contact);
}
}
}
cursor.close();
return contacts;
}
public ArrayList<SongInfo> getAllSong(Context context) {
ArrayList<SongInfo> listSong = new ArrayList<SongInfo>();
RingtonesSharedPreferences pref = new RingtonesSharedPreferences(
context);
Field[] fields = R.raw.class.getFields();
for (int i = 0; i < fields.length - 1; i++) {
SongInfo info = new SongInfo();
try {
String name = fields[i].getName();
if (!name.equals("ringtones")) {
info.setFileName(name + ".mp3");
info.setFavorite(pref.getString(info.getFileName()));
int audioResource = R.raw.class.getField(name).getInt(name);
info.setAudioResource(audioResource);
}
// info.setName(name);
} catch (Exception e) {
// TODO: handle exception
// Log.e("LOG", "Error: " + e.getMessage());
}
listSong.add(info);
}
InputStream inputStream = context.getResources().openRawResource(
R.raw.zeallist);
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
try {
String line;
int i = 0;
while ((line = reader.readLine()) != null) {
listSong.get(i).setName(line);
i++;
}
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return listSong;
}
public void assignRingtoneToContact(Context context, SongInfo info,Contact contact) {
File dir =null;
ContentValues values = new ContentValues();
boolean isRingTone = false;
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),
"Ringtones");
} 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
}
}
String[] columns = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DISPLAY_NAME,
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);
Uri fullUri = Uri.withAppendedPath(hasUri, cursor.getString(idColumn));
isRingTone = true;
values.put(ContactsContract.Contacts.CUSTOM_RINGTONE, fullUri.toString());
}
}
cursor.close();
if(!isRingTone){
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
Uri oldUri = MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath());
ContentValues Newvalues = new ContentValues();
Uri newUri;
String uriString;
context.getContentResolver().delete(oldUri, MediaStore.MediaColumns.DATA + "=\"" + file.getAbsolutePath() + "\"", null);
Newvalues.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
Newvalues.put(MediaStore.MediaColumns.TITLE, info.getName());
Newvalues.put(MediaStore.MediaColumns.SIZE, file.length());
Newvalues.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
Newvalues.put(MediaStore.Audio.Media.IS_RINGTONE, true);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath());
newUri = context.getContentResolver().insert(uri, Newvalues);
uriString = newUri.toString();
values.put(ContactsContract.Contacts.CUSTOM_RINGTONE, uriString);
Log.i("LOG", "uriString: " + uriString);
}
}
int count = context.getContentResolver().update(ContactsContract.Contacts.CONTENT_URI, values,ContactsContract.Contacts._ID +" = "+contact.getId(), null);
// Log.i("LOG", "Update: " + count);
}
#SuppressWarnings("deprecation")
public Uri getContactContentUri() {
if(Build.VERSION.SDK_INT >= 5){
return ContactsContract.Contacts.CONTENT_URI;
}
else{
return Contacts.People.CONTENT_URI;
}
}
}
try using MediaPlayer, it has many options
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(context, ringtone);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
mediaPlayer.start();
You need to develop player as a service, refer this ,
official docs

How to backup/restore a contacts in android programmatically?

Hello sackoverflow I'm trying to develop an application which can backup and restore contacts, my code is as follows
public class MainActivity extends Activity
{
Cursor cursor;
ArrayList<String> vCard ;
String vfile;
FileOutputStream mFileOutputStream = null;
Button btnRestorects = null;
Button btnBackupCts = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRestorects = (Button) findViewById(R.id.buttonRstCts);
btnBackupCts = (Button) findViewById(R.id.buttonBackCts);
vfile = "contacts.vcf";
final String storage_path = Environment.getExternalStorageDirectory().toString() +"/"+ vfile;
final File f = new File(storage_path);
btnBackupCts.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
try
{
if (!f.exists())
f.createNewFile();
mFileOutputStream = new FileOutputStream(storage_path, false);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
getVcardString();
}
});
btnRestorects.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
final Intent intent = new Intent();
final MimeTypeMap mime = MimeTypeMap.getSingleton();
String tmptype = mime.getMimeTypeFromExtension("vcf");
final File file = new File(Environment.getExternalStorageDirectory().toString() +"/contacts.vcf");
intent.setDataAndType(Uri.fromFile(file),tmptype);
startActivity(intent);
}
});
}
private void getVcardString()
{
// TODO Auto-generated method stub
vCard = new ArrayList<String>();
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if(cursor!=null&&cursor.getCount()>0)
{
cursor.moveToFirst();
for(int i =0;i<cursor.getCount();i++)
{
get(cursor);
Log.d("TAG", "Contact "+(i+1)+"VcF String is"+vCard.get(i));
cursor.moveToNext();
}
}
else
{
Log.d("TAG", "No Contacts in Your Phone");
}
try
{
mFileOutputStream.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void get(Cursor cursor)
{
//cursor.moveToFirst();
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try
{
fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String vcardstring= new String(buf);
vCard.add(vcardstring);
mFileOutputStream.write(vcardstring.toString().getBytes());
}
catch (Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
Permissions in manifest
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
So far my code was backing up the contact but only name and contact number, but not retrieving the information like whether the contact is starred or not. Please help me in solving this riddle.
Thanks in advance.
Use this to restore:
final MimeTypeMap mime = MimeTypeMap.getSingleton();
String tmptype = mime.getMimeTypeFromExtension("vcf");
final File file = new File(Environment.getExternalStorageDirectory().toString()
+ "/contacts.vcf");
Intent i = new Intent();
i.setAction(android.content.Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(file), "text/x-vcard");
startActivity(i);
Intent mIntent = new Intent(Intent.ACTION_VIEW);
mIntent.setDataAndType(Uri.fromFile(new File(filePath)), MimeTypeMap.getSingleton().getMimeTypeFromExtension("vcf"));
startActivity(Intent.createChooser(mIntent, "Select App"));

size of recorded video is 0 by recording video through intent

I have developed video recording application using Intent.
It creates file and stores at specified location but shows 0 bytes on sdcard.
what would be the problem?
I am setting the path for storing the video at different place on sdcard
Thank you.
public class RecordVideoActivity extends Activity{
Button btn_NewVideoRec;
Button btn_RecVideoList;
ListView lstvwVideo;
VideoView videoview;
final static int REQUEST_VIDEO_CAPTURED = 1;
Uri uriVideo = null;
Uri custLoc;
File myRecFile;
String pathtovideo;
ArrayAdapter<String> videoadap;
ArrayList<String> videolist;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.video_record_activity);
btn_NewVideoRec = (Button)findViewById(R.id.btn_RecordNewVideo);
btn_RecVideoList = (Button)findViewById(R.id.btn_RecordedVideoList);
lstvwVideo = (ListView)findViewById(R.id.videolistview);
videoview = (VideoView)findViewById(R.id.videoVw);
btn_NewVideoRec.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
Uri custLoc = getOutputVideoFileUri();
//intent.putExtra(MediaStore.EXTRA_OUTPUT, custLoc);
startActivityForResult(intent, REQUEST_VIDEO_CAPTURED);
}
});
btn_RecVideoList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
System.out.println("path to video::"+pathtovideo);
int lstindxofslash = pathtovideo.lastIndexOf("/");
System.out.println("last index of slash::"+lstindxofslash);
String pathofvdofldr = pathtovideo.substring(0,lstindxofslash);
System.out.println("path of video folder:"+pathofvdofldr);
File srcDir = new File(pathofvdofldr);
File dstDir = new File(Environment.getExternalStorageDirectory()+"/app");
}catch (NullPointerException e) {
// TODO: handle exception
e.getStackTrace();
}
ListView videolw = (ListView)findViewById(R.id.videolistview);
videolw.setVisibility(View.VISIBLE);
videolist = getRecVideoFiles(Environment.getExternalStorageDirectory()+"/app/video");
//videolist = getRecVideoFiles(Environment.getExternalStorageDirectory()+"/DCIM/Camera");
//"Whatsapp/Media/WhatsApp Video/");
videoadap = new ArrayAdapter<String>(RecordVideoActivity.this, android.R.layout.simple_list_item_1, videolist);
videolw.setAdapter(videoadap);
videolw.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), videolist.get(pos), Toast.LENGTH_SHORT).show();
videoview.setVisibility(View.VISIBLE);
btn_NewVideoRec.setVisibility(View.GONE);
btn_RecVideoList.setVisibility(View.GONE);
lstvwVideo.setVisibility(View.GONE);
MediaController mediaController = new MediaController(RecordVideoActivity.this);
mediaController.setAnchorView(videoview);
// Set video link (mp4 format )
Uri video = Uri.parse(videolist.get(pos));
videoview.setMediaController(mediaController);
videoview.setVideoURI(video);
videoview.start();
}
});
}
});
}
public Uri getOutputVideoFileUri(){
return Uri.fromFile(getOutPutVideoFile());
}
public File getOutPutVideoFile(){
String videofolder = "/app/video";
File videofldr = new File(Environment.getExternalStorageDirectory().toString()+videofolder);
if (videofldr.isDirectory()) {
myRecFile = new File(videofldr.getAbsolutePath()+"/"+System.currentTimeMillis()+".mp4");
//myRecFile = audiofldr.toString()+"/"+System.currentTimeMillis()+".3gp";
System.out.println("Path for existing folder::"+myRecFile);
} else {
videofldr.mkdir();
System.out.println("path for created directory::"+myRecFile.getAbsolutePath());
myRecFile = new File(videofldr.getAbsolutePath()+"/"+System.currentTimeMillis()+".mp4");
}
return myRecFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if(requestCode == REQUEST_VIDEO_CAPTURED){
//pathtovideo = getpathofVideo(data.getData());
//System.out.println("pathv::"+pathtovideo);
uriVideo = data.getData();
//uriVideo = (Uri) data.getExtras().get(custLoc.toString());
Toast.makeText(RecordVideoActivity.this,uriVideo.getPath(),Toast.LENGTH_LONG).show();
System.out.println("UriVideoPath::"+uriVideo.getPath());
}
}else if(resultCode == RESULT_CANCELED){
uriVideo = null;
Toast.makeText(RecordVideoActivity.this, "Cancelled!",Toast.LENGTH_LONG).show();
}
}
}
private String getpathofVideo(Uri uriVideo) {
// TODO Auto-generated method stub
String[] proj = { MediaStore.Video.Media.DATA };
Cursor cursor = managedQuery(uriVideo, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private ArrayList<String> getRecVideoFiles(String videorecpath) {
// TODO Auto-generated method stub
ArrayList<String> videofiles = new ArrayList<String>();
File file = new File(videorecpath);
file.mkdir();
File[] f = file.listFiles();
if (f.length == 0) {
Toast.makeText(getApplicationContext(), "No Files!", Toast.LENGTH_SHORT).show();
}else{
for (int i = 0; i < f.length; i++) {
System.out.println("from file.."+f[i].toString());
videofiles.add(f[i].getName());
System.out.println("from arraylist.."+videofiles.get(i).toString());
}
}
return videofiles;
}
}
Instead of your code Try this: First record video aftr that get data and write it to particular location.
Intent photoPickerIntent= new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(Intent.createChooser(photoPickerIntent,"Take Video"),TAKE_VIDEO);
And startActivityForResult will be:
try
{
AssetFileDescriptor videoAsset = getContentResolver().openAssetFileDescriptor(data.getData(), "r");
FileInputStream fis = videoAsset.createInputStream();
File root=new File(Environment.getExternalStorageDirectory(),"Directory");
if (!root.exists()) {
root.mkdirs();
}
File file;
file = new File(root,"test.mp4" );
Uri uri=Uri.fromFile(file);
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}

Categories

Resources