Android writing file issue while setting song as Ringtone - android

I have successfully written a program to set song as Ringtone, but facing a very small issue
When i do tap on Button first time to set song as ringtone, getting this:
But when I do click on button again (second time), getting this:
So What could be the reason ? Why i never get success in first time...
Here is the complete code of RingtoneActivity.java:
public class RingtoneActivity extends Activity {
private final Context context = this;
private static final String TAG = "Meri Desi Look";
private File sound;
private final File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES);
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonRingtone = (Button) findViewById(R.id.btnRingtone);
buttonRingtone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ask();
}
});
}
private void ask() {
mediaPlayer = MediaPlayer.create(this, R.raw.meri_desi_look);
mediaPlayer.start();
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Meri Desi Look");
alert.setMessage("You want this sound as your ringtone?");
alert.setCancelable(false);
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
mediaPlayer.stop();
mediaPlayer.reset();
confirmed();
dialog.dismiss();
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
mediaPlayer.stop();
mediaPlayer.reset();
dialog.dismiss();
}
});
alert.show();
}
/**
* When the user confirms the popup, this will run, saving the file and
* setting the ringtone utilising the RingtoneManager class.
*/
private void confirmed() {
Boolean success = false;
sound = new File(folder, "meri_desi_look.mp3");
if (!sound.exists()) {
Log.i(TAG, "Writing Meri Desi Look to " + folder.toString());
try {
InputStream in = getResources().openRawResource(R.raw.meri_desi_look);
FileOutputStream out = new FileOutputStream(sound.getPath());
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
} catch (Exception e) {
success = false;
Log.i(TAG, "Desi Look failed to write.");
}
} else {
success = true;
Log.i(TAG, "Meri Desi Look ringtone already there.");
}
if (!success) {
onSetRingtoneError("We couldn't give you a Meri Desi Look ringtone.\n\nThere's an issue writing the file.");
} else {
setRingtone();
}
}
/**
* Physically sets the RingtoneManager preferences.
*/
private void setRingtone() {
try {
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, sound.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "Meri Desi Look - performed by Sunny Leone");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
values.put(MediaStore.Audio.Media.ARTIST, "Meri Desi Look");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, true);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(sound.getAbsolutePath());
getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + sound.getAbsolutePath() + "\"",
null);
Uri newUri = getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);
onSetRingtoneSuccess();
} catch (Exception e) {
onSetRingtoneError("We couldn't give you a Meri Desi Look ringtone.\n\nThere's an issue setting the file.");
}
}
/**
* Generic helper to show error messages (if ever there are any) :p
*
* #param message
*/
private void onSetRingtoneError(String message) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Meri Desi Look");
alert.setMessage(message);
alert.setCancelable(false);
alert.setPositiveButton("OK. That's too bad.", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
alert.show();
}
private void onSetRingtoneSuccess() {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Meri Desi Look");
alert.setMessage("You've got the ringtone :)\n\nHope you enjoy it!");
alert.setCancelable(false);
alert.setPositiveButton("Sweet!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
alert.show();
}
#Override
protected void onPause() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
super.onPause();
}
}

I think you must have figured out long ago where the issue is in the code. But if you didn't,try the following.
private void confirmed() {
...
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
success = true;
}
catch(Exception e) {
success = false;
e.printStackTrace();
}
finally {
n.close();
out.close();
}
...
}

Related

If Recyclerview scroll then item id change how to resolve?

public PDFListAdapter(Context context, ArrayList<NotesResponseInfo> pdfModelClasses, String final_nav_opt_name) {
this.context = context;
this.pdfModelClasses = pdfModelClasses;
this.final_nav_opt_name = final_nav_opt_name;
databaseNotes = new DatabaseNotes(context);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView txtBookName, txtBookTitle, txtBookBookDateOFIssue, txtBookCategory, txtDownload;
LinearLayout layout_open_pdf, layout_download_note_option;
ImageView imgDownloadNote, imgCancelDownloadNote;
ProgressBar progress_download_note;
public MyViewHolder(View view) {
super(view);
txtBookName = (TextView) view.findViewById(R.id.txtBookName);
txtBookTitle = (TextView) view.findViewById(R.id.txtBookTitle);
txtBookBookDateOFIssue = (TextView) view.findViewById(R.id.txtBookBookDateOFIssue);
txtBookCategory = (TextView) view.findViewById(R.id.txtBookCategory);
txtDownload = view.findViewById(R.id.txtDownload);
layout_open_pdf = (LinearLayout) view.findViewById(R.id.layout_open_pdf);
layout_download_note_option = (LinearLayout) view.findViewById(R.id.layout_download_note_option);
imgDownloadNote = (ImageView) view.findViewById(R.id.imgDownloadNote);
progress_download_note = (ProgressBar) view.findViewById(R.id.progress_download_note);
imgCancelDownloadNote = (ImageView) view.findViewById(R.id.imgCancelDownloadNote);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.layout_pdf_adapter, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder1, int index) {
holder = holder1;
final int position = index;
pdfList = pdfModelClasses.get(position);
final DownloadedNotesDataBase databaseNotes = new DownloadedNotesDataBase(context);
holder.txtBookName.setText(pdfList.getSubjectName().toUpperCase());
holder.txtBookTitle.setText(StringUtils.getTrimString(pdfList.getTypeName()));
holder.txtBookBookDateOFIssue.setText(pdfList.getType());
holder.txtBookCategory.setText(StringUtils.getTrimString(pdfList.getDescription()));
if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
holder.txtDownload.setVisibility(View.VISIBLE);
holder.layout_download_note_option.setVisibility(View.GONE);
} else {
holder.txtDownload.setVisibility(View.GONE);
holder.layout_download_note_option.setVisibility(View.VISIBLE);
}
holder.layout_open_pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pdfList = pdfModelClasses.get(position);
// holder = holder1;
Log.e("PDFListAdapter", "layout_open_pdf position = "+position);
Log.e("PDFListAdapter", "layout_open_pdf = "+pdfList.getId());
if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
DownloadeNotesModel downloadeNotesModel = databaseNotes.getNotesByID(pdfList.getId(), final_nav_opt_name);
Intent intent = new Intent(context, PDFResults.class);
intent.putExtra("pdfList", downloadeNotesModel.getFileLocation());
intent.putExtra("from", "database");
intent.putExtra("getSubjectName", downloadeNotesModel.getSubjectName());
context.startActivity(intent);
} else {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Alert");
alertDialog.setCancelable(true);
alertDialog.setMessage("Notes not downloaded. Do you want to download it?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
downloader = new Downloader();
new CheckSpace().execute(pdfList.getFileName());
}
});
/* alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(context, PDFResults.class);
intent.putExtra("pdfList", pdfList.getFileName());
intent.putExtra("from", "url");
intent.putExtra("getSubjectName", pdfList.getSubjectName());
context.startActivity(intent);
}
});*/
alertDialog.show();
}
}
});
holder.imgDownloadNote.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
#Override
public void onClick(View v) {
Log.e("PDFListAdapter", "imgDownloadNote position = "+position);
Log.e("PDFListAdapter", "imgDownloadNote = "+pdfList.getId());
pdfList = pdfModelClasses.get(position);
holder = holder1;
if (!databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
if (UtilsMethods.isNetworkAvailable(context)) {
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
downloader = new Downloader();
new CheckSpace().execute(pdfList.getFileName());
} else {
Toast.makeText(context, "storage permission is not granted", Toast.LENGTH_SHORT).show();
PermissionCheck.checkWritePermission(context);
}
} else {
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
context.startActivity(new Intent(context, NoInternetActivity.class));
}
}
else Log.e("","Not in db");
}
});
holder.imgCancelDownloadNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("PDFListAdapter", "imgCancelDownloadNote position = "+position);
Log.e("PDFListAdapter", "imgCancelDownloadNote = "+pdfList.getId());
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Are you sure want to cancel download?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
downloader.cancel(true);
}
});
alertDialog.show();
}
});
}
#Override
public int getItemCount() {
return pdfModelClasses.size();
}
#Override
public int getItemViewType(int position)
{
return position;
}
private void startSave(final Context context, NotesResponseInfo url) {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
final base_url b = new base_url();
Retrofit.Builder builder = new Retrofit.Builder().baseUrl(b.BASE_URL);
Retrofit retrofit = builder.client(httpClient.build()).build();
AllApis downloadService = retrofit.create(AllApis.class);
Call<ResponseBody> call = downloadService.downloadFileByUrl(StringUtils.getCroppedUrl(url.getFileName()));
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(context);
downloader.execute(response.body());
} else {
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
}
private class Downloader extends AsyncTask<ResponseBody, Integer, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mBuilder.setContentTitle("Download")
.setContentText("Download in progress")
.setSmallIcon(R.mipmap.lun);
mBuilder.setProgress(100, 0, false);
mNotifyManager.notify(id, mBuilder.build());
}
#Override
protected void onProgressUpdate(Integer... values) {
mBuilder.setContentTitle("Download")
.setContentText("Download in progress")
.setSmallIcon(R.mipmap.lun);
mBuilder.setProgress(100, values[0], false);
mNotifyManager.notify(id, mBuilder.build());
super.onProgressUpdate(values);
}
#Override
protected void onCancelled() {
super.onCancelled();
holder.imgDownloadNote.setVisibility(View.VISIBLE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
mNotifyManager.cancelAll();
}
#Override
protected Integer doInBackground(ResponseBody... params) {
ResponseBody body = params[0];
try {
URL url = new URL(pdfList.getFileName());
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestProperty("Accept-Encoding", "identity");
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
ContextWrapper wrapper = new ContextWrapper(getApplicationContext());
int lenghtOfFile = c.getContentLength();
Log.w("getContentLength",""+lenghtOfFile);
File file = wrapper.getDir("PDF", MODE_PRIVATE);
file = new File(file, pdfList.getSubjectName() + "_" + TimeUtils.getCurrentTimeStamp() + ".pdf");
FileOutputStream f = new FileOutputStream(file);
InputStream in = c.getInputStream();
float finalValue = 0;
byte[] buffer = new byte[100 * 1024];
int len1 = 0;
int progress = 0;
long total = 0;
if (!(isCancelled())) {
while ((len1 = in.read(buffer)) !=-1) {
if (UtilsMethods.isNetworkAvailable(context)) {
f.write(buffer, 0, len1);
total += len1;
setProgress(Integer.parseInt(("" + (int) ((total * 100) / lenghtOfFile))));
/* progress += len1;finalValue = (float) progress/body.contentLength() *100;
setProgress((int) finalValue);
mBuilder.setProgress((int) finalValue,0,false);*/
} else {
File file1 = new File(file.getPath());
file1.delete();
cancel(true);
}
}
new DownloadedNotesDataBase(context).addDonloadedNotesToDatabase(file.getPath(), pdfList);
} else {
File file1 = new File(file.getPath());
file1.delete();
holder.imgDownloadNote.setVisibility(View.VISIBLE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
Toast.makeText(context, "Cancelled", Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (ProtocolException e1) {
e1.printStackTrace();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
mBuilder.setContentText("Download complete");
mBuilder.setSmallIcon(R.mipmap.ic_logo);
mBuilder.setProgress(100, 100, false);
mNotifyManager.notify(id, mBuilder.build());
holder.txtDownload.setVisibility(View.VISIBLE);
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
}
private void setProgress(int progress) {
mBuilder.setContentText("Downloading...")
.setContentTitle(progress + "%")
.setSmallIcon(R.mipmap.ic_logo)
.setOngoing(true)
.setContentInfo(progress + "%")
.setProgress(100, progress, false);
mNotifyManager.notify(id, mBuilder.build());
holder.progress_download_note.setProgress(progress);
}
}
public class CheckSpace extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String file_size = "";
URL url = null;
try {
url = new URL(params[0]);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int fileSize = urlConnection.getContentLength();
file_size = UtilsMethods.generateFileSize(fileSize);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return file_size;
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
#Override
protected void onPostExecute(String result) {
if (UtilsMethods.compareSpace(result)) {
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Download this PDF of size " + result + " ?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.VISIBLE);
holder.progress_download_note.setVisibility(View.VISIBLE);
startSave(context, pdfList);
}
});
alertDialog.show();
} else {
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Unable to download file. Storage space is not available");
alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
}
});
alertDialog.show();
}
}
}
}
this is my adapter class
I have a RecyclerView. Each row has a Download button, Cancale button, and Progressbar. when click on the Download button have to Download PDF from my phone storage and have to progress Progressbar The problem is when I scroll down the recyclerview the change item Id .means I can fit 1 items on the screen at once.then scroll ItemId change

Class Context from other class android

I have two Classes (MainActivity & Dialogs)
I am trying to call the Dialogs Class (which as a context) to the MainAcitivity;
I have tried
Dialogs WorkOnDialog = (Dialogs)context;
WorkOnDialog.WorkOnSavedDialog();
This is my MainAcitivty
public class MainActivity extends AppCompatActivity {
Context context = this;
boolean WorkOn = false;
boolean WorkOff = false;
Dialogs WorkOnSaveDialog;
// Dialogs WorkOnSaveDialog = (Dialogs) context;
// Dialogs WorkOffSaveDialog = (Dialogs)context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//Press Work On Button
public void WorkOnClicked(View v) {
//Creates ImageButton var for ActionListener
ImageButton WorkOnClicked = (ImageButton) findViewById(R.id.WorkOn);
WorkOnClicked.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Gets & Sets Date, Filename, Data Content
// Creates Output Stream to save to file
String nowDate = DateFormat.getDateTimeInstance().format(new Date());
String filename = "WorkOnFile";
String string = nowDate + " Work On";
FileOutputStream outputStream;
File file = new File(Environment.getDataDirectory(), filename);
System.out.println("Work On Button CLicked");
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
System.out.println("!Wrote " + string + " !");
System.out.println("Wrote at " + file);
WorkOn = true;
} catch (Exception e) {
e.printStackTrace();
}
Dialogs WorkOnDialog = (Dialogs)context;
WorkOnDialog.WorkOnSavedDialog();
}
});
}
//Press WorkOff Button
public void WorkOffClicked(View v) {
//Creates ImageButton var for ActionListener
ImageButton WorkOffClicked = (ImageButton) findViewById(R.id.WorkOff);
WorkOffClicked.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Gets & Sets Date, Filename, Data Content
// Creates Output Stream to save to file
String nowDate = DateFormat.getDateTimeInstance().format(new Date());
String filename = "WorkOffFile";
String string = nowDate + " Work Off";
FileOutputStream outputStream;
File file = new File(Environment.getDataDirectory(), filename);
System.out.println(" Work Off Button CLicked");
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
System.out.println("!Wrote " + string + " !");
System.out.println("Wrote at " + file);
WorkOn=false;
} catch (Exception e) {
e.printStackTrace();
}
// WorkOffSaveDialog.WorkOffSavedDialog();
}
});
This is my Dialogs class
public class Dialogs extends AppCompatActivity {
public Context context = this;
public void WorkOnSavedDialog() {
new AlertDialog.Builder(context)
.setTitle("Work On File Saved")
.setMessage("[Displaying for Test] Work On File Saved")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
public void WorkOffSavedDialog() {
new AlertDialog.Builder(context)
.setTitle("Work Off File Saved")
.setMessage("[Displaying for Test] Work Off File Saved")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
Can anyone explain to me why I am unable to call this "Dialogs" Class within the main method?
I have searched about calling methods with context, and everything I found did not work out, what exactly is going wrong and why?
You need to make constructor to your Dialog class and pass the MainActivity context to this constructor :
public class Dialogs extends AppCompatActivity {
public Context context;
public Dialogs(Context context) {
this.context = context;
}
public void WorkOnSavedDialog() {
new AlertDialog.Builder(context)
.setTitle("Work On File Saved")
.setMessage("[Displaying for Test] Work On File Saved")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
public void WorkOffSavedDialog() {
new AlertDialog.Builder(context)
.setTitle("Work Off File Saved")
.setMessage("[Displaying for Test] Work Off File Saved")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}

How to play an audio from soundcloud in our app.?

Following program allows user to upload an audio from app to SoundCloud.But what if i need to play an audio from my account in soundcloud in my app?How to play an audio from soundcloud or from particular url of soundclous to in our app ?
public class Record extends Activity {
public static final String TAG = "soundcloud-intent-sharing-example";
private boolean mStarted;
private MediaRecorder mRecorder;
private File mArtwork;
private static boolean AAC_SUPPORTED = Build.VERSION.SDK_INT >= 10;
private static final int PICK_ARTWORK = 1;
private static final int SHARE_SOUND = 2;
private static final File FILES_PATH = new File(
Environment.getExternalStorageDirectory(),
"Android/data/com.soundcloud.android.examples/files");
private static final File RECORDING = new File(
FILES_PATH,
"demo-recording" + (AAC_SUPPORTED ? ".mp4" : "3gp"));
private static final Uri MARKET_URI = Uri.parse("market://details?id=com.soundcloud.android");
private static final int DIALOG_NOT_INSTALLED = 0;
// Replace with the client id of your registered app!
// see http://soundcloud.com/you/apps/
private static final String CLIENT_ID = "fecfc092de134a960dc48e53c044ee91";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Environment.MEDIA_MOUNTED.equals(
Environment.getExternalStorageState())) {
if (!FILES_PATH.mkdirs()) {
Log.w(TAG, "Could not create " + FILES_PATH);
}
} else {
Toast.makeText(this, R.string.need_external_storage, Toast.LENGTH_LONG).show();
finish();
}
setContentView(R.layout.record);
final Button record_btn = (Button) findViewById(R.id.record_btn);
final Button share_btn = (Button) findViewById(R.id.share_btn);
final Button play_btn = (Button) findViewById(R.id.play_btn);
final Button artwork_btn = (Button) findViewById(R.id.artwork_btn);
Record last = getLastNonConfigurationInstance();
if (last != null) {
mStarted = last.mStarted;
mRecorder = last.mRecorder;
mArtwork = last.mArtwork;
record_btn.setText(mStarted ? R.string.stop : R.string.record);
}
record_btn.setOnClickListener(new View.OnClickListener() {
public synchronized void onClick(View v) {
if (!mStarted) {
Toast.makeText(Record.this, R.string.recording, Toast.LENGTH_SHORT).show();
mStarted = true;
mRecorder = getRecorder(RECORDING, AAC_SUPPORTED);
mRecorder.start();
record_btn.setText(R.string.stop);
} else {
Toast.makeText(Record.this, R.string.recording_stopped, Toast.LENGTH_SHORT).show();
mRecorder.stop();
mRecorder.release();
mRecorder = null;
mStarted = false;
record_btn.setText(R.string.record);
share_btn.setEnabled(true);
play_btn.setEnabled(true);
artwork_btn.setEnabled(true);
}
}
});
play_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
play_btn.setEnabled(false);
record_btn.setEnabled(false);
share_btn.setEnabled(false);
play(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
play_btn.setEnabled(true);
record_btn.setEnabled(true);
share_btn.setEnabled(true);
}
});
}
});
share_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
shareSound();
}
});
artwork_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"), PICK_ARTWORK);
}
});
if (!isCompatibleSoundCloudInstalled(this)) {
showDialog(DIALOG_NOT_INSTALLED);
}
}
private void play(MediaPlayer.OnCompletionListener onCompletion) {
MediaPlayer player = new MediaPlayer();
try {
player.setDataSource(RECORDING.getAbsolutePath());
player.prepare();
player.setOnCompletionListener(onCompletion);
player.start();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// the actual sharing happens here
private void shareSound() {
Intent intent = new Intent("com.soundcloud.android.SHARE")
.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(RECORDING))
// here you can set metadata for the track to be uploaded
.putExtra("com.soundcloud.android.extra.title", "SoundCloud Android Intent Demo upload")
.putExtra("com.soundcloud.android.extra.where", "Somewhere")
.putExtra("com.soundcloud.android.extra.description", "This is a demo track.")
.putExtra("com.soundcloud.android.extra.public", true)
.putExtra("com.soundcloud.android.extra.tags", new String[] {
"demo",
"post lolcat bluez",
"soundcloud:created-with-client-id="+CLIENT_ID
})
.putExtra("com.soundcloud.android.extra.genre", "Easy Listening")
.putExtra("com.soundcloud.android.extra.location", getLocation());
// attach artwork if user has picked one
if (mArtwork != null) {
intent.putExtra("com.soundcloud.android.extra.artwork", Uri.fromFile(mArtwork));
}
try {
startActivityForResult(intent, SHARE_SOUND);
} catch (ActivityNotFoundException notFound) {
// use doesn't have SoundCloud app installed, show a dialog box
showDialog(DIALOG_NOT_INSTALLED);
}
}
#Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case SHARE_SOUND:
// callback gets executed when the SoundCloud app returns
if (resultCode == RESULT_OK) {
Toast.makeText(this, R.string.shared_ok, Toast.LENGTH_SHORT).show();
} else {
// canceled
Toast.makeText(this, R.string.shared_canceled, Toast.LENGTH_SHORT).show();
}
break;
case PICK_ARTWORK:
if (resultCode == RESULT_OK) {
mArtwork = getFromMediaUri(getContentResolver(), data.getData());
}
break;
}
}
private MediaRecorder getRecorder(File path, boolean useAAC) {
MediaRecorder recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
if (useAAC) {
recorder.setAudioSamplingRate(44100);
recorder.setAudioEncodingBitRate(96000);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
} else {
// older version of Android, use crappy sounding voice codec
recorder.setAudioSamplingRate(8000);
recorder.setAudioEncodingBitRate(12200);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
}
recorder.setOutputFile(path.getAbsolutePath());
try {
recorder.prepare();
} catch (IOException e) {
throw new RuntimeException(e);
}
return recorder;
}
// just get the last known location from the passive provider - not terribly
// accurate but it's a demo app.
private Location getLocation() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
}
#Override public Record getLastNonConfigurationInstance() {
return (Record) super.getLastNonConfigurationInstance();
}
#Override public Record onRetainNonConfigurationInstance() {
return this;
}
// Helper method to get file from a content uri
private static File getFromMediaUri(ContentResolver resolver, Uri uri) {
if ("file".equals(uri.getScheme())) {
return new File(uri.getPath());
} else if ("content".equals(uri.getScheme())) {
String[] filePathColumn = {MediaStore.MediaColumns.DATA};
Cursor cursor = resolver.query(uri, filePathColumn, null, null, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
return new File(filePath);
}
} finally {
cursor.close();
}
}
}
return null;
}
private static boolean isCompatibleSoundCloudInstalled(Context context) {
try {
PackageInfo info = context.getPackageManager()
.getPackageInfo("com.soundcloud.android",
PackageManager.GET_META_DATA);
// intent sharing only got introduced with version 22
return info != null && info.versionCode >= 22;
} catch (PackageManager.NameNotFoundException e) {
// not installed at all
return false;
}
}
#Override
protected Dialog onCreateDialog(int id, Bundle data) {
if (DIALOG_NOT_INSTALLED == id) {
return new AlertDialog.Builder(this)
.setTitle(R.string.sc_app_not_found)
.setMessage(R.string.sc_app_not_found_message)
.setPositiveButton(android.R.string.yes, new Dialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent market = new Intent(Intent.ACTION_VIEW, MARKET_URI);
startActivity(market);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).create();
} else {
return null;
}
}
}
knowing the url of the sound, you need to do the following:
resolve the URL in order to get the soundcloud API URL using Resolve endpoint
load the tracks API URL to get track representation in json or xml
initialise audio object and set the audio source to the value of stream_url property of track representation
The particular implementation varies depending on the libraries you use etc. But you'll definitely need to use HTTP requests, JSON parser and an audio object.

How I get the default ringtone list in android on programmatically?

I am android developer and want to create a android apps.In this apps ,it needed to show the android default ringtone list.But i can not show it.How to get the android default ringtone list .
Please help to me.
I have upvote Yuichi's answer but it did not completely work for me. For each ringtone I was getting same URI (different title thought). Following code worked for me -
public void listRingtones() {
RingtoneManager manager = new RingtoneManager(this);
manager.setType(RingtoneManager.TYPE_RINGTONE);
Cursor cursor = manager.getCursor();
while (cursor.moveToNext()) {
String title = cursor.getString(RingtoneManager.TITLE_COLUMN_INDEX);
Uri ringtoneURI = manager.getRingtoneUri(cursor.getPosition());
// Do something with the title and the URI of ringtone
}
}
You can see the working app on playstore.
This question/answer should provide what you're after: How to bring up list of available notification sounds on Android
You'll just need to swap out the RingtoneManager.TYPE_NOTIFICATION for RingtoneManager.TYPE_RINGTONE
You can get the list of Ringtones using RingtoneManager
public void listRingtones() {
RingtoneManager manager = new RingtoneManager(this);
manager.setType(RingtoneManager.TYPE_RINGTONE);
Cursor cursor = manager.getCursor();
while (cursor.moveToNext()) {
String title = cursor.getString(RingtoneManager.TITLE_COLUMN_INDEX);
String uri = cursor.getString(RingtoneManager.URI_COLUMN_INDEX);
// Do something with the title and the URI of ringtone
}
}
Get a List of All ringTones with default ringtones in a list :
public static Map<String, Uri> getRingtones(Activity activity) {
RingtoneManager manager = new RingtoneManager(activity);
manager.setType(RingtoneManager.TYPE_RINGTONE);
Cursor cursor = manager.getCursor();
Map<String, Uri> list = new LinkedHashMap<>();
String title = "Set to Default";
Uri defaultRingtoneUri = RingtoneManager.getActualDefaultRingtoneUri(activity, RingtoneManager.TYPE_RINGTONE);
list.put(title, defaultRingtoneUri); // first add the default, to get back if select another
while (cursor.moveToNext()) {
String notificationTitle = cursor.getString(RingtoneManager.TITLE_COLUMN_INDEX);
Uri notificationUri = manager.getRingtoneUri(cursor.getPosition());
list.put(notificationTitle, notificationUri);
}
return list;
}
Then Create a dialog for select :
public static void getRingtonesDialog(Activity activity, Collection<String> items, int selected, DialogInterface.OnClickListener itemClickListener, DialogInterface.OnClickListener okClickListener, final DialogInterface.OnClickListener cancelClickListener) {
AlertDialog.Builder builderSingle = new AlertDialog.Builder(activity);
builderSingle.setTitle("Select Ringtone");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(activity, android.R.layout.select_dialog_singlechoice);
arrayAdapter.addAll(items);
builderSingle.setNegativeButton(android.R.string.cancel, cancelClickListener);
builderSingle.setPositiveButton(android.R.string.ok, okClickListener);
builderSingle.setSingleChoiceItems(arrayAdapter, selected, itemClickListener);
builderSingle.setCancelable(false);
builderSingle.show();
}
Then Select And Play them to test : (Here AppSettings settings is SharedPreferences in your App ) :
Map<String, Uri> mRingtonesMap;
private Uri mLastSelectedRingtone = null;
private String mLastSelectedRingtoneName = "Default";
private MediaPlayer mMediaPlayer;
AppSettings settings;
TextView mRingtone ;
in Oncreate :
mRingtone = (TextView)findViewById(R.id.mRingtone);
settings = AppSettings.getInstance(this);
mRingtone.setText(getString(R.string.set_alarm_select_ringtone,
settings.getString(AppSettings.Key.SELECTED_RINGTONE_NAME, mLastSelectedRingtoneName)));
mRingtone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setupRingtoneSelection();
}
});
Then :
private void setupRingtoneSelection() {
mRingtonesMap = AlarmUtils.getRingtones(SelectionsActivity.this);
mRingtone.setText(getString(R.string.set_alarm_select_ringtone,
settings.getString(AppSettings.Key.SELECTED_RINGTONE_NAME, mLastSelectedRingtoneName)));
mRingtone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final List<String> ringtoneKeys = new ArrayList<>(mRingtonesMap.keySet());
String ringtoneUri = settings.getString(AppSettings.Key.SELECTED_RINGTONE, "");
int selected = -1;
for (int i = 0; i < ringtoneKeys.size(); i++) {
String ring = ringtoneKeys.get(i);
if (mRingtonesMap.get(ring).toString().equalsIgnoreCase(ringtoneUri)) {
selected = i;
break;
}
}
AlarmUtils.getRingtonesDialog(SelectionsActivity.this, ringtoneKeys, selected, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) { //item selected
String name = ringtoneKeys.get(which);
mLastSelectedRingtoneName = name;
mLastSelectedRingtone = mRingtonesMap.get(name);
try {
if (mMediaPlayer == null) {
mMediaPlayer = new MediaPlayer();
} else {
mMediaPlayer.stop();
mMediaPlayer.reset();
}
mMediaPlayer.setDataSource(SelectionsActivity.this, mLastSelectedRingtone);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(false);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (IOException ioe) {
//do nothing
}
}
}, new DialogInterface.OnClickListener() { //ok
#Override
public void onClick(DialogInterface dialog, int which) {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
settings.set(AppSettings.Key.SELECTED_RINGTONE, mLastSelectedRingtone.toString());
settings.set(AppSettings.Key.SELECTED_RINGTONE_NAME, mLastSelectedRingtoneName);
//Update the textview
mRingtone.setText(getString(R.string.set_alarm_select_ringtone,
settings.getString(AppSettings.Key.SELECTED_RINGTONE_NAME, mLastSelectedRingtoneName)));
dialog.dismiss();
}
}, new DialogInterface.OnClickListener() { //cancel
#Override
public void onClick(DialogInterface dialog, int which) {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
dialog.dismiss();
}
});
}
});
}
#Override
protected void onDestroy() {
if (mMediaPlayer != null) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
}
mMediaPlayer.release();
mMediaPlayer = null;
}
mRingtone.setOnClickListener(null);
super.onDestroy();
}
You can set and change ringtone, and after you want, can get back to default.

android textview does not show after setting visible from another thread

I am having problems making my TextViews visible from another thread using the method showDisclaimer(). I have used runOnUiThread() to set the visibility of my TextViews. Basically, I want to show these views after importing the csv to the database. Can you take a look and see what I missed?
public class MainActivity extends Activity {
final static int INDEX_ACCTTYPE = 0;
final static int INDEX_ECN = 1;
final static int INDEX_TLN = 2;
final static int INDEX_SIN = 3;
final static int INDEX_MOBILE = 4;
final static int INDEX_CITY = 5;
final static int INDEX_START_DATE = 6;
final static int INDEX_START_TIME = 7;
final static int INDEX_END_DATE = 8;
final static int INDEX_END_TIME = 9;
final static int INDEX_REASON = 10;
final static int INDEX_DETAILS = 11;
DatabaseHandler db;
String str;
ProgressDialog pd;
final private String csvFile = "http://www.meralco.com.ph/pdf/pms/pms_test.csv";
final private String uploadDateFile = "http://www.meralco.com.ph/pdf/pms/UploadDate_test.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView homeText1 = (TextView) findViewById(R.id.home_text1);
TextView homeText2 = (TextView) findViewById(R.id.home_text2);
TextView homeText3 = (TextView) findViewById(R.id.home_text3);
TextView homeText4 = (TextView) findViewById(R.id.home_text4);
homeText1.setVisibility(View.INVISIBLE);
homeText2.setVisibility(View.INVISIBLE);
homeText3.setVisibility(View.INVISIBLE);
homeText4.setVisibility(View.INVISIBLE);
//db = new DatabaseHandler(MainActivity.this);
if(dbExists()){
db = new DatabaseHandler(MainActivity.this);
Log.d("Count", "" + db.count());
if(!uploadDateEqualsDateInFile())
promptOptionalUpdate("There is a new schedule");
showDisclaimer();
Log.i("oncreate", "finished!");
return;
}
promptRequiredUpdate("Schedule not updated");
//showDisclaimer();
Log.i("oncreate", "finished!");
}
public void promptOptionalUpdate(String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(
this);
builder.setMessage(Message)
.setCancelable(false)
.setPositiveButton("Update Now",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "update");
dropOldSchedule();
triggerDownload();
dialog.cancel();
}
})
.setNegativeButton("Later",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "cancel");
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void dropOldSchedule(){
//TODO drop old schedule
}
public void triggerDownload() {
if (!checkInternet()) {
showAlert("An internet connection is required to perform an update, please check that you are connected to the internet");
return;
}
if(pd!=null && pd.isShowing()) pd.dismiss();
pd = ProgressDialog.show(this, "Downloading schedule",
"This may take a few minutes...", true, false);
Thread thread = new Thread(new Runnable() {
public void run() {
db = new DatabaseHandler(MainActivity.this);
db.beginTransaction();
try {
URL myURL = new URL(csvFile);
BufferedReader so = new BufferedReader(new InputStreamReader(myURL.openStream()));
while (true) {
String output = so.readLine();
if (output != null) {
String[] sched = output.split(",");
try {
db.addRow(sched[INDEX_SIN], sched[INDEX_CITY],
sched[INDEX_START_DATE], sched[INDEX_START_TIME],
sched[INDEX_END_DATE], sched[INDEX_END_TIME],
sched[INDEX_DETAILS], sched[INDEX_REASON]);
} catch (IndexOutOfBoundsException e) {
db.addRow(sched[INDEX_SIN], sched[INDEX_CITY],
sched[INDEX_START_DATE], sched[INDEX_START_TIME],
sched[INDEX_END_DATE], sched[INDEX_END_TIME],
"", sched[INDEX_REASON]);
e.printStackTrace();
}
}
else {
break;
}
}
so.close();
} catch (MalformedURLException e) {
e.printStackTrace();
db.endTransaction();
} catch (IOException e) {
e.printStackTrace();
db.endTransaction();
}
Log.d("Count", ""+db.count());
db.setTransactionSuccessful();
db.endTransaction();
runOnUiThread(new Runnable() {
public void run() {
while (!pd.isShowing());
getUploadDate();
writeUploadDateInTextFile();
showDisclaimer();
pd.dismiss();
}
});
}
});
thread.start();
//while(thread.isAlive());
Log.d("triggerDownload", "thread died, finished dl. showing disclaimer...");
}
public void getUploadDate() {
Log.d("getUploadDate", "getting upload date of schedule");
if(pd!=null && pd.isShowing()) pd.dismiss();
pd = ProgressDialog.show(this, "Getting upload date",
"This may take a few minutes...", true, false);
Thread thread = new Thread(new Runnable() {
public void run() {
try {
URL myURL = new URL(uploadDateFile);
BufferedReader so = new BufferedReader(new InputStreamReader(myURL.openStream()));
while (true) {
String output = so.readLine();
if (output != null) {
str = output;
}
else {
break;
}
}
so.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
while (!pd.isShowing());
pd.dismiss();
}
});
}
});
thread.start();
while (thread.isAlive());
Log.d("getUploadDate","thread died, upload date="+str);
}
public void writeUploadDateInTextFile() {
Log.d("writeUploadDateTextFile", "writing:"+str);
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(
"update.txt", 0));
out.write(str);
out.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
public void showDisclaimer() {
Log.d("ShowDisclaimer", "showing disclaimer");
TextView homeText1x = (TextView) findViewById(R.id.home_text1);
TextView homeText2x = (TextView) findViewById(R.id.home_text2);
TextView homeText3x = (TextView) findViewById(R.id.home_text3);
TextView homeText4x = (TextView) findViewById(R.id.home_text4);
homeText3x
.setText("You may view the schedule of pre-arranged power interruptions by clicking any of these buttons : SIN, City or Date. " +
"The schedule has been updated as of " + str
+ ". Meralco is exerting all efforts to restore electric service as scheduled." +
" The schedule, however, may change without further notice. For verification, follow-ups, or " +
"latest updates, please contact our CALL CENTER through telephone nos. 16211, " +
"fax nos. 1622-8554/1622-8556 or email address callcenter.tech.assist#meralco.com.ph.");
homeText1x.setVisibility(View.VISIBLE);
homeText2x.setVisibility(View.VISIBLE);
homeText3x.setVisibility(View.VISIBLE);
homeText4x.setVisibility(View.VISIBLE);
Log.d("ShowDisclaimer", "finished showing disclaimer");
}
public void promptRequiredUpdate(String Message) {
Log.d("required update","required!");
AlertDialog.Builder builder = new AlertDialog.Builder(
this);
builder.setMessage(Message)
.setCancelable(false)
.setPositiveButton("Update Now",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "update");
triggerDownload();
dialog.cancel();
}
})
.setNegativeButton("Later",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "cancel");
dialog.cancel();
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public boolean uploadDateEqualsDateInFile() {
Log.d("uploadDateEqualsDateInFile","comparing schedule upload dates");
getUploadDate();
try {
String recordedDate = "";
InputStream instream = openFileInput("update.txt");
if (instream != null) { // if file the available for reading
Log.d("uploadDateEqualsDateInFile","update.txt found!");
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line = null;
while ((line = buffreader.readLine()) != null) {
recordedDate = line;
Log.d("uploadDateEqualsDateInFile","recorded:"+recordedDate);
}
Log.d("uploadDateEqualsDateInFile","last upload date: " + str + ", recorded:" +recordedDate);
if(str.equals(recordedDate)) return true;
return false;
}
Log.d("uploadDateEqualsDateInFile","update.txt is null!");
return false;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public void showAlert(String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(getBaseContext());
builder.setMessage(Message).setCancelable(false)
.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public boolean checkInternet() {
ConnectivityManager cm = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo infos[] = cm.getAllNetworkInfo();
for (NetworkInfo info : infos)
if (info.getState() == NetworkInfo.State.CONNECTED
|| info.getState() == NetworkInfo.State.CONNECTING) {
return true;
}
return false;
}
public boolean dbExists() {
File database=getApplicationContext().getDatabasePath(DatabaseHandler.DATABASE_NAME);
if (!database.exists()) {
Log.i("Database", "Not Found");
return false;
}
Log.i("Database", "Found");
return true;
}
#Override
protected void onDestroy() {
super.onDestroy();
if (db != null) {
db.close();
}
}
#Override
protected void onPause() {
super.onPause();
if (db != null) {
db.close();
}
}
}
simplymoody, do what Chirag Raval suggested by declaring private static TextView homeText1, globally and in your onCreate initialise them. However, you should always update the UI from the main thread. But showDisclaimer() is still running on the background thread, so you could run the showDisclaimer() a couple of different ways. One would be to do what you have done in getUploadDate():
runOnUiThread(new Runnable() {
public void run() {
showDisclaimer()
}
});
Or you could use a handler:
private Handler showDisclaimerHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
homeText3x.setText("TEXT");
homeText1x.setVisibility(View.VISIBLE);
homeText2x.setVisibility(View.VISIBLE);
homeText3x.setVisibility(View.VISIBLE);
homeText4x.setVisibility(View.VISIBLE);
Log.d("ShowDisclaimer", "finished showing disclaimer");
return false;
}
});
And everywhere in a background thread you wish to run your showDisclaimer(), instead you run:
showDisclaimerHandler.sendEmptyMessage(0);

Categories

Resources