I have a problem by reading getSharedPreferences from non-Activity class to set playlist in player… In my Activity I take string variable from edittext to get path of folder to work with audio files…
public class MainActivity extends Activity {
String ppp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String PATH = getSharedPreferences("PATH", MODE_PRIVATE).getString("path", ppp);
if (PATH == null){
..........
...........
path_tv.setText("folder is undefined");
}
else {
path_tv.setText("folder defined: /mnt/sdcard/" + PATH);
}
set_path.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (path_edit.getText().toString().length() == 0){
Toast.makeText(getBaseContext(), "folder is undefined", Toast.LENGTH_SHORT).show();
}
else {
ppp = path_edit.getText().toString();
getSharedPreferences("PATH", MODE_PRIVATE)
.edit()
.putString("path", ppp)
.commit();
File folder = new File(Environment.getExternalStorageDirectory() + "/" + ppp);
boolean success = false;
if (!folder.exists()) {
success = folder.mkdir();
if (success) Toast.makeText(getBaseContext(), ".....", Toast.LENGTH_SHORT).show();
}
String PATH = getSharedPreferences("PATH", MODE_PRIVATE).getString("path", ppp);
path_tv.setText("........ /mnt/sdcard/" + PATH);
path_edit.setText("");
}
}
});
So, in activity I can change and save value of String in shared preferences… But ho can I do it from public class…? Appreciate any examples…
One way is to use Application object. This is a dirty hack but none the less sometimes helpful.
First you need a static member in your Application class, so:
Since Application object is always created before any activity is created and run and is kept throughout application lifetime you can always be sure you will have proper one.
Then in your code simply call
MyApplication.getInstance()and you will have global app context.Remember to declare
MyApplicationin manifest.