Getting audio from the folder - android

I have an alarm and want to give the choice to user choose the music.
I have an activity with some code, include this fragment:
Button ring_button = (Button) findViewById(R.id.button2);
ring_button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent_for_ring_button = new Intent();
intent_for_ring_button.setAction(Intent.ACTION_GET_CONTENT);
File file = new File(REPORTS_DIRECTORY);
intent_for_ring_button.setDataAndType(Uri.fromFile(file),"audio/*");
startActivityForResult(Intent.createChooser(intent_for_ring_button,"Open folder"), 0);
}
});
and one more activity with alarm that extends BroadcastReceiver, where i`m starting next activity with dialog window with some music.
Here is it:
public class Dialog_window extends ActionBarActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_window_bckg);
getSupportActionBar().hide();
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
final MediaPlayer Alarm_mp3 = MediaPlayer.create(Dialog_window.this, R.raw.data_don_t_sing);
Alarm_mp3.start();
Alarm_mp3.setLooping(true);
AlertDialog.Builder builder = new AlertDialog.Builder(Dialog_window.this);
builder.setTitle("Важное сообщение!")
.setMessage("Вставай!")
.setIcon(R.drawable.uncle_sam)
.setCancelable(false)
.setNegativeButton("ОК, встаю, встаю.",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Alarm_mp3.stop();
System.exit(0);
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
How i can realize this? I must get some extras from the first activity or smth else?

After you called startActivityForResult with ACTION_GET_CONTENT intent, you should overwrite onActivityResult in the same class, and get the chosen file's path. After you have the path, you can save to shared preferences, and easily retrieve from another activity (ex. in your Dialog_window) and play with MediaPlayer.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 0){ // you've set to 0 at startActivityForResult
if(resultCode==RESULT_OK){
String filePath = data.getData().getPath();
// save filePath to shared preferences
}
}
}
After you retrieved inside another activity, just simply play it.
String savedPath = ..... ; // retrieve from shared preferences
//check your saved path, it could be a full path already..
//if it is, you don't need to concatenate anything to it
String fullPath = Environment.getExternalStorageDirectory()+savedPath;
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(fullPath);
mediaPlayer.prepare();
mediaPlayer.start()
Saving file path to shared preferences:
SharedPreferences.Editor editor = getSharedPreferences("mypref", MODE_PRIVATE).edit();
editor.putString("audioFilePath", filePath);
editor.commit();
Restoring file path from shared preferences:
SharedPreferences prefs = getSharedPreferences("mypref", MODE_PRIVATE);
String restoredFilePath = prefs.getString("audioFilePath", null);
if (restoredFilePath != null) {
// here you have the restored file path
}

Related

if application re-open SharedPreferences not saving boolean

I have the following code in my project called menu.class
f1 =(Button)findViewById(R.id.f1);
f1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
Intent intent = new Intent ();
intent.setClassName ("com.example.aplication", "com.example.application.levelone");
startActivityForResult (intent, 0);
}
});
}
public void onActivityResult (int requestCode, int resultCode, Intent intent) {
super.onActivityResult (requestCode, resultCode, intent);
f2=(Button)findViewById(R.id.f2);
f2lock=(ImageView)findViewById(R.id.f2lock);
switch (resultCode) {
case 11: f2.setVisibility(View.VISIBLE);
f2lock.setVisibility(View.GONE);
}
SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
boolean levelTwoUnlocked = preferences.getBoolean("f2", true);
if(levelTwoUnlocked){
f2.setVisibility(View.VISIBLE);
f2lock.setVisibility(View.GONE);
}
else {
f2.setVisibility(View.GONE);
f2lock.setVisibility(View.VISIBLE);
}
f2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
Intent intent = new Intent ();
intent.setClassName ("com.example.application", "com.example.application.leveltwo");
startActivityForResult (intent, 0);
}
});
}
The code is working fine. f2 button is set visible and f2lock invisible.
But when I re-open the application the f2 button back to visible.
Did my Preferences code not complete?
UPDATED
i had changed the preferences code like this
SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
SharedPreferences.Editor ed = preferences.edit();
boolean levelTwoUnlocked = preferences.getBoolean("f2", true);
ed.commit();
and when i re-open the application it still had the same problems
You are retrieving the value of f2, but it doesn't look like you're saving it anywhere.
preferences.getBoolean("f2", true);
This will return the last saved value of f2 or true if f2 doesn't exist (i.e. you've never saved it in your SharedPreference instance) - it won't create or save any value in the SharedPreferences instance for you.
To save the value, you need to create a SharedPreferences editor, set the value (or values) you want to save and commit it:
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("f2", levelTwoUnlocked);
editor.commit();
Now the next time you read the f2 value, it will have whatever value you last committed.

android sharedPreferences to set and retrieve boolean value

I want to save boolean values and then compare them in an if-else block. but when run my application, nothing is displayed.
my Code is here:
prefs = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
editor = prefs.edit();
boolean init = false;
if (init) {
Ion.with(this)
.load("myurl")
.asJsonArray().setCallback(new FutureCallback<JsonArray>() {
#Override
public void onCompleted(Exception arg0, JsonArray data) {
// TODO Auto-generated method stub
for (int i = 0; i < data.size(); i++) {
cat.setTitle(data.get(i).getAsJsonObject()
.get("title").getAsString());
arrayList.add(cat);
db.addCategory(cat);
adapter.notifyDataSetChanged();
}
populateScroller();
editor.putBoolean("init", true).commit();
}
});
} else {
dataSource = new CategoryDataSource(this);
dataSource.open();
arrayList = dataSource.getCategoryList();
for (Categories c : arrayList) {
c.getTitle();
}
}
So my question is why shared preferences is not working? please help me.
This is how you need to work with shared preferences.
The senerio I am about to show is to check if this particular activity is running for the first time or not.
Here is what you do in your on create method:
//SharePrefernces
SharedPreferences appIntro = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Check if the Application is Running for the First time
appIntro = getSharedPreferences("hasRunBefore_appIntro", 0); //load the preferences
Boolean hasRun = appIntro.getBoolean("hasRun_appIntro", false); //see if it's run before, default no
//If FirstTime
if (!hasRun) {
//code for if this is the first time the application is Running
//Display Activity
super.onCreate(savedInstanceState);
setContentView(R.layout.app_intro_activity);
//Button to send Confirmation back
Button btn_ok = (Button) findViewById(R.id.appintro_btn_ok);
btn_ok.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Save information that this application has run for the first time
SharedPreferences settings = getSharedPreferences("hasRunBefore_appIntro", 0);
SharedPreferences.Editor edit = settings.edit();
edit.putBoolean("hasRun_appIntro", true);
edit.commit(); //apply
Intent intent = new Intent(Application_Intro_Activity.this, MainActivity.class);
startActivity(intent);
//close Activity
finish();
}
});
}//End of if(firstTime)
else {
//code if the Application has run before
super.onCreate(savedInstanceState);
//Navigate Directly to MainActivity
Intent intent = new Intent(Application_Intro_Activity.this, MainActivity.class);
startActivity(intent);
//close Activity
finish();
}
}//End of OnCreate()
you are checking always false value of init and it does not enter into your if statement,So prefs will not updated.instead do it as
boolean init = prefs.getBoolean("init",false);
and check it as
if(!init)
i.e. change
boolean init = false;
if (init) {
to
boolean init = prefs.getBoolean("init",false);
if(!init)
You are not using SharedPreferences values in above code . You might need to do like this :
SharedPreferences prefs = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
boolean prefValue = prefs.getBoolean("init", false);
if(!prefValue)
{
// add value in SharedPreferences
Ion.with(this)
.load("myurl")
.asJsonArray().setCallback(new FutureCallback<JsonArray>() {
#Override
public void onCompleted(Exception arg0, JsonArray data) {
// TODO Auto-generated method stub
for (int i = 0; i < data.size(); i++) {
cat.setTitle(data.get(i).getAsJsonObject()
.get("title").getAsString());
arrayList.add(cat);
db.addCategory(cat);
adapter.notifyDataSetChanged();
}
populateScroller();
editor = prefs.edit();
editor.putBoolean("init", true).commit();
}
});
}
else{
dataSource = new CategoryDataSource(this);
dataSource.open();
arrayList = dataSource.getCategoryList();
for (Categories c : arrayList) {
c.getTitle();
}
}
The key is : You need to check the preference values first and accordingly code
You can also use SharedPreferences like this:
/* In your onCreate method */
SharedPreferences sp = getSharedPreferences(MyPrefs, Context.MODE_PRIVATE);
if (!sp.getBoolean("first", false)) {
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("first", true);
editor.apply();
Intent intent = new Intent(this, IntroActivity.class); // Call the one tie launch java class
startActivity(intent);
}

User setup activity of android app

I want to create a simple app to upload my location .I have two activities and in first activity the user can input parameters url for upload with editbox , a checkbox if user wish upload location save preferences button and start button for go to get location activity.I try this but no work...How i call my function start and save?Any help?I have errors when debug...after click button
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences preferences = getSharedPreferences("gpstracker" , MODE_PRIVATE);
String strValue = preferences.getString("Url",strValued);
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
edittxtUrl.setText(strValue);
Button buttonStart = (Button)findViewById(R.id.buttonStart);
buttonStart.setOnClickListener(startListener);
Button buttonSave = (Button)findViewById(R.id.buttonSave);
buttonSave.setOnClickListener(saveListener);
}
private OnClickListener startListener = new OnClickListener() {
public void onClick(View v) {
Start();
}
};
private OnClickListener saveListener = new OnClickListener() {
public void onClick(View v) {
Save();
}
};
public void Save() {
SharedPreferences preferences = getSharedPreferences("gpstracker" , MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
String strUrl = edittxtUrl.getText().toString();
CheckBox chkTandC = (CheckBox)findViewById(R.id.chkTandC);
boolean blnTandC = chkTandC.isChecked();
editor.putString("Url", strUrl); // value to store
editor.putBoolean("TandC", blnTandC); // value to store
// Commit to storage
editor.commit();
}
public void Start() {
startActivity(new Intent(this, LocTracker.class));
}
Without your log cat it is somewhat hard to tell what your problem is, but what I think is happening is that you are passing a null view to the start method, and this is a problem because you are then trying to get a context. Effectively what you have written is
null.getContext()
which doesn't work. You can fix this by replacing view.getContext() with getApplicationContext()

app is crashing after quickly changes preferences with commit(

I need to check the user input in the preferences if they want to save a new value. I believe the code is correct... because if I'm change the values slowly there's no problem at all. If I change too quick the app is crashing.
i'm using commit() for editing the preferences. Is this a too slow methode?
What I'm trying?: If a user gave an empty string, I give an alert dialog and intern I change the pref back to the old value. Here is the code:
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
//save settings
static String SMStext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
//-- First get SMStext and save in Strings
SMStext = sp.getString("SMSText", "0");
//SharedPreferences.Editor prefEditor = sp.edit();
sp.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
String smstriggerworderror = "String cannot be empty";
if (key.equals("SMSText")) {
if sp.getString("SMSText", "0").equals(""){
SharedPreferences.Editor prefEditor = sp.edit();
prefEditor.putString("SMSText", SMStext);
prefEditor.commit();
//write current value back to value and refresh interface
SMStext = sp.getString("SMSText", "0");
//Show alert dialog
showdialog(smstriggerworderror);
//finish();
}
//write current value back to value
SMStext = sp.getString("SMSText", "0");
}
private void showdialog(String message) {
//create alertbox
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setMessage(message);
alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
// Click listener on the neutral button or alert box
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
});
// show the alert box
alertbox.show();
}
Inside of onSharedPreferenceChanged your doing a prefEditor.commit(); this will then call the onSharedPreferenceChanged listener, which wil then call commit() over and over until............... StackOverFlow error.
Fix:
Don't change your SharedPreferences inside of the OnSharedPreferencesChanged listener.

android getsharedPreferences not sure how to show hide other activities

I decided to use sharedPreferences so I could store the value of a togglebutton on my activity Preferences. On my main activity I want to hide a twitter button when the user clicks the twitter button in the Preferences activity.
private SharedPreferences prefs;
private String prefName = "MyPref";
private ToggleButton timer, twitter;
// this is the key used to set the timer to visible or hidden
private static final String TIMER_KEY = "timekey";
private static final String TWITTER_KEY= "tweet";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preferences);
timer = (ToggleButton)findViewById(R.id.timer_pref);
twitter =(ToggleButton)findViewById(R.id.twitter_pref);
timer.setChecked(true);
twitter.setChecked(true);
// Toast.makeText(Preferences.this, timer, Toast.LENGTH_SHORT).show();
Button b = (Button) findViewById(R.id.home_btn);
b.setOnClickListener(new View.OnClickListener()
{
// now add the new screen
public void onClick(View arg0) {
// TODO Auto-generated method stub
// get the shared perference data
Intent i = new Intent(Preferences.this, AndroidGUIActivity.class);
startActivity(i);
}
});
twitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
prefs = getSharedPreferences("MyPref", 0 );
SharedPreferences.Editor editor = prefs.edit();
if (timer.isChecked() == true)
{
editor.putBoolean("twitterButtonStatus", true);
}
else if(timer.isChecked() == false)
{
editor.putBoolean("twitterButtonStatus", false);
}
// now save the value that is passed to the editor.putBoolean function
// the twitter data hase been saved
editor.commit();
// now store the variable so that it can be copied to another activity
Bundle b = new Bundle();
}
});
There is no need to transfer Preferences through activities using intent.
You can access your "shared"Preferences from any activity.
You just put the button status with a string key inside:
SharedPreferences settings = getSharedPreferences("MyPrefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("twitterButtonStatus", buttonStatus);
And in another activity you retrieve these preferences using string key ("twitterButtonStatus"):
SharedPreferences settings = getSharedPreferences("MyPrefs", 0);
boolean buttonStatus = settings.getBoolean("twitterButtonStatus", false); // second param is default!
See: http://developer.android.com/guide/topics/data/data-storage.html
Edit:
Youre saving SharedPrefs now, to get them back and set your Button Gone do something like this:
SharedPreferences settings = getSharedPreferences(prefName, 0);
boolean buttonStatus = settings.getBoolean(TWITTER_KEY, true); //2nd is default
if(buttonstatus==false) twitter.setVisibility(View.GONE);

Categories

Resources