having one text and audio(recording) and saving the name and path in db.while clicking the name that audio has to play its playing also.But while editing if i supposed to change the name alone,it will not take the old file name of the respective one,its make that one as null.
How to take the old audio file name if people will not update the audio(recording)
audioactivity.java
private void saveState() {
String audioname = et1.getText().toString();
String audiofilename = gfilename;
String audiocount = et2.getText().toString();
if(audiocount.equals("")){
audiocount ="1";
}
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String audiodate = sdf.format(new Date());
if (mRowId == null || mRowId.longValue() == 0)
{
long id = mDbHelper.createProject4(audioname, audiofilename, audiocount, audiodate);
if (id > 0) {
mRowId = id;
}
} else {
audiofilename=gfilename;
mDbHelper.updateProject4(mRowId, audioname, audiofilename, audiocount,audiodate);
}
}
public View.OnClickListener btnClick = new View.OnClickListener()
{
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnStart:{
AppLog.logString("Start Recording");
enableButtons(true);
startRecording();
break;
}
case R.id.btnstop:{
AppLog.logString("Start Recording");
enableButtons(false);
stopRecording();
break;
}
}
}
};
public MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
#Override
public void onError(MediaRecorder mr, int what, int extra) {
AppLog.logString("Error: " + what + ", " + extra);
}
};
public MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
AppLog.logString("Warning: " + what + ", " + extra);
}
};
public void setButtonHandlers() {
((Button)findViewById(R.id.btnStart)).setOnClickListener(btnClick);
((Button)findViewById(R.id.btnstop)).setOnClickListener(btnClick);
}
public void enableButton(int id,boolean isEnable){
((Button)findViewById(id)).setEnabled(isEnable);
}
public void enableButtons(boolean isRecording) {
enableButton(R.id.btnStart,!isRecording);
enableButton(R.id.btnstop,isRecording);
}
#SuppressLint("NewApi")
private void startRecording(){
//displayFormatDialog();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String formats[] = {"MPEG 4", "3GPP", "AMR"};
builder.setTitle(getString(R.string.choose_format_title))
.setSingleChoiceItems(formats, currentFormat, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
currentFormat = which;
dialog.dismiss();
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(output_formats[currentFormat]);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(getFilename());
//recorder.setOnErrorListener(errorListener);
//recorder.setOnInfoListener(infoListener);
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
})
.show();
}
private void stopRecording(){
if(null != recorder)
{
//mDbHelper.updateProject4FileName(mRowId, gfilename);
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
else
{
recorder.stop();
recorder.release();
}
}
public String getFilename(){
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath,AUDIO_RECORDER_FOLDER);
if(!file.exists()){
file.mkdirs();
}
gfilename = (file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]);
return (gfilename);
}
#Override
public void onCompletion (MediaPlayer arg0)
{
}
public void playSong(String gfilename){
// Play song
try
{
mp.reset();
mp.setDataSource(gfilename);
mp.prepare();
mp.start();
// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_pause);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I checked in debugging also,if we didnt update the recording its taking that place as null only.
Here i attached my db updated code also
public boolean updateProject4(long _id, String audioname, String audiofilename,String audiocount,String audiodate) {
ContentValues args = new ContentValues();
args.put(CATEGORY_COLUMN_AUDIONAME, audioname );
args.put(CATEGORY_COLUMN_AUDIOFILENAME, audiofilename );
args.put(CATEGORY_COLUMN_AUDIOCOUNT, audiocount );
args.put(CATEGORY_COLUMN_AUDIODATE, audiodate );
return mDb.update(DATABASE_TABLE_AUDIOPRAYER, args, CATEGORY_COLUMN_ID4 + "=" + _id, null) > 0;
}
Actually i got the way for my question.
Want to fetchfile from db if my filename becomes null while updating
private void saveState() {
String audioname = et1.getText().toString();
String audiofilename = gfilename;
String audiocount = et2.getText().toString();
if(audiocount.equals("")){
audiocount ="1";
}
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String audiodate = sdf.format(new Date());
//String reqname= spin.getSelectedItem().toString();
//Log.i(" save state mathod "," values are "+title+Desc+Body+reqname);
if (mRowId == null || mRowId.longValue() == 0)
{
long id = mDbHelper.createProject4(audioname, audiofilename, audiocount, audiodate);
if (id > 0) {
mRowId = id;
}
} else {
if(audiofilename.equals("")){
Cursor filename = mDbHelper.fetchProject4FileName(mRowId, audiofilename);
startManagingCursor(filename);
gfilename =filename.getString(filename.getColumnIndexOrThrow(GinfyDbAdapter.CATEGORY_COLUMN_AUDIOFILENAME));
//mDbHelper.fetchProject4FileName(mRowId, audiofilename);
audiofilename = gfilename;
mDbHelper.updateProject4(mRowId, audioname, audiofilename, audiocount,audiodate);
}
else
{
audiofilename = gfilename;
mDbHelper.updateProject4(mRowId, audioname, audiofilename, audiocount,audiodate);
}
}
we have to fetch the filename from db and check whether our audiofilename is null means,we have to set the older filename
Related
This question already has answers here:
Can't toast on a thread that has not called Looper.prepare()
(4 answers)
Closed 2 years ago.
I want to show Toast message in my app after finishing the downloading. I took the code on the internet and it works like this:- the app is downloading the video from the server and after that, it adds my own watermark in the video, it works nicely but now I want to show TOAST message after finishing the adding watermark thing. I add a simple Toast code but after finishing the watermark processing app but it automatically closes because of the simple Toast message, so anyone help to fix his coding problem, if you need any additional info than this, then let me know.
THIS IS THE WHOLE CODE OF MY JAVA CLASS
public class DownloadService extends Service {
private DatabaseHandler db;
private NotificationCompat.Builder myNotify;
private String video_id, downloadUrl, file_path_delete, file_path, file_name, layout_type, watermark_image, watermark_on_off;
private RemoteViews rv;
private OkHttpClient client;
private WaterMarkData waterMarkData;
private GPUMp4Composer gpuMp4Composer;
public static final String ACTION_STOP = "com.mydownload.action.STOP";
public static final String ACTION_START = "com.mydownload.action.START";
private String NOTIFICATION_CHANNEL_ID = "download_ch_1";
private static final String CANCEL_TAG = "c_tag";
NotificationManager mNotificationManager;
private boolean isWaterMark = false;
private boolean isResize = false;
private Handler mHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message message) {
int progress = Integer.parseInt(message.obj.toString());
switch (message.what) {
case 1:
rv.setTextViewText(R.id.nf_title, getString(R.string.app_name));
rv.setProgressBar(R.id.progress, 100, progress, false);
if (isWaterMark) {
rv.setTextViewText(R.id.nf_percentage, getResources().getString(R.string.watermark) + " " + "(" + progress + " %)");
} else {
rv.setTextViewText(R.id.nf_percentage, getResources().getString(R.string.downloading) + " " + "(" + progress + " %)");
}
myNotify.setCustomContentView(rv);
startForeground(1002, myNotify.build());
break;
case 2:
stopForeground(true);
stopSelf();
break;
}
return false;
}
});
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
db = new DatabaseHandler(getApplicationContext());
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
myNotify = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
myNotify.setChannelId(NOTIFICATION_CHANNEL_ID);
myNotify.setSmallIcon(R.mipmap.ic_launcher);
myNotify.setTicker(getResources().getString(R.string.downloading));
myNotify.setWhen(System.currentTimeMillis());
myNotify.setOnlyAlertOnce(true);
rv = new RemoteViews(getPackageName(),
R.layout.my_custom_notification);
rv.setTextViewText(R.id.nf_title, getString(R.string.app_name));
rv.setProgressBar(R.id.progress, 100, 0, false);
rv.setTextViewText(R.id.nf_percentage, getResources().getString(R.string.downloading) + " " + "(0%)");
Intent closeIntent = new Intent(this, DownloadService.class);
closeIntent.setAction(ACTION_STOP);
PendingIntent pcloseIntent = PendingIntent.getService(this, 0,
closeIntent, 0);
rv.setOnClickPendingIntent(R.id.nf_close, pcloseIntent);
myNotify.setCustomContentView(rv);
NotificationChannel mChannel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Online Channel download";// The user-visible name of the channel.
mChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH);
mNotificationManager.createNotificationChannel(mChannel);
}
startForeground(1002, myNotify.build());
}
#Override
public void onDestroy() {
super.onDestroy();
stopForeground(true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (intent.getAction() != null && intent.getAction().equals(ACTION_START)) {
video_id = intent.getStringExtra("video_id");
downloadUrl = intent.getStringExtra("downloadUrl");
file_path = intent.getStringExtra("file_path");
file_name = intent.getStringExtra("file_name");
layout_type = intent.getStringExtra("layout_type");
watermark_image = intent.getStringExtra("watermark_image");
watermark_on_off = intent.getStringExtra("watermark_on_off");
assert watermark_on_off != null;
if (watermark_on_off.equals("true")) {
file_path = getExternalCacheDir().getAbsolutePath();
}
file_path_delete = file_path;
init();
}
if (intent.getAction() != null && intent.getAction().equals(ACTION_STOP)) {
stopForeground(true);
stopSelf();
if (gpuMp4Composer != null) {
gpuMp4Composer.cancel();
}
if (waterMarkData != null) {
waterMarkData.cancel(true);
}
if (!db.checkId_video_download(video_id)) {
db.delete_video_download(video_id);
}
File file = new File(file_path_delete, file_name);
if (file.exists()) {
file.delete();
}
Method.isDownload = true;
if (client != null) {
for (Call call : client.dispatcher().runningCalls()) {
if (call.request().tag().equals(CANCEL_TAG))
call.cancel();
}
}
}
return START_STICKY;
}
public void init() {
new Thread(new Runnable() {
#Override
public void run() {
client = new OkHttpClient();
Request.Builder builder = new Request.Builder()
.url(downloadUrl)
.addHeader("Accept-Encoding", "identity")
.get()
.tag(CANCEL_TAG);
Call call = client.newCall(builder.build());
call.enqueue(new Callback() {
#Override
public void onFailure(#NonNull Call call, #NonNull IOException e) {
Log.e("TAG", "=============onFailure===============");
e.printStackTrace();
Log.d("error_downloading", e.toString());
Method.isDownload = true;
}
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) throws IOException {
Log.e("TAG", "=============onResponse===============");
Log.e("TAG", "request headers:" + response.request().headers());
Log.e("TAG", "response headers:" + response.headers());
assert response.body() != null;
final ResponseBody responseBody = ProgressHelper.withProgress(response.body(), new ProgressUIListener() {
//if you don't need this method, don't override this methd. It isn't an abstract method, just an empty method.
#Override
public void onUIProgressStart(long totalBytes) {
super.onUIProgressStart(totalBytes);
Log.e("TAG", "onUIProgressStart:" + totalBytes);
Toast.makeText(getApplicationContext(), getResources().getString(R.string.downloading), Toast.LENGTH_SHORT).show();
}
#Override
public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
Log.e("TAG", "=============start===============");
Log.e("TAG", "numBytes:" + numBytes);
Log.e("TAG", "totalBytes:" + totalBytes);
Log.e("TAG", "percent:" + percent);
Log.e("TAG", "speed:" + speed);
Log.e("TAG", "============= end ===============");
Message msg = mHandler.obtainMessage();
msg.what = 1;
msg.obj = (int) (100 * percent) + "";
mHandler.sendMessage(msg);
}
//if you don't need this method, don't override this method. It isn't an abstract method, just an empty method.
#Override
public void onUIProgressFinish() {
super.onUIProgressFinish();
Log.e("TAG", "onUIProgressFinish:");
if (watermark_on_off.equals("true")) {
//call data watermark class add to watermark
waterMarkData = new WaterMarkData();
waterMarkData.execute();
} else {
Message msg = mHandler.obtainMessage();
msg.what = 2;
msg.obj = 0 + "";
mHandler.sendMessage(msg);
Method.isDownload = true;
showMedia(file_path, file_name);
}
}
});
try {
BufferedSource source = responseBody.source();
File outFile = new File(file_path + "/" + file_name);
BufferedSink sink = Okio.buffer(Okio.sink(outFile));
source.readAll(sink);
sink.flush();
source.close();
} catch (Exception e) {
Log.d("show_data", e.toString());
}
}
});
}
}).start();
}
#SuppressLint("StaticFieldLeak")
class WaterMarkData extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
//check water mark on or off
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(downloadUrl);
mp.prepareAsync();
mp.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.d("call_data", "sizedata");
if (layout_type.equals("Portrait")) {
if (height <= 700) {
isResize = true;
}
} else {
if (height <= 400 || width <= 400) {
isResize = true;
}
}
watermark();//call method water mark adding
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
watermark();//call method water mark adding
Log.d("call_data", "error");
} catch (SecurityException e) {
e.printStackTrace();
watermark();//call method water mark adding
Log.d("call_data", "error");
} catch (IllegalStateException e) {
e.printStackTrace();
watermark();//call method water mark adding
Log.d("call_data", "error");
} catch (IOException e) {
e.printStackTrace();
watermark();//call method water mark adding
Log.d("call_data", "error");
} catch (Exception e) {
e.printStackTrace();
watermark();//call method water mark adding
Log.d("call_data", "error");
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("data", "execute");
}
}
private void watermark() {
//check water mark on or off
new Thread(new Runnable() {
#Override
public void run() {
Bitmap image = null;
try {
URL url = new URL(watermark_image);
try {
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (Exception e) {
Log.d("error_data", e.toString());
}
} catch (IOException e) {
Log.d("error", e.toString());
System.out.println(e);
image = BitmapFactory.decodeResource(getResources(), R.drawable.watermark);
}
if (isResize) {
image = getResizedBitmap(image, 40, 40);
isResize = false;
}
String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Latest_Video_Status/";
file_path_delete = destinationPath;
gpuMp4Composer = new GPUMp4Composer(file_path + "/" + file_name, destinationPath + file_name)
.filter(new GlWatermarkFilter(image, GlWatermarkFilter.Position.RIGHT_BOTTOM))
.listener(new GPUMp4Composer.Listener() {
#Override
public void onProgress(double progress) {
isWaterMark = true;
double value = progress * 100;
int i = (int) value;
Message msg = mHandler.obtainMessage();
msg.what = 1;
msg.obj = i + "";
mHandler.sendMessage(msg);
Log.d(TAG, "onProgress = " + progress);
Log.d("call_data", "watermark");
}
#Override
public void onCompleted() {
isWaterMark = false;
new File(getExternalCacheDir().getAbsolutePath() + "/" + file_name).delete();//delete file to save in cash folder
Message msg = mHandler.obtainMessage();
msg.what = 2;
msg.obj = 0 + "";
mHandler.sendMessage(msg);
Method.isDownload = true;
showMedia(destinationPath, file_name);
Log.d(TAG, "onCompleted()");
runOnUiThread(new Runnable()
{
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Your text.",
Toast.LENGTH_SHORT).show();
}
}
);
}
#Override
public void onCanceled() {
isWaterMark = false;
Message msg = mHandler.obtainMessage();
msg.what = 2;
msg.obj = 0 + "";
mHandler.sendMessage(msg);
Method.isDownload = true;
Log.d(TAG, "onCanceled");
}
#Override
public void onFailed(Exception exception) {
isWaterMark = false;
Message msg = mHandler.obtainMessage();
msg.what = 2;
msg.obj = 0 + "";
mHandler.sendMessage(msg);
Method.isDownload = true;
Log.e(TAG, "onFailed()", exception);
}
})
.start();
}
}).start();
}
public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(
bm, 0, 0, width, height, matrix, false);
bm.recycle();
return resizedBitmap;
}
public void showMedia(String file_path, String file_name) {
try {
MediaScannerConnection.scanFile(getApplicationContext(), new String[]{file_path + "/" + file_name},
null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
ERROR
Can't toast on a thread that has not called Looper.prepare()
How what to do now to fix this issue, please anyone help me.
Solution
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "KISHAN",
Toast.LENGTH_SHORT).show();
}
});
Add the following line in onCompleted():-
Toast toast = Toast.makeText(getApplicationContext(),
"The text you want to show",
Toast.LENGTH_SHORT
);
If that doesn't work, then let me know.
Edit :-
Working code:-
private DatabaseHandler db;
private NotificationCompat.Builder myNotify;
private String video_id, downloadUrl, file_path_delete, file_path, file_name, layout_type, watermark_image, watermark_on_off;
private RemoteViews rv;
private OkHttpClient client;
private WaterMarkData waterMarkData;
private GPUMp4Composer gpuMp4Composer;
public static final String ACTION_STOP = "com.mydownload.action.STOP";
public static final String ACTION_START = "com.mydownload.action.START";
private String NOTIFICATION_CHANNEL_ID = "download_ch_1";
private static final String CANCEL_TAG = "c_tag";
NotificationManager mNotificationManager;
private boolean isWaterMark = false;
private boolean isResize = false;
public class ServiceHandler {
private final Activity mactivity;
public ServiceHandler(Activity activity)
{
mActivity = activity;
}
public void run() {
<Your Activity Name>.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast toast = Toast.makeText(getApplicationContext(), "Your text", Toast.LENGTH_SHORT).show();
}
});
}
}
private Handler mHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message message) {
int progress = Integer.parseInt(message.obj.toString());
switch (message.what) {
case 1:
rv.setTextViewText(R.id.nf_title, getString(R.string.app_name));
rv.setProgressBar(R.id.progress, 100, progress, false);
if (isWaterMark) {
rv.setTextViewText(R.id.nf_percentage, getResources().getString(R.string.watermark) + " " + "(" + progress + " %)");
} else {
rv.setTextViewText(R.id.nf_percentage, getResources().getString(R.string.downloading) + " " + "(" + progress + " %)");
}
myNotify.setCustomContentView(rv);
startForeground(1002, myNotify.build());
break;
case 2:
stopForeground(true);
stopSelf();
break;
}
return false;
}
});
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
db = new DatabaseHandler(getApplicationContext());
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
myNotify = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
myNotify.setChannelId(NOTIFICATION_CHANNEL_ID);
myNotify.setSmallIcon(R.mipmap.ic_launcher);
myNotify.setTicker(getResources().getString(R.string.downloading));
myNotify.setWhen(System.currentTimeMillis());
myNotify.setOnlyAlertOnce(true);
rv = new RemoteViews(getPackageName(),
R.layout.my_custom_notification);
rv.setTextViewText(R.id.nf_title, getString(R.string.app_name));
rv.setProgressBar(R.id.progress, 100, 0, false);
rv.setTextViewText(R.id.nf_percentage, getResources().getString(R.string.downloading) + " " + "(0%)");
Intent closeIntent = new Intent(this, DownloadService.class);
closeIntent.setAction(ACTION_STOP);
PendingIntent pcloseIntent = PendingIntent.getService(this, 0,
closeIntent, 0);
rv.setOnClickPendingIntent(R.id.nf_close, pcloseIntent);
myNotify.setCustomContentView(rv);
NotificationChannel mChannel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Online Channel download";// The user-visible name of the channel.
mChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH);
mNotificationManager.createNotificationChannel(mChannel);
}
startForeground(1002, myNotify.build());
}
#Override
public void onDestroy() {
super.onDestroy();
stopForeground(true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (intent.getAction() != null && intent.getAction().equals(ACTION_START)) {
video_id = intent.getStringExtra("video_id");
downloadUrl = intent.getStringExtra("downloadUrl");
file_path = intent.getStringExtra("file_path");
file_name = intent.getStringExtra("file_name");
layout_type = intent.getStringExtra("layout_type");
watermark_image = intent.getStringExtra("watermark_image");
watermark_on_off = intent.getStringExtra("watermark_on_off");
assert watermark_on_off != null;
if (watermark_on_off.equals("true")) {
file_path = getExternalCacheDir().getAbsolutePath();
}
file_path_delete = file_path;
init();
}
if (intent.getAction() != null && intent.getAction().equals(ACTION_STOP)) {
stopForeground(true);
stopSelf();
if (gpuMp4Composer != null) {
gpuMp4Composer.cancel();
}
if (waterMarkData != null) {
waterMarkData.cancel(true);
}
if (!db.checkId_video_download(video_id)) {
db.delete_video_download(video_id);
}
File file = new File(file_path_delete, file_name);
if (file.exists()) {
file.delete();
}
Method.isDownload = true;
if (client != null) {
for (Call call : client.dispatcher().runningCalls()) {
if (call.request().tag().equals(CANCEL_TAG))
call.cancel();
}
}
}
return START_STICKY;
}
public void init() {
new Thread(new Runnable() {
#Override
public void run() {
client = new OkHttpClient();
Request.Builder builder = new Request.Builder()
.url(downloadUrl)
.addHeader("Accept-Encoding", "identity")
.get()
.tag(CANCEL_TAG);
Call call = client.newCall(builder.build());
call.enqueue(new Callback() {
#Override
public void onFailure(#NonNull Call call, #NonNull IOException e) {
Log.e("TAG", "=============onFailure===============");
e.printStackTrace();
Log.d("error_downloading", e.toString());
Method.isDownload = true;
}
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) throws IOException {
Log.e("TAG", "=============onResponse===============");
Log.e("TAG", "request headers:" + response.request().headers());
Log.e("TAG", "response headers:" + response.headers());
assert response.body() != null;
final ResponseBody responseBody = ProgressHelper.withProgress(response.body(), new ProgressUIListener() {
//if you don't need this method, don't override this methd. It isn't an abstract method, just an empty method.
#Override
public void onUIProgressStart(long totalBytes) {
super.onUIProgressStart(totalBytes);
Log.e("TAG", "onUIProgressStart:" + totalBytes);
Toast.makeText(getApplicationContext(), getResources().getString(R.string.downloading), Toast.LENGTH_SHORT).show();
}
#Override
public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
Log.e("TAG", "=============start===============");
Log.e("TAG", "numBytes:" + numBytes);
Log.e("TAG", "totalBytes:" + totalBytes);
Log.e("TAG", "percent:" + percent);
Log.e("TAG", "speed:" + speed);
Log.e("TAG", "============= end ===============");
Message msg = mHandler.obtainMessage();
msg.what = 1;
msg.obj = (int) (100 * percent) + "";
mHandler.sendMessage(msg);
}
//if you don't need this method, don't override this method. It isn't an abstract method, just an empty method.
#Override
public void onUIProgressFinish() {
super.onUIProgressFinish();
Log.e("TAG", "onUIProgressFinish:");
if (watermark_on_off.equals("true")) {
//call data watermark class add to watermark
waterMarkData = new WaterMarkData();
waterMarkData.execute();
} else {
Message msg = mHandler.obtainMessage();
msg.what = 2;
msg.obj = 0 + "";
mHandler.sendMessage(msg);
Method.isDownload = true;
showMedia(file_path, file_name);
}
}
});
try {
BufferedSource source = responseBody.source();
File outFile = new File(file_path + "/" + file_name);
BufferedSink sink = Okio.buffer(Okio.sink(outFile));
source.readAll(sink);
sink.flush();
source.close();
} catch (Exception e) {
Log.d("show_data", e.toString());
}
}
});
}
}).start();
}
#SuppressLint("StaticFieldLeak")
class WaterMarkData extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
//check water mark on or off
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(downloadUrl);
mp.prepareAsync();
mp.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.d("call_data", "sizedata");
if (layout_type.equals("Portrait")) {
if (height <= 700) {
isResize = true;
}
} else {
if (height <= 400 || width <= 400) {
isResize = true;
}
}
watermark();//call method water mark adding
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
watermark();//call method water mark adding
Log.d("call_data", "error");
} catch (SecurityException e) {
e.printStackTrace();
watermark();//call method water mark adding
Log.d("call_data", "error");
} catch (IllegalStateException e) {
e.printStackTrace();
watermark();//call method water mark adding
Log.d("call_data", "error");
} catch (IOException e) {
e.printStackTrace();
watermark();//call method water mark adding
Log.d("call_data", "error");
} catch (Exception e) {
e.printStackTrace();
watermark();//call method water mark adding
Log.d("call_data", "error");
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("data", "execute");
}
}
private void watermark() {
//check water mark on or off
new Thread(new Runnable() {
#Override
public void run() {
Bitmap image = null;
try {
URL url = new URL(watermark_image);
try {
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (Exception e) {
Log.d("error_data", e.toString());
}
} catch (IOException e) {
Log.d("error", e.toString());
System.out.println(e);
image = BitmapFactory.decodeResource(getResources(), R.drawable.watermark);
}
if (isResize) {
image = getResizedBitmap(image, 40, 40);
isResize = false;
}
String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Latest_Video_Status/";
file_path_delete = destinationPath;
gpuMp4Composer = new GPUMp4Composer(file_path + "/" + file_name, destinationPath + file_name)
.filter(new GlWatermarkFilter(image, GlWatermarkFilter.Position.RIGHT_BOTTOM))
.listener(new GPUMp4Composer.Listener() {
#Override
public void onProgress(double progress) {
isWaterMark = true;
double value = progress * 100;
int i = (int) value;
Message msg = mHandler.obtainMessage();
msg.what = 1;
msg.obj = i + "";
mHandler.sendMessage(msg);
Log.d(TAG, "onProgress = " + progress);
Log.d("call_data", "watermark");
}
#Override
public void onCompleted() {
isWaterMark = false;
new File(getExternalCacheDir().getAbsolutePath() + "/" + file_name).delete();//delete file to save in cash folder
Message msg = mHandler.obtainMessage();
msg.what = 2;
msg.obj = 0 + "";
mHandler.sendMessage(msg);
Method.isDownload = true;
showMedia(destinationPath, file_name);
Log.d(TAG, "onCompleted()");
ServiceHandler sh = new ServiceHandler(this);
sh.run();
}
#Override
public void onCanceled() {
isWaterMark = false;
Message msg = mHandler.obtainMessage();
msg.what = 2;
msg.obj = 0 + "";
mHandler.sendMessage(msg);
Method.isDownload = true;
Log.d(TAG, "onCanceled");
}
#Override
public void onFailed(Exception exception) {
isWaterMark = false;
Message msg = mHandler.obtainMessage();
msg.what = 2;
msg.obj = 0 + "";
mHandler.sendMessage(msg);
Method.isDownload = true;
Log.e(TAG, "onFailed()", exception);
}
})
.start();
}
}).start();
}
public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(
bm, 0, 0, width, height, matrix, false);
bm.recycle();
return resizedBitmap;
}
public void showMedia(String file_path, String file_name) {
try {
MediaScannerConnection.scanFile(getApplicationContext(), new String[]{file_path + "/" + file_name},
null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public class CallReceiver extends BroadcastReceiver {
MediaRecorder recorder;
TelephonyManager telManager;
boolean recordStarted;
private Context ctx;
static boolean status = false;
String phoneNumber;
public static SharedPreferences preferences;
boolean enabled;
private static Date date;
public static Boolean isIncoming;
private static String dateStr;
#Override
public void onReceive(Context context, Intent intent) {
ctx = context;
String action = intent.getAction();
preferences = context.getSharedPreferences("Numbers", Context.MODE_PRIVATE);
enabled = preferences.getBoolean("enabled", false);
date = new Date();
dateStr = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
if (enabled) {
if (status == false) {
try {
recorder = new MediaRecorder();
} catch (Exception ex) {
ex.printStackTrace();
}
Bundle extras = intent.getExtras();
if (extras != null) {
String state = extras.getString(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
phoneNumber = extras.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
incomingcallrecord(action, context);
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
incomingcallrecord(action, context);
}
}
} else {
status = false;
}
}
}
private void incomingcallrecord(String action, Context context) {
// TODO Auto-generated method stub
if (action.equals("android.intent.action.PHONE_STATE")) {
telManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
private final PhoneStateListener phoneListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
Log.d("calling number", "calling number" + incomingNumber);
try {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING: {
Log.e("CALL_STATE_RINGING", "CALL_STATE_RINGING");
isIncoming = true;
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
Log.e("incoming", "incoming call" + incomingNumber);
File file = createDirIfNotExists();
recorder.setOutputFile(file.getAbsolutePath());
recorder.prepare();
Thread.sleep(1000);
recorder.start();
recordStarted = true;
status = true;
Log.e("Record start", " Start");
String insertStr = "IN_" + dateStr;
ContentValues values = new ContentValues();
values.put(CallRecorderSQLite.FeedEntry.COLUMN_2_NUMBER, insertStr);
Activity_Landing.dbWritable.insert(CallRecorderSQLite.FeedEntry.TABLE_NAME, null, values);
Log.d("calling number ringing", "" + incomingNumber);
break;
}
case TelephonyManager.CALL_STATE_OFFHOOK: {
Log.e("CALL_STATE_OFFHOOK", "CALL_STATE_OFFHOOK");
isIncoming = false;
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
Log.e("outgoing", "outgoing call" + incomingNumber);
File file = createDirIfNotExists();
recorder.setOutputFile(file.getAbsolutePath());
recorder.prepare();
Thread.sleep(1000);
recorder.start();
recordStarted = true;
status = true;
Log.e("Record start", " Start");
String insertStr = "OUT_" + dateStr;
ContentValues values = new ContentValues();
values.put(CallRecorderSQLite.FeedEntry.COLUMN_2_NUMBER, insertStr);
Activity_Landing.dbWritable.insert(CallRecorderSQLite.FeedEntry.TABLE_NAME, null, values);
Log.d("calling number offhook", "" + incomingNumber);
break;
}
case TelephonyManager.CALL_STATE_IDLE: {
Log.e("CALL_STATE_IDLE", "CALL_STATE_IDLE");
if (recordStarted) {
recorder.stop();
recorder.reset();
recorder.release();
Log.e("Record stop", " stop");
recorder = null;
recordStarted = false;
}
Log.d("calling number idle", "" + incomingNumber);
break;
}
default: {
}
}
} catch (Exception ex) {
Log.e("Exception ------", "" + ex.toString());
}
}
};
public File createDirIfNotExists() {
File folder = new File(Environment.getExternalStorageDirectory() + "/PhoneCallRecording");
if (!folder.exists()) {
if (!folder.mkdirs()) {
Log.e("TravellerLog :: ", "folder is created");
}
}
File file;
if (isIncoming) {
file = new File(folder, "IN_" + dateStr + ".amr");
} else {
file = new File(folder, "OUT_" + dateStr + ".amr");
}
try {
if (!file.exists()) {
if (file.createNewFile()) {
Log.e("TravellerLog :: ", "file is created");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
}
My code
I am developing android app from call recorder. In manifest file i am using phone state permission but cannot access outgoing call, i am getting null pointer exception.
Manifest,
<receiver android:name=".Receiver.CallReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"></action>
</intent-filter>
</receiver>
Change manifest to this:
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<receiver android:name=".MyPhoneReceiver" >
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
and code:
...
#Override public void onReceive(final Context context, final Intent intent) {
if (Intent.ACTION_NEW_OUTGOING_CALL.equals(intent.getAction())) {
final String originalNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
}
...
According to this answer
public class CallReceiver extends BroadcastReceiver {
MediaRecorder recorder;
TelephonyManager telManager;
boolean recordStarted;
private Context ctx;
static boolean status = false;
String phoneNumber;
public static SharedPreferences preferences;
boolean enabled;
private static Date date;
Boolean isIncoming;
String isInOrOut;
private static String dateStr;
static long start_time, end_time;
String lastCallnumber;
#Override
public void onReceive(Context context, Intent intent) {
ctx = context;
String action = intent.getAction();
preferences = context.getSharedPreferences("Numbers", Context.MODE_PRIVATE);
enabled = preferences.getBoolean("enabled", false);
date = new Date();
dateStr = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
if (enabled) {
if (status == false) {
try {
recorder = new MediaRecorder();
} catch (Exception ex) {
ex.printStackTrace();
}
Bundle extras = intent.getExtras();
if (extras != null) {
String state = extras.getString(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
incomingcallrecord(action, context);
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
incomingcallrecord(action, context);
}
}
} else {
status = false;
}
}
}
private void incomingcallrecord(String action, Context context) {
// TODO Auto-generated method stub
if (action.equals("android.intent.action.PHONE_STATE")) {
telManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
private final PhoneStateListener phoneListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
Log.d("calling number", "calling number" + incomingNumber);
try {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING: {
Log.e("CALL_STATE_RINGING", "CALL_STATE_RINGING");
isIncoming = true;
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
Log.e("incoming", "incoming call" + incomingNumber);
phoneNumber = incomingNumber;
File file = createDirIfNotExists();
recorder.setOutputFile(file.getAbsolutePath());
recorder.prepare();
Thread.sleep(1000);
recorder.start();
recordStarted = true;
status = true;
Log.e("Record start", " Start");
Log.d("calling number ringing", "" + incomingNumber);
break;
}
case TelephonyManager.CALL_STATE_OFFHOOK: {
Log.e("CALL_STATE_OFFHOOK", "CALL_STATE_OFFHOOK");
isIncoming = false;
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
Log.e("outgoing", "outgoing call" + lastCallnumber);
File file = createDirIfNotExists();
recorder.setOutputFile(file.getAbsolutePath());
recorder.prepare();
Thread.sleep(1000);
recorder.start();
recordStarted = true;
status = true;
Log.e("Record start", " Start");
Log.d("calling number offhook", "" + lastCallnumber);
break;
}
case TelephonyManager.CALL_STATE_IDLE: {
Log.e("CALL_STATE_IDLE", "CALL_STATE_IDLE");
if (recordStarted) {
recorder.stop();
recorder.reset();
recorder.release();
Log.e("Record stop", " stop");
recorder = null;
recordStarted = false;
}
if (isIncoming) {
isInOrOut = "in";
ContentValues values = new ContentValues();
values.put(CallRecorderSQLite.FeedEntry.COLUMN_1_TIME, dateStr);
values.put(CallRecorderSQLite.FeedEntry.COLUMN_2_NUMBER, phoneNumber);
values.put(CallRecorderSQLite.FeedEntry.COLUMN_3_INOUT, isInOrOut);
Activity_Landing.dbWritable.insert(CallRecorderSQLite.FeedEntry.TABLE_NAME, null, values);
} else {
isInOrOut = "out";
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Log.i("CallLogDetailsActivity", "Getting Log activity...");
String[] projection = new String[]{CallLog.Calls.NUMBER};
if (ActivityCompat.checkSelfPermission(ctx, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
return;
}
Cursor cur = ctx.getContentResolver().query(CallLog.Calls.CONTENT_URI, projection, null, null, CallLog.Calls.DATE + " desc");
cur.moveToFirst();
lastCallnumber = cur.getString(0);
ContentValues values = new ContentValues();
values.put(CallRecorderSQLite.FeedEntry.COLUMN_1_TIME, dateStr);
values.put(CallRecorderSQLite.FeedEntry.COLUMN_2_NUMBER, lastCallnumber);
values.put(CallRecorderSQLite.FeedEntry.COLUMN_3_INOUT, isInOrOut);
Activity_Landing.dbWritable.insert(CallRecorderSQLite.FeedEntry.TABLE_NAME, null, values);
}
}, 500);
}
Log.d("calling number idle", "" + incomingNumber);
break;
}
default: {
}
}
} catch (Exception ex) {
Log.e("Exception ------", "" + ex.toString());
}
}
};
public File createDirIfNotExists() {
File folder = new File(Environment.getExternalStorageDirectory() + "/PhoneCallRecording");
if (!folder.exists()) {
if (!folder.mkdirs()) {
Log.e("TravellerLog :: ", "folder is created");
}
}
File file = new File(folder, dateStr + ".amr");
try {
if (!file.exists()) {
if (file.createNewFile()) {
Log.e("TravellerLog :: ", "file is created");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
}
From the second you click on the notification activity button the program immediately starts acting slow. This screen for some reason takes minutes to scroll down in a very glitchy and drawn out manner. What can I do to speed up and smooth out my notification activity screen?
NotificationActivity:
public class NotificationActivity extends BaseActivity {
public static final String TAG = LoginActivity.class.getSimpleName();
private NotificationAdapter notificationAdapter;
private HeaderLayout headerLayout;
private FooterLayout footerLayout;
private SimpleGestureFilter detector;
private ListView mNotificationLv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
mNotificationLv = (ListView) findViewById(R.id.notification_lv);
mNotificationLv = (ListView) findViewById(R.id.notification_lv);
notificationAdapter = new NotificationAdapter(this);
notificationAdapter.setList(AtlasApplication.lstNotificationModels);
mNotificationLv.setAdapter(notificationAdapter);
// Detect touched area
detector = new SimpleGestureFilter(this,this);
}
#Override
protected void onResume() {
super.onResume();
List<NotificationModel> userModelList = AtlasApplication.lstNotificationModels;
notificationAdapter = new NotificationAdapter(this);
notificationAdapter.setList(userModelList);
mNotificationLv.setAdapter(notificationAdapter);
}
}
NotificationAdapter:
public class NotificationAdapter extends BaseAdapter{
private List<NotificationModel> lstNotificationModels;
private SQLiteAdapter sqLiteAdapter;
private Context context;
public NotificationAdapter(Context context) {
this.context = context; sqLiteAdapter=new SQLiteAdapter(context, this, new Dialog(context));
}
public void setList(List<NotificationModel> genres) {
this.lstNotificationModels = genres;
notifyDataSetChanged();
}
private class ViewHolder {
TextView mNotifiactionTypeTv, mNotifiactionTextTv, mNotifiactionTimeTv;
LinearLayout rowNotificationLl;
}
public void setRead(int i){
sqLiteAdapter.updateNotificationStatus(i, "read");
lstNotificationModels.get(i).setmNotificationStatus("read");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_notification, null);
holder = new ViewHolder();
holder.rowNotificationLl = (LinearLayout) convertView.findViewById(R.id.row_notification_ll);
holder.mNotifiactionTextTv = (TextView) convertView.findViewById(R.id.notification_text_tv);
holder.mNotifiactionTimeTv = (TextView) convertView.findViewById(R.id.notification_time_tv);
holder.mNotifiactionTypeTv = (TextView) convertView.findViewById(R.id.notification_type_atv);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final NotificationModel notificationModel = lstNotificationModels.get(position);
final String newFullText = sqLiteAdapter.getFullText(notificationModel.getmLawId());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currentDate = new Date();
Date notificationDate = new Date();
String timeElapsed = "moments ago.";
try {
notificationDate = simpleDateFormat.parse(notificationModel.getmNotificationTime().trim());
} catch(ParseException e){
}
long milliElapsed = currentDate.getTime() - notificationDate.getTime() + 14400000;
if(milliElapsed>=60000){
long minutesElapsed = milliElapsed/60000;
timeElapsed = minutesElapsed + " minutes ago.";
if(minutesElapsed>=60){
long hoursElapsed = minutesElapsed/60;
timeElapsed = hoursElapsed + " hours ago.";
if(hoursElapsed>=24){
long daysElapsed = hoursElapsed/60;
timeElapsed = daysElapsed + " days ago.";
if(daysElapsed>=7){
long weeksElapsed = daysElapsed/7;
timeElapsed = hoursElapsed + " weeks ago.";
if(weeksElapsed>=4){
long monthsElapsed = weeksElapsed/4;
timeElapsed = monthsElapsed + " months ago.";
if(daysElapsed>=365){
long yearsElapsed = daysElapsed/365;
timeElapsed = yearsElapsed + " years ago.";
}
}
}
}
}
}
holder.mNotifiactionTextTv.setText(Html.fromHtml(notificationModel.getmNotificationText().trim()));
holder.mNotifiactionTimeTv.setText(timeElapsed);
if (notificationModel.getmNotificationStatus().equalsIgnoreCase("unread")) {
convertView.findViewById(R.id.unread_vw).setVisibility(View.VISIBLE);
holder.rowNotificationLl.setBackgroundResource(R.color.black);
}
else {
convertView.findViewById(R.id.unread_vw).setVisibility(View.GONE);
holder.rowNotificationLl.setBackgroundResource(R.color.grad_light);
}
switch (notificationModel.getmNotificationType().toLowerCase()){
case "traffic":
holder.mNotifiactionTypeTv.setBackgroundResource(R.drawable.traffic_noti_bg);
holder.mNotifiactionTypeTv.setText("f");
holder.mNotifiactionTypeTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_TRAFFIC;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(0);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
holder.mNotifiactionTextTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_TRAFFIC;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(0);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
catch(Exception e){
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
break;
case "law enforcement":
holder.mNotifiactionTypeTv.setBackgroundResource(R.drawable.enforcement_noti_bg);
holder.mNotifiactionTypeTv.setText("c");
holder.mNotifiactionTypeTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_ENFORCEMENT;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(1);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
holder.mNotifiactionTextTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_ENFORCEMENT;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(1);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
catch(Exception e){
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
break;
case "alcohol":
holder.mNotifiactionTypeTv.setBackgroundResource(R.drawable.alcohal_noti_bg);
holder.mNotifiactionTypeTv.setText("a");
holder.mNotifiactionTypeTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_ALCOHOL;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(2);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
holder.mNotifiactionTextTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_ALCOHOL;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(2);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
catch(Exception e){
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
break;
case "taxes":
holder.mNotifiactionTypeTv.setBackgroundResource(R.drawable.taxes_noti_bg);
holder.mNotifiactionTypeTv.setText("e");
holder.mNotifiactionTypeTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_TAXES;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(3);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
holder.mNotifiactionTextTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_TAXES;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(3);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
break;
case "guns":
holder.mNotifiactionTypeTv.setBackgroundResource(R.drawable.guns_noti_bg);
holder.mNotifiactionTypeTv.setText("b");
holder.mNotifiactionTypeTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_GUNS;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(4);
setRead(notificationModel.getmNotificaticationId());
AtlasApplication.lstLawsForLocation.get(1).setSelected(true);
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
holder.mNotifiactionTextTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_GUNS;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(4);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
catch(Exception e){
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
break;
case "marijuana":
holder.mNotifiactionTypeTv.setBackgroundResource(R.drawable.marijuana_noti_bg);
holder.mNotifiactionTypeTv.setText("d");
holder.mNotifiactionTypeTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_MARIJUANA;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(5);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
holder.mNotifiactionTextTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_MARIJUANA;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(5);
setRead(notificationModel.getmNotificaticationId());
AtlasApplication.lstLawsForLocation.get(1).setSelected(true);
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
break;
default:
break;
}
FontLoader.setAtlasFont(holder.mNotifiactionTypeTv);
FontLoader.setRalewayRegularFont(holder.mNotifiactionTextTv, holder.mNotifiactionTimeTv);
holder.rowNotificationLl.setId(position);
holder.rowNotificationLl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
return convertView;
}
}
SQLiteAdapter:
public class SQLiteAdapter {
private static final int DATABASE_VERSION = 1;
private static String DB_PATH;//= Environment.getExternalStorageDirectory() + "/" + context.getPackageName() + "/";
private SQLiteDatabase mSqLiteDatabase;
private Context mContext;
private Dialog mDialog;
private SQLiteDbQueryListener sqLiteDbQueryListener;
private ExceptionHandler exceptionHandler;
public SQLiteAdapter(Context c, SQLiteDbQueryListener listener, Dialog dialog) {
mContext = c;
sqLiteDbQueryListener = listener;
exceptionHandler = new ExceptionHandler(mContext, "SQLiteAdapter");
mDialog = dialog;
DB_PATH = Environment.getExternalStorageDirectory() + "/" + mContext.getPackageName() + "/";
//call it so db get copied from assets to sdcard
//call it so db get copied from assets to sdcard
openToRead();
close();
}
public void updateLaw(int lawID, String newSummary, String newFullText){
int tagID = getTagID(lawID);
String tagName = getTagName(tagID);
int categoryID = getCategoryID(tagID);
String categoryName = getCategoryName(categoryID);
String location;
location = getLocationName(getLocationID(lawID));
if (location.toLowerCase().equals(AtlasApplication.sHometownSelected.getLocationName().toLowerCase())) {
location = "your current state";
} else if (location.toLowerCase().equals(AtlasApplication.sHometownSelected.getLocationName().toLowerCase())) {
location = "your home state";
}
openToWrite();
ContentValues contentValues = new ContentValues();
contentValues.put(Constants.KEY_SUMMARY, newSummary);
if(newFullText!=null)
contentValues.put(Constants.KEY_FULL_TEXT, newFullText);
mSqLiteDatabase.update(Constants.TABLE_LAW, contentValues, Constants.KEY_LAW_ID + "=" + lawID, null);
close();
insertNotification(lawID, categoryName, tagName + " has changed in " + location + ".");
}
public int getCategoryID(int tagID){
openToRead();
int categoryID = 0;
String Query = "SELECT * from " + Constants.TABLE_CATEGORY_TAG;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
if (cursor.getInt(cursor.getColumnIndex(Constants.KEY_TAG_ID)) == tagID) {
int indexCategoryID = cursor.getColumnIndex(Constants.KEY_CATEGORY_ID);
categoryID = cursor.getInt(indexCategoryID);
}
cursor.moveToNext();
}
}
close();
return categoryID;
}
public String getCategoryName(int categoryID){
String categoryName = "";
openToRead();
String Query = "SELECT * from " + Constants.TABLE_CATEGORY;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
if (cursor.getInt(cursor.getColumnIndex(Constants.KEY_CATEGORY_ID)) == categoryID) {
int indexCategoryName = cursor.getColumnIndex(Constants.KEY_CATEGORY_NAME);
categoryName = cursor.getString(indexCategoryName);
}
cursor.moveToNext();
}
}
close();
return categoryName.toLowerCase();
}
public int getLocationID(int lawID){
openToRead();
String Query = "SELECT * from " + Constants.TABLE_LAW_LOCATION;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
int locationID = 0;
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
try {
if(cursor.getInt(cursor.getColumnIndex(Constants.KEY_LAW_ID)) == lawID) {
int indexTagID = cursor.getColumnIndex(Constants.KEY_LOCATION_ID);
locationID = cursor.getInt(indexTagID);
}
} catch (Exception e) {
exceptionHandler.alert(e, "getLocationID()");
}
cursor.moveToNext();
}
}
close();
return locationID;
}
public String getLocationName(int locationID){
openToRead();
String Query = "SELECT * from " + Constants.TABLE_LOCATION;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
String locationName = "";
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
if(cursor.getInt(cursor.getColumnIndex(Constants.KEY_LOCATION_ID)) == locationID) {
int indexTagID = cursor.getColumnIndex(Constants.KEY_LOCATION_NAME);
locationName = cursor.getString(indexTagID);
}
cursor.moveToNext();
}
}
close();
return locationName;
}
public int getTagID(int lawID){
openToRead();
String Query = "SELECT * from " + Constants.TABLE_LAW_TAG;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
int tagID = 0;
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
if(cursor.getInt(cursor.getColumnIndex(Constants.KEY_LAW_ID)) == lawID) {
int indexTagID = cursor.getColumnIndex(Constants.KEY_TAG_ID);
tagID = cursor.getInt(indexTagID);
cursor.moveToNext();
}
}
close();
return tagID;
}
public String getTagName(int tagID){
openToRead();
String tagName = "";
String Query = "SELECT * from " + Constants.TABLE_TAG;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
if(cursor.moveToFirst()){
while (cursor.isAfterLast() == false) {
try {
if(cursor.getInt(cursor.getColumnIndex(Constants.KEY_TAG_ID)) == tagID) {
int indexTagName = cursor.getColumnIndex(Constants.KEY_TAG_NAME);
tagName = cursor.getString(indexTagName);
}
} catch (Exception e) {
exceptionHandler.alert(e, "getTagName()");
}
cursor.moveToNext();
}
}
close();
return tagName;
}
public void insertNotification(int lawID, String type, String text){
openToWrite();
try {
ContentValues contentValues = new ContentValues();
contentValues.put(Constants.KEY_LAW_ID, lawID);
contentValues.put(Constants.KEY_NOTIFICATION_TYPE, type);
contentValues.put(Constants.KEY_NOTIFICATION_TEXT, text);
contentValues.put(Constants.KEY_NOTIFICATION_STATUS, "unread");
mSqLiteDatabase.insert(Constants.TABLE_NOTIFICATION, null, contentValues);
}
catch(Exception e){
exceptionHandler.alert(e, "insertNotification()");
}
close();
}
public void dropNotifications(){
openToWrite();
try{
mSqLiteDatabase.execSQL("DROP TABLE IF EXISTS notification");
}
catch(Exception e){
}
close();
}
public void updateNotificationStatus(int notificationID, String status){
openToWrite();
try {
ContentValues contentValues = new ContentValues();
contentValues.put(Constants.KEY_NOTIFICATION_STATUS, status);
mSqLiteDatabase.update(Constants.TABLE_NOTIFICATION, contentValues, Constants.KEY_NOTIFICATION_ID + "=" + notificationID, null);
}
catch(Exception e){
exceptionHandler.alert(e, "updateNotificationStatus()");
}
close();
}
public String getNotificationStatus(int notificationID){
openToRead();
String Query = "SELECT * FROM " + Constants.TABLE_NOTIFICATION + " WHERE " + Constants.KEY_NOTIFICATION_ID + "=" + notificationID;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
String notificationStatus = "";
if(cursor.moveToFirst()){
while (cursor.isAfterLast() == false) {
try {
if(cursor.getInt(cursor.getColumnIndex(Constants.KEY_NOTIFICATION_ID)) == notificationID) {
int indexNotificationStatus = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_STATUS);
notificationStatus = cursor.getString(indexNotificationStatus);
}
} catch (Exception e) {
exceptionHandler.alert(e, "getNotificationStatus()");
}
cursor.moveToNext();
}
}
close();
return notificationStatus;
}
public int getNotificationId(int lawID, String time){
openToRead();
int notificationId = 0;
String query = "SELECT * FROM " + Constants.TABLE_NOTIFICATION +
" WHERE " + Constants.KEY_NOTIFICATION_TIME + " = " + time;
Cursor cursor = mSqLiteDatabase.rawQuery(query, null);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
int indexNotificationID = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_ID);
notificationId = cursor.getInt(indexNotificationID);
}
}
close();
return notificationId;
}
public List<NotificationModel> getNotificationList(){
List<NotificationModel> lstNotifications = new ArrayList<NotificationModel>();
openToRead();
String Query = "SELECT * from " + Constants.TABLE_NOTIFICATION;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
try {
int indexNotificationID = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_ID);
int indexLawID = cursor.getColumnIndex(Constants.KEY_LAW_ID);
int indexNotificationTime = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_TIME);
int indexNotificationType = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_TYPE);
int indexNotificationText = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_TEXT);
int indexNotificationStatus = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_STATUS);
int notificationID = cursor.getInt(indexNotificationID);
int lawID = indexLawID;
String notificationTime = cursor.getString(indexNotificationTime);
String notificationType = cursor.getString(indexNotificationType);
String notificationText = cursor.getString(indexNotificationText);
String notificationStatus = cursor.getString(indexNotificationStatus);
lstNotifications.add(new NotificationModel(notificationID, lawID, notificationType, notificationText, notificationTime, notificationStatus));
} catch (Exception e) {
exceptionHandler.alert(e, "getNotificationList()");
}
cursor.moveToNext();
}
}
close();
Collections.reverse(lstNotifications);
return lstNotifications;
}
}
MainActivity:
sqLiteAdapter.updateLaw(962, "test", "test");
The issue you described is pretty hard to detect in this code but here is a list of notes/best practices you should take into consideration:
You should ALWAYS do your DB queries on a secondary thread and not on your main thread (Try an AsyncTask).
you have a SimpleGestureFilter which I can't say what is for or what it does. If you have some ugly logic there, that may affect scrolling.
You create tons of LayoutInflater variables in your getView() method which is pretty bad. Make it a global variable and initialize it in the Adapter's constructor. Do you have an idea of how many times the getView() method gets called when you scroll? Put a log there and analyse :).
Definitely not hold an instance to your SQLiteAdapter object in the adapter. Do that in your activity and update your adapter when you need it. The Adapter should always be the representation of your data and not doing having logic and whatever else.
Not sure what the FontLoader does but if you read a font from the assets every time the getView() is called, you have a huuuge problem. Try to load fonts as few times as possible because that's a heavy operation.
Never catch general Exceptions. Try to focus on the specific ones.
I have developed basic call recorder application, its working fine on devices with versions below 'lollipop', but when I have to run lollipop devices (Android 5.0) I'm getting this error.
E/MediaRecorder(29786): start failed: -2147483648
java.lang.RuntimeException: start failed.
at android.media.MediaRecorder.start(Native Method)
at com.androiddoc.callRecorder_anirbanjana.CallRecordingService.startRec(CallRecordingService.java:234)
at com.androiddoc.callRecorder_anirbanjana.CallRecordingService.onCreate(CallRecordingService.java:54)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:2763)
at android.app.ActivityThread.access$1800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1375)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
My code is below. When I call recorder.prepare(); and recorder.start(); Now I'm getting above error and I can't work out why. Can anyone advise?
public class CallRecordingService extends Service {
MediaRecorder myRec = new MediaRecorder();
boolean isRecMode = false;
private static final int RECORDER_SAMPLERATE = 8000;
private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
private AudioRecord recorder = null;
private Thread recordingThread = null;
private boolean isRecording = false;
int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,
RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY_COMPATIBILITY;
}
#Override
public void onCreate() {
// Start recording
startRec();
System.out.println("BUFFER SIZE VALUE IS " + bufferSize);
super.onCreate();
}
public void stopRec() {
myRec.reset();
Toast.makeText(CallRecordingService.this, "Rec Stoped",
Toast.LENGTH_SHORT).show();
Log.i("CallRecordingService", "Rec Stoped");
isRecMode = false;
}
public void startRec() {
try {
// String selectedPath = this.getApplicationContext().getFilesDir()
// + "/system_sound";
String selectedPath = Environment.getExternalStorageDirectory()
+ "/Testing";
SimpleDateFormat sdf = new SimpleDateFormat(
"dd_MM_yyyy_hh_mm_ss aa");
String currentDateandTime = sdf.format(new Date());
// Crate folder if not exist
// String packageName = this.getPackageName();
File yourDir = new File(Environment.getExternalStorageDirectory()
+ "/Testing");
// File yourDir = new
// File(this.getApplicationContext().getFilesDir() +
// "/system_sound");
if (!yourDir.exists()) {
yourDir.mkdirs();
}
// String selectedPath =
// Environment.getExternalStorageDirectory().getAbsolutePath() +
// "/Android/data/" + packageName + "/system_sound";
myRec.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
myRec.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
// myRec.setOutputFile(Environment.getExternalStorageDirectory().getPath()+"/my_rec_voice.mp3");
myRec.setOutputFile(selectedPath + "/" + currentDateandTime + "_"
+ getFromPreference("phoneNo") + ".amr");
AudioManager am; // Audio manager
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_IN_CALL);
int volume_level = am
.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
int max_volume = am
.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);
if (volume_level < max_volume) {
am.setStreamVolume(AudioManager.STREAM_VOICE_CALL, max_volume,
AudioManager.FLAG_SHOW_UI);
}
} catch (IllegalStateException e) {
// Log.e("Call recorder IllegalStateException: ", "");
terminateAndEraseFile();
} catch (Exception e) {
// Log.e("Call recorder Exception: ", "");
terminateAndEraseFile();
}
OnErrorListener errorListener = new OnErrorListener() {
public void onError(MediaRecorder arg0, int arg1, int arg2) {
terminateAndEraseFile();
}
};
myRec.setOnErrorListener(errorListener);
try {
Log.v("Call Recorder", "Media recorder prepared");
myRec.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
Log.v("Call Recorder", "Media recorder started ");
myRec.start();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(CallRecordingService.this, "Rec Start",
Toast.LENGTH_SHORT).show();
Log.i("CallRecordingService", "Rec Start");
isRecMode = true;
}
#Override
public void onDestroy() {
stopRec();
//stopRecording();
if (isRecMode) {
// Stop recording
myRec.stop();
}
myRec.release();
super.onDestroy();
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Preference Variable
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// --------------------------------------------
// method to save variable in preference
// --------------------------------------------
public void saveInPreference(String name, String content) {
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(name, content);
editor.commit();
}
// --------------------------------------------
// getting content from preferences
// --------------------------------------------
public String getFromPreference(String variable_name) {
String preference_return;
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
preference_return = preferences.getString(variable_name, "");
return preference_return;
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Preference Variable
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
private void terminateAndEraseFile() {
try {
Toast toast = Toast.makeText(this,
this.getString(R.string.reciever_end_call),
Toast.LENGTH_SHORT);
toast.show();
} catch (IllegalStateException e) {
e.printStackTrace();
}
Toast toast = Toast.makeText(this,
this.getString(R.string.record_impossible), Toast.LENGTH_LONG);
toast.show();
}
}
If you get start failed for VOICE_CALL then use MIC.
VOICE_CALL is allowed only for system apps.
Here is the detailed code:
int audioSource = MediaRecorder.AudioSource.MIC;
mediaRecorder.setAudioSource(audioSource);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mediaRecorder.setAudioEncodingBitRate(32);
mediaRecorder.setAudioSamplingRate(44100);
mediaRecorder.setOutputFile(MediaUri);
mediaRecorder.prepare();
mediaRecorder.start();
I have listview which contains a list of audio files with play button and seekbar.
When I click a play button of a listview I want to play an audio file. I successfully implemented this but when i click another play button in list two audio files are playing continuously, It will continue for all onclick of play button. How can I restrict the mediaplayer to play in one position and if I click a another icon it have to stop the old media player and start to play the new one. Can anyone say me how do I implement this ?.
I have same button for play and pause.
#SuppressLint("NewApi") public class ChatMessageAdapter1 extends BaseAdapter implements UpdatableAdapter, AnimationListener{
public ChatMessageAdapter1(Activity activity)
{
// MediaPlayer mp = new MediaPlayer();
#Override
public int getCount() {
return messages.size() + 1;
}
#Override
public Object getItem(int position) {
if (position < messages.size())
return messages.get(position);
else
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return 3;
}
#Override
public int getItemViewType(int position){
if (position < messages.size())
return TYPE_MESSAGE;
else
return hint == null ? TYPE_EMPTY : TYPE_HINT;
}
//#SuppressLint("RtlHardcoded")
#SuppressLint({ "RtlHardcoded", "NewApi" }) #TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) #Override
public View getView(int position, View convertView, ViewGroup parent)
{
final int type = getItemViewType(position);
final ViewHolder view;
// final View view;
if (convertView == null)
{
final int resource;
if (type == TYPE_MESSAGE)
{
resource = R.layout.chat_viewer_message;
}
else if (type == TYPE_HINT)
resource = R.layout.chat_viewer_info;
else if (type == TYPE_EMPTY)
resource = R.layout.chat_viewer_empty;
else
throw new IllegalStateException();
convertView = activity.getLayoutInflater().inflate(resource, parent, false);
if (type == TYPE_MESSAGE)
{
((TextView) convertView.findViewById(R.id.text)).setTextAppearance(activity, appearanceStyle);
}
view= new ViewHolder();
convertView.setTag(view);
}
else
view = (ViewHolder)convertView.getTag();
//view = convertView;
if (type == TYPE_EMPTY)
return convertView;
if (type == TYPE_HINT) {
TextView textView = ((TextView) convertView.findViewById(R.id.info));
textView.setText(hint);
textView.setTextAppearance(activity, R.style.ChatInfo_Warning);
return convertView;
}
final MessageItem messageItem = (MessageItem) getItem(position);
final String name;
final String account = messageItem.getChat().getAccount();
final String user = messageItem.getChat().getUser();
final String resource = messageItem.getResource();
final boolean incoming = messageItem.isIncoming();
final String messageText = messageItem.getText();
if (isMUC)
{
name = resource;
}
else
name = "";
convertView.setBackgroundColor(Color.TRANSPARENT);
view.textView = (TextView) convertView.findViewById(R.id.text);
final RelativeLayout layoutImage = (RelativeLayout) convertView.findViewById(R.id.layoutImage);
RelativeLayout layoutAudio = (RelativeLayout) convertView.findViewById(R.id.layoutAudio);
view.imgView1 = (ImageView) convertView.findViewById(R.id.attachedImageNvideoShowAyushi);
view.iconImageNvideo = (ImageView) convertView.findViewById(id.iconOnTopOfImageNVideo);
view.imgAudioPlay = (ImageButton) convertView.findViewById(R.id.attachedAUDIOtattlePLAY);
view.avatarView = (ImageView) convertView.findViewById(R.id.avatar);
view.audioSeekBar = (SeekBar) convertView.findViewById(R.id.SeekBarAudioTattle);
view.audioDuration =(TextView) convertView.findViewById(R.id.audioLengthTattle);
view.dateTimeTattle = (TextView) convertView.findViewById(R.id.tattleDateTimeOnChatPage);
view.statusTattle = (ImageView) convertView.findViewById(R.id.tattleStatusOnChatPage);
view.datePast = (TextView) convertView.findViewById(R.id.pastDate);
// view.tabhost = (TabHost) convertView.findViewById(R.id.tabhostAttach);
if(builder.toString().contains("ABCDEF_AUDIO"))
{
layoutAudio.setVisibility(View.VISIBLE);
final MediaPlayer mp;
final Handler durationHandler = new Handler();
view.audioSeekBar.setClickable(true);
view.audioSeekBar.setVisibility(View.VISIBLE);
view.imgView1.setVisibility(View.GONE);
view.iconImageNvideo.setVisibility(View.GONE);
view.textView.setVisibility(View.GONE);
String path = messageItem.getText();
//System.out.println("AUDIO path : " + path);
File PathDirectoryCHECK= new File(Environment.getExternalStorageDirectory().toString() + "/ABCDEF/ABCDEF_AUDIO");
final File PathofAudioCHECK = new File(PathDirectoryCHECK.getPath() + File.separator + path);
//System.out.println("PathofAudioCHECK : " + PathofAudioCHECK);
mp = new MediaPlayer();
mp.setLooping(false);
final Runnable runnableAudio = new Runnable()
{
public void run()
{
timeElapsed = mp.getCurrentPosition();
view.audioSeekBar.setProgress((int) timeElapsed);
finalTime = mp.getDuration();
double timeRemaining = finalTime - timeElapsed;
view.audioDuration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));
durationHandler.postDelayed(this, 100);
}
};
try {
if(PathofAudioCHECK.isFile())
{
final Uri audioUri=Uri.fromFile(PathofAudioCHECK);
mp.setDataSource(activity,audioUri);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepare();
finalTime = mp.getDuration();
view.audioSeekBar.setMax((int) finalTime);
int duration = mp.getDuration();
if(duration==-1)
view.audioDuration.setText("");
else
view.audioDuration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((int) duration), TimeUnit.MILLISECONDS.toSeconds((int) duration)));
view.audioSeekBar.setOnTouchListener(new OnTouchListener()
{
#SuppressLint("ClickableViewAccessibility") #Override
public boolean onTouch(View v, MotionEvent event)
{
if(mp.isPlaying())
{
SeekBar sb = (SeekBar)v;
mp.seekTo(sb.getProgress());
}
return false;
}
});
view.imgAudioPlay.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
//System.out.println("test");s
//System.out.println(""+mp.toString()+"---"+mp.isPlaying());
if(mp.isPlaying() && mp!=null)
{
// mp.pause();
mp.stop();
mp.reset();
mp.release();
if(incoming) {
view.imgAudioPlay.setImageResource(R.drawable.audio_play_incoming_tattle);
}
else {
view.imgAudioPlay.setImageResource(R.drawable.audio_play_outgoing_tattle);
}
}
else if(!mp.isPlaying())
{
if(mp!=null)
{
/*try {
mp.setDataSource(activity,audioUri);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepare();
}
catch (IllegalStateException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}*/
mp.start();
if(incoming)
{
view.imgAudioPlay.setImageResource(R.drawable.audio_pause_incoming_tattle);
}
else
{
view.imgAudioPlay.setImageResource(R.drawable.audio_pause__outgoing_tattle);
}
timeElapsed = mp.getCurrentPosition();
view.audioSeekBar.setProgress((int) timeElapsed);
durationHandler.postDelayed(runnableAudio, 100);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
view.audioSeekBar.setProgress(0);
mp.seekTo(0);
mp.reset();
mp.stop();
mp.release();
durationHandler.removeCallbacks(runnableAudio);
}
});
mp.setOnSeekCompleteListener(new OnSeekCompleteListener()
{
public void onSeekComplete(MediaPlayer mp) {
view.audioSeekBar.setProgress(0);
mp.reset();
mp.stop();
//mp.release();
durationHandler.removeCallbacks(runnableAudio);
}
});
}}
}
catch (IllegalStateException e) {
e.printStackTrace();
}
}});
}
else if(!PathofAudioCHECK.isFile() || PathofAudioCHECK==null)
{
if(incoming)
{
if(counterDOWNLOADfromSERVER!=1)
{
counterDOWNLOADfromSERVER=1;
String[] parts = path.split("\\."); // String array, each element is text between dots
String beforeFirstDot = parts[0];
String pathSubStr=beforeFirstDot.substring(13);
// System.out.println("BUILDER name ID : " + pathSubStr);
String url = configurationsFileTransfer.FILE_URL_TRANSFER + pathSubStr;
new HttpAsyncTaskforAudio().execute(url);
//System.out.println("AUDIo received : " + get_newPathofAUDIOreceived());
try
{
if(get_newPathofAUDIOreceived().exists() || get_newPathofAUDIOreceived().isFile() || get_newPathofAUDIOreceived()!=null)
{
final Uri audioUri=Uri.fromFile(get_newPathofAUDIOreceived());
mp.setDataSource(activity,audioUri);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepare();
finalTime = mp.getDuration();
view.audioSeekBar.setMax((int) finalTime);
view.audioSeekBar.setMax(mp.getDuration());
int duration = mp.getDuration();
if(duration==-1)
view.audioDuration.setText("");
else
view.audioDuration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((int) duration), TimeUnit.MILLISECONDS.toSeconds((int) duration)));
view.audioSeekBar.setOnTouchListener(new OnTouchListener()
{
#SuppressLint("ClickableViewAccessibility") #Override
public boolean onTouch(View v, MotionEvent event)
{
if(mp.isPlaying())
{
SeekBar audioSeekBar = (SeekBar)v;
mp.seekTo(audioSeekBar.getProgress());
}
return false;
}
});
view.imgAudioPlay.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if(mp.isPlaying() && mp!=null)
{
mp.pause();
if(incoming)
{
view.imgAudioPlay.setImageResource(R.drawable.audio_pause_incoming_tattle);
}
else
{
view.imgAudioPlay.setImageResource(R.drawable.audio_pause__outgoing_tattle);
}
}
else if(!mp.isPlaying())
{
if(mp!=null)
{
try {
mp.setDataSource(activity,audioUri);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
if(incoming)
{
view.imgAudioPlay.setImageResource(R.drawable.audio_play_incoming_tattle);
}
else
{
view.imgAudioPlay.setImageResource(R.drawable.audio_play_outgoing_tattle);
}
timeElapsed = mp.getCurrentPosition();
view.audioSeekBar.setProgress((int) timeElapsed);
durationHandler.postDelayed(runnableAudio, 100);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.seekTo(0);
mp.reset();
mp.stop();
//mp.release();
durationHandler.removeCallbacks(runnableAudio);
}
});
}
}
}
});
}
else
{
System.out.println("Audio Deleted! 1 ");
}
}
catch(NullPointerException e)
{
System.out.println("null error : " + e.getMessage());
}
}
else
{ }
}
else
{ System.out.println("Audio Deleted! 2");
}
}
}
catch(NullPointerException e)
{
//String pathA = messageItem.getText();
//System.out.println("AUDIO path A : " + pathA);
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
// mp.setOnSeekCompleteListener(new OnSeekCompleteListener()
// {
// public void onSeekComplete(MediaPlayer mp) {
// audioSeekBar.setProgress(0);
// mp.reset();
// mp.stop();
// mp.release();
// mp=null;
// durationHandler.removeCallbacks(runnableAudio);
// }
// });
if(activity.isChangingConfigurations())
{
mp.stop();
mp.reset();
//mp.release();
}
if (activity.isFinishing()){
mp.stop();
mp.reset();
//mp.release();
}
}
return convertView;
}
public String getAccount() {
return account;
}
public String getUser() {
return user;
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private File newPathDirectoryforAudio;
private static File newPathofAUDIOreceived;
private String fid_response_audio;
private class HttpAsyncTaskforAudio extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls)
{
return GET(urls[0]);
}
#Override
protected void onPostExecute(String result)
{
// System.out.println("RESULT AUDIO : " + result);
JSONObject json;
try {
json = new JSONObject(result);
fid_response=json.getString("fid");
String fileNAME_response=json.getString("name");
String audioUrl = configurationsFileTransfer.FILE_URL_MEDIA + fileNAME_response;
// System.out.println("audioURL : " + audioUrl);
set_fid_response_audio(fid_response_audio);
new DownloadFileAUDIOfromURL().execute(audioUrl);
} catch (JSONException e)
{
e.printStackTrace();
}
}
}
class DownloadFileAUDIOfromURL extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... f_url) {
int count;
try
{
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
newPathDirectoryforAudio = new File(Environment
.getExternalStorageDirectory().toString() + "/TATTLE/TATTLE_AUDIO");
if(!newPathDirectoryforAudio.exists())
{
newPathDirectoryforAudio.mkdirs();
}
newPathofAUDIOreceived = new File(newPathDirectoryforAudio.getPath() + File.separator + "TATTLE_AUDIO_"+ get_fid_response() + ".mp3");
set_newPathofAUDIOreceived(newPathofAUDIOreceived);
OutputStream output = new FileOutputStream(newPathofAUDIOreceived);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1)
{
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e)
{
Log.e("Error: ", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String file_url)
{
// System.out.println("Set incoming audios from this path : " + newPathofAUDIOreceived.toString());
set_newPathofAUDIOreceived(newPathofAUDIOreceived);
notifyDataSetChanged();
}
}
private void set_fid_response_audio(String fid_response_audio)
{
this.fid_response_audio= fid_response_audio;
}
// private String get_fid_response_audio()
// {
// return fid_response_audio;
// }
private static void set_newPathofAUDIOreceived(File newPathofAUDIOreceived)
{
ChatMessageAdapter.newPathofAUDIOreceived= newPathofAUDIOreceived;
}
private static File get_newPathofAUDIOreceived()
{
return newPathofAUDIOreceived;
}
if(builder.toString().contains("ABCDEF_AUDIO"))
{
layoutAudio.setVisibility(View.VISIBLE);
final MediaPlayer mp;
final Handler durationHandler = new Handler();
view.audioSeekBar.setClickable(true);
view.audioSeekBar.setVisibility(View.VISIBLE);
view.imgView1.setVisibility(View.GONE);
view.iconImageNvideo.setVisibility(View.GONE);
view.textView.setVisibility(View.GONE);
String path = messageItem.getText();
//System.out.println("AUDIO path : " + path);
File PathDirectoryCHECK= new File(Environment.getExternalStorageDirectory().toString() + "/ABCDEF/ABCDEF_AUDIO");
final File PathofAudioCHECK = new File(PathDirectoryCHECK.getPath() + File.separator + path);
//System.out.println("PathofAudioCHECK : " + PathofAudioCHECK);
mp = new MediaPlayer();
mp.setLooping(false);
final Runnable runnableAudio = new Runnable()
{
public void run()
{
timeElapsed = mp.getCurrentPosition();
view.audioSeekBar.setProgress((int) timeElapsed);
finalTime = mp.getDuration();
double timeRemaining = finalTime - timeElapsed;
view.audioDuration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));
durationHandler.postDelayed(this, 100);
}
};
try {
if(PathofAudioCHECK.isFile())
{
final Uri audioUri=Uri.fromFile(PathofAudioCHECK);
mp.setDataSource(activity,audioUri);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepare();
finalTime = mp.getDuration();
view.audioSeekBar.setMax((int) finalTime);
int duration = mp.getDuration();
if(duration==-1)
view.audioDuration.setText("");
else
view.audioDuration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((int) duration), TimeUnit.MILLISECONDS.toSeconds((int) duration)));
view.audioSeekBar.setOnTouchListener(new OnTouchListener()
{
#SuppressLint("ClickableViewAccessibility") #Override
public boolean onTouch(View v, MotionEvent event)
{
if(mp.isPlaying())
{
SeekBar sb = (SeekBar)v;
mp.seekTo(sb.getProgress());
}
return false;
}
});
view.imgAudioPlay.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
if(isPlaying && !mp.isPlaying() && mp!=null)
{
mpG.pause();
}
if(mp!=null && mp.isPlaying())
{
mp.pause();
isPlaying = false;
}
else if(!mp.isPlaying())
{
if(mp!=null)
{
mpG = mp;
isPlaying = true;
vhG = view;
mp.start();
timeElapsed = mp.getCurrentPosition();
view.audioSeekBar.setProgress((int) timeElapsed);
durationHandler.postDelayed(runnableAudio, 100);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
view.audioSeekBar.setProgress(0);
mp.seekTo(0);
mp.reset();
mp.stop();
isPlaying = false;
mp.release();
durationHandler.removeCallbacks(runnableAudio);
notifyDataSetChanged();
}
});
mp.setOnSeekCompleteListener(new OnSeekCompleteListener()
{
public void onSeekComplete(MediaPlayer mp) {
// System.out.println("Audio : 6");
view.audioSeekBar.setProgress(0);
mp.reset();
mp.stop();
isPlaying = false;
mp.release();
durationHandler.removeCallbacks(runnableAudio);
notifyDataSetChanged();
}
});
}
}
}
catch (IllegalStateException e) {
e.printStackTrace();
}
}});
}
else if(!PathofAudioCHECK.isFile() || PathofAudioCHECK==null)
{
if(incoming)
{
if(counterDOWNLOADfromSERVER!=1)
{
counterDOWNLOADfromSERVER=1;
String[] parts = path.split("\\."); // String array, each element is text between dots
String beforeFirstDot = parts[0];
String pathSubStr=beforeFirstDot.substring(13);
// System.out.println("BUILDER name ID : " + pathSubStr);
String url = configurationsFileTransfer.FILE_URL_TRANSFER + pathSubStr;
new HttpAsyncTaskforAudio().execute(url);
//System.out.println("AUDIo received : " + get_newPathofAUDIOreceived());
try
{
if(get_newPathofAUDIOreceived().exists() || get_newPathofAUDIOreceived().isFile() || get_newPathofAUDIOreceived()!=null)
{
final Uri audioUri=Uri.fromFile(get_newPathofAUDIOreceived());
mp.setDataSource(activity,audioUri);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepare();
finalTime = mp.getDuration();
view.audioSeekBar.setMax((int) finalTime);
view.audioSeekBar.setMax(mp.getDuration());
int duration = mp.getDuration();
if(duration==-1)
view.audioDuration.setText("");
else
view.audioDuration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((int) duration), TimeUnit.MILLISECONDS.toSeconds((int) duration)));
view.audioSeekBar.setOnTouchListener(new OnTouchListener()
{
#SuppressLint("ClickableViewAccessibility") #Override
public boolean onTouch(View v, MotionEvent event)
{
if(mp.isPlaying())
{
SeekBar audioSeekBar = (SeekBar)v;
mp.seekTo(audioSeekBar.getProgress());
}
return false;
}
});
view.imgAudioPlay.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if(isPlaying && !mp.isPlaying() && mp!=null){
mpG.pause();
}
if(mp.isPlaying() && mp!=null)
{
mp.pause();
isPlaying = false;
}
else if(!mp.isPlaying())
{
if(mp!=null)
{
try {
mp.setDataSource(activity,audioUri);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mpG = mp;
isPlaying = true;
vhG = view;
mp.start();
timeElapsed = mp.getCurrentPosition();
view.audioSeekBar.setProgress((int) timeElapsed);
durationHandler.postDelayed(runnableAudio, 100);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.seekTo(0);
mp.reset();
mp.stop();
isPlaying = false;
durationHandler.removeCallbacks(runnableAudio);
}
});
}
}
}
});
}
else
{
System.out.println("Audio Deleted! 1 ");
}
}
catch(NullPointerException e)
{
System.out.println("null error : " + e.getMessage());
}
}
else
{ }
}
else
{ System.out.println("Audio Deleted! 2");
}
}
}
catch(NullPointerException e)
{
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
if(activity.isChangingConfigurations())
{
mp.stop();
mp.reset();
}
if (activity.isFinishing()){
mp.stop();
mp.reset();
}
}