Background music and shared preferences - java

i want to toggle the background music on and off using settings , which is an activity and it can be launched by pressing the menu button through the main activity and selecting settings. the problem I am facing now is that when i tick the background music checkbox , upon clicking save and returning to the main activity , my music stops playing. how to i make sure that the music keeps playing after going back to the main activity? And when i stop the app and relaunch the activity , i want the settings to remain the way they were selected (using sharedpreferences). Can anyone take a look at my codes and see what I am doing wrong?
my MainActivity.java
package sp.com;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.Button;
import android.widget.TextView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import android.app.TabActivity;
import android.widget.TabHost;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.media.MediaPlayer;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.KeyEvent;
public class MainActivity extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.setting:
Intent intent = new Intent(MainActivity.this, Settings.class);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
}
My settings.java
package sp.com;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.View.OnClickListener;
import android.content.SharedPreferences.Editor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
public class Settings extends Activity implements OnClickListener {
CheckBox Backmusic;
Button button1;
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.xml.preferences);
Backmusic = (CheckBox) findViewById(R.id.backmusic);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
loadSavedPreferences();
}
private void loadSavedPreferences(){
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
boolean checkBoxValue = sharedPreferences.getBoolean("CheckBox_Value",false);
if (checkBoxValue){
Backmusic.setChecked(true);
} else {
Backmusic.setChecked(false);
}
}
private void savePreferences(String key, boolean value){
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
#Override
public void onClick(View v){
savePreferences("CheckBox_Value",Backmusic.isChecked());
if (Backmusic.isChecked()){
mp = MediaPlayer.create(getBaseContext(), R.raw.sound);
mp.start();
} else {
mp.stop();
finish();
}
}
#Override
protected void onStop() {
super.onStop();
mp.stop();
finish();
}
}
Thanks in advance.

So right now you are just playing the music within your Settings activity. In fact you are calling mp.stop() in onStop(). That's why when it closes the music stops.
You should also put code in your MainActivity in onCreate() and onResume() to read from sharedpreferences and if the background music is true, play music. That could look something like this:
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
boolean backgroundMusic = sp.getBoolean("CheckBox_Value",false);
if (backgroundMusic)
{
MediaPlayer mp = MediaPlayer.create(getBaseContext(), R.raw.sound);
mp.start();
}
else
{
mp.stop();
}
Note that you'll now want to write to SharedPreferences in Settings using getApplicationContext() instead of this. That way the preferences will be saved across the entire application and not just one activity.

Related

Save markers to csv file

I am wondering how to when the user closes the app, save the markers to a file then load them back in when the app is opened again
Here is my code:
package com.example.mapapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import org.osmdroid.config.Configuration;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.OverlayItem;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends Activity
{
MapView mv;
StringBuffer filePath;
File file;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// This line sets the user agent, a requirement to download OSM maps
Configuration.getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));
setContentView(R.layout.activity_main);
mv = (MapView)findViewById(R.id.map1);
ItemizedIconOverlay<OverlayItem> items;
mv.setBuiltInZoomControls(true);
mv.getController().setZoom(11);
mv.getController().setCenter(new GeoPoint(53.3710,-1.4502));
}
public boolean onOptionsItemSelected(MenuItem item)
{
if(item.getItemId() == R.id.addpoi)
{
// react to the menu item being selected...
Intent intent = new Intent(this,AddPoi.class);
startActivityForResult(intent,0);
return true;
}
Intent intent = new Intent(this,AddPoi.class);
startActivityForResult(intent,0);
return false;
}
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.menu_mad_assignment, menu);
return true;
}
protected void onActivityResult(int requestCode,int resultCode,Intent intent)
{
if(requestCode==0)
{
if (resultCode==RESULT_OK)
{
Bundle extras=intent.getExtras();
String poiName= extras.getString("poiName");
String poiType= extras.getString("poiType");
String poiDesc= extras.getString("poiDesc");
ItemizedIconOverlay<OverlayItem> items = new ItemizedIconOverlay<>(this, new ArrayList<OverlayItem>(), null);
OverlayItem marker = new OverlayItem(poiName, poiType,poiDesc, new GeoPoint(53.3710,-1.4502));
items.addItem(marker);
mv.getOverlays().add(items);
Log.d("NAME",poiName);
Log.d("NAME",poiType);
Log.d("NAME",poiDesc);
}
}
}
}
Add marker code:
package com.example.mapapp;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import com.example.luke.madassignment.R;
public class AddPoi extends Activity implements OnClickListener {
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_poi);
Button addPoiButton = (Button)findViewById(R.id.addPoi);
Button cancelButton = (Button)findViewById(R.id.cancel);
addPoiButton.setOnClickListener(this);
cancelButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent();
Bundle bundle=new Bundle();
EditText poiName = (EditText)findViewById(R.id.editTextPoiName);
EditText poiType = (EditText)findViewById(R.id.editTextPoiType);
EditText poiDesc = (EditText)findViewById(R.id.editTextPoiDesc);
String poiNameString = poiName.toString();
String poiTypeString = poiName.toString();
String poiDescString = poiName.toString();
bundle.putString("poiName",poiNameString);
bundle.putString("poiType",poiTypeString);
bundle.putString("poiDesc",poiDescString);
intent.putExtras(bundle);
setResult(RESULT_OK,intent);
finish();
}
}
The problem is i cant figure out a way to save the users marker to a file if the app is closed and then load back in the markers when the app is opened again
Use built in sharedPref, simple key value storage, to save data in persistence mode. Check doc here
The SharedPreferences class provides a general framework that allows
you to save and retrieve persistent key-value pairs of primitive data
types. You can use SharedPreferences to save any primitive data:
booleans, floats, ints, longs, and strings. This data will persist
across user sessions (even if your application is killed).
https://developer.android.com/guide/topics/data/data-storage.html#pref
Using OSMBonusPack, you can grab your markers in a KML structure, then save the KML file locally (in onStop).
And load back this KML file when the app is opened (in onCreate).

R.id. Cannot resolve symbol 'message'

This is the code and the error in "Cannot resolve symbol 'message'" on the line:
EditText editText = (EditText) findViewById(R.id.message);
The application worked well, previously. It's likely to be a stupid error.
File MainActivity.java
package com.example.antonio.newsbooklite2;
/**
* Created by antonio on 30/12/16.
*/
import android.os.Bundle;
import android.support.annotation.Nullable;
//import android.support.design.widget.*;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.*;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.util.ArrayList;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** Called when the user clicks the Send button */
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
// Do something in response to button
}
}
File strings.xml
<resources>
<string name="app_name">newsbooklite2</string>
<string name="message">Scrivi messaggio: </string>
<string name="button_send">Send</string>
enter code here
<string name="nome_stringa">Testo_visualizzato</string>
</resources>
You might be mixing these things.
findViewById(R.id.message);
returns the View from the layout.
If you want the string, you can use:
getResources().getString(R.string.message);
You are using a message id defined in the string.xml file in line:
EditText editText = (EditText) findViewById(R.id.message);
Change the message to the id defined in the layout file.

android studio cannot resolve method(), ignoring import

I'm a total noob at android studio, and I have a (to me) weird problem. I have inserted a button in my XML document:
<Button
android:layout_width="match_parent"
android:layout_height="127dp"
android:text="SUM"
android:id="#+id/button"
android:layout_row="15"
android:layout_column="0" />
And in the java code I would like a to make it do something when i click on it. However in code (I know there is way too many import):
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class TestActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
R.id.button.onCliclistener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent action) {
DO THIS WHEN CLICKED ON
}
});
}
BUT it says: Cannot resolve method() and Cannot resolve symbol, to the onCliclistener and ActionListener. And it says: unused import statement, to thier imports. It's probably a stupid question, but what am I doing wrong?
Nicolaj
Try making reference to your button in your onCreate method and then create an onClick method.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class TestActivity extends AppCompatActivity implements View.OnClickListener {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
btn = (Button) findViewById(R.id.button); //Reference to the button
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
DO THIS WHEN CLICKED ON
}
}
I expect it will be helpful for you!

Toggle button onClick method does not work

I have toggle button which has android:onClick=onToggleClicked. I tried to reference the onToggleClicked method from the java code but the problem is, eclipse underscore the onToggleClicked with red and does not recognizes it. How to fix this error.
Imports:
import java.util.Set;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.os.Build;
JavaCode:
if (myBluetoothAdapter == null) {
tb_OnOFF.setEnabled(false);
btnFind.setEnabled(false);
btnPaired.setEnabled(false);
tvStatusCaption.setText("Status: Not Supported.");
Toast.makeText(getApplicationContext(), "Your Device Does Not Support " +
"Bluetooth", Toast.LENGTH_LONG).show();
} else {
public void onToggleClicked (View view) {
boolean on = ((ToggleButton) view).isChecked();
if (on) {
//enable bluetooth
}
if (!on) {
//disable bluetooth
}
}
}
XML:
<ToggleButton
android:id="#+id/btnToggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="#string/toggle_turn_on"
android:textOff="#string/toggle_turn_off"
android:checked="true"
android:onClick="onToggleClicked" />
onToggleClicked is a public method and needs to be attached to your Activity. You cannot use this method as an inner method inside onCreate method.
USE THIS
mToggleButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (mToggleButton.isChecked()) {
//your code
}
else{
//your code
}
}
});

Android crashing on activity start

Android crashes whenever this activity is started. here is the code.
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class SettingsActivity extends Activity {
EditText vname, vphone, vemail, vaddress;
TextView textDeviceID;
Button settings_submit;
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.settingmenu);
vname = (EditText) findViewById(R.id.get_name);
vphone = (EditText) findViewById(R.id.get_phone);
vemail = (EditText) findViewById(R.id.get_email);
vaddress = (EditText) findViewById(R.id.get_address);
settings_submit = (Button) findViewById(R.id.settings_submit);
settings_submit.setOnClickListener(settings_submitOnClickListener);
TextView textDeviceID = (TextView) findViewById(R.id.deviceid);
super.onCreate(savedInstanceState);
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(
you should tell us more details. But I see that everything looks fine, except that
super.onCreate(savedInstanceState);
should go before setContentView() and all other stuff. By the way, check your xml for bad config controls too.

Categories