Shared Preferences not found - java

Im trying to load SharedPreferences but the shared preferences never gets found, and im trying to update it from another class but that doesn't work as well. Im using a lst adapter for a list vieew as well. Any idea's for the following code? Im getting the back up hello string for the list view.
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class WorldMenu extends ListActivity{
SharedPreferences prefs = null;
String splitter;
String[] worldList;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
context = getBaseContext();
prefs = context.getSharedPreferences("worldString", 1);
splitter = "Create World," + prefs.getString("worldString", "hello");
worldList = splitter.split(",");
setListAdapter(new ArrayAdapter<String>(WorldMenu.this,
android.R.layout.simple_list_item_1, worldList));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
if(position == 0){
Intent openWorldNamer = new Intent("this works no need to check");
startActivity(openWorldNamer);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Edit Updater Class:
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class WorldCreator extends Activity{
EditText worldNameEditor;
Button saver;
SharedPreferences prefs;
OnSharedPreferenceChangeListener listener;
String updater2;
Editor editor;
String updater;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_worldcreator);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
worldNameEditor = (EditText) findViewById(R.id.hello);
saver = (Button) findViewById(R.id.button1);
updater2 = worldNameEditor.getText().toString() + ",";
saver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
updater = updater2;
editor = prefs.edit();
editor.putString("worldString", updater);
editor.commit();
Intent openListWorld = new
Intent("the list activity");
startActivity(openListWorld);
}});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
}

Until you create preferences they don't exist, so you'll always see "hello".
Here is some code I use to set a value:
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Editor editor = sharedPreferences.edit();
editor.putBoolean("LicenseAccepted", true);
editor.commit();
Note that this not using a named file as you are, but the concept is the same :-)

Related

lanjava.lang.runtimeexception: unable to destroy activity {com.example.quickfinder/com.example.quickfinder.ocrresult}:java.lang.nullpointerexception

package com.example.quickfinder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class Ocrresult extends Activity {
private TessOCR mTessOCR;
TextView txt1;
Button save, cancel;
ImageView viewImage;
Bitmap bmp;
private ProgressDialog mProgressDialog;
private String mCurrentPhotoPath;
private TextView mResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.nextactivity);
mResult = (TextView)findViewById(R.id.textView1);
mResult.setTextColor(Color.BLACK);
save = (Button)findViewById(R.id.save);
cancel= (Button)findViewById(R.id.cancel);
ImageView view = (ImageView) findViewById(R.id.image);
byte[] byteArray = getIntent().getByteArrayExtra("image");
bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
view.setImageBitmap(bmp);
doOCR(bmp);
}
private void doOCR(final Bitmap bitmap) {
if (mProgressDialog == null)
{
mProgressDialog = ProgressDialog.show(this, "Processing", "Doing OCR...", true);
}
else
{
mProgressDialog.show();
//make comment hre from dialog box////////////////
new Thread(new Runnable()
{
public void run()
{
final String result = mTessOCR.getOCRResult(bitmap);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
// TODO Auto-generated method stub
if (result != null && !result.equals(""))
{
mResult.setText(result);
}
mProgressDialog.dismiss();
}
});
};
}).start();
///////////complete coment hre for dialog.
}
///////////////destroing avtivity after use compete//////////////////
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mTessOCR.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
This is the code of my OCRresult activity when I run this activity it returns this error in logcat:
lanjava.lang.runtimeexception: unable to destroy activity {com.example.quickfinder/com.example.quickfinder.ocrresult}:java.lang.nullpointerexception"
How do I resolve this?

Set OnclickListener For ListView Such that line selected in list is used as edit text in another class

I have two classes for my translation app. One(Voice.java) in which we speak and RecognizerIntent gets our speech and displays it in form of a list. This is voice.java
package com.example.testing;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class Voice extends Activity implements OnClickListener{
ListView lv;
static final int check=1111;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.voice);
lv=(ListView)findViewById(R.id.lvVoiceReturn);
Button b=(Button)findViewById(R.id.bVoice);
b.setOnClickListener(this);
lv.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId()){
case R.id.bVoice:
Intent i=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak Up");
startActivityForResult(i, check);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == check && resultCode==RESULT_OK){
ArrayList<String> results=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));
}
super.onActivityResult(requestCode, resultCode, data);
}
}
And another class TranslateActivity which has one button and two edit text. Button works as translator of text from 1st edit text to translated text in second edit Text and speaks the translated text also . Code is as follows:
package com.example.testing;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.memetix.mst.language.Language;
import com.memetix.mst.translate.Translate;
public class TranslateActivity extends Activity implements OnClickListener {
EditText etInput
;
EditText etOutput;
TextToSpeech tts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_translate);
Translate.setClientId("d6159b31-37ba-4668-a31f-de0de6c47a38");
Translate.setClientSecret("UMjSB3cHaSkLE+2xw4+a4dLIFahLdQQqh1YOhXdqfh4");
Button Trans = (Button)findViewById(R.id.translate);
etInput = (EditText)findViewById(R.id.input);
etOutput = (EditText)findViewById(R.id.output);
Trans.setOnClickListener(this);
tts =new TextToSpeech(TranslateActivity.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if(status !=TextToSpeech.ERROR){
tts.setLanguage(Locale.US);
}
}
});
}
#Override
public void onClick(View v) {
//get the text entered
String In =etInput.getText().toString();
String s[]=In.split(" ");
//String out[]= new String[3];
String str=new String();
String outString=new String();
//String Out;
try {
for(int i=0;i<s.length;i++){
if(s[i].equals("who")){
str="whoa";
//etOutput.setText("whoa");
//str=etOutput.getText().toString();
//tts.speak(str,TextToSpeech.QUEUE_FLUSH, null);
}else if(s[i].equals("are")){
// etOutput.setText("arey");
str="arey";
//str=etOutput.getText().toString();
//tts.speak(str,TextToSpeech.QUEUE_FLUSH, null);
}else if(s[i].equals("you")){
str="ram";
//etOutput.setText("your");
//str=etOutput.getText().toString();
//tts.speak(str,TextToSpeech.QUEUE_FLUSH, null);
}
outString+=str ;
outString+=" ";
}
tts.speak(outString,TextToSpeech.QUEUE_FLUSH, null);
// String Out = Translate.execute(In, Language.AUTO_DETECT, Language.FRENCH);
// etInput.setText(Out);
// etOutput.setText(Out);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now I want an on click listener for list view such that whatever line I click on list View, it gets used as edit Text of 2nd class(TranslateActivity.java) and gets translated without clicking the button on 2nd class. That is functionality of button in 2nd class is done by just clicking on list view in 1st class.Anyone who knows how to do this?

Shared Preferences doesn't get updated

I'm trying to make a world creator thing like in games and I am using shared preferences to store the arrays and such. But there is a problem. I am trying to update it from another class so I use static variables to do so. But when I go back to the original class with the list view, I find out that nothing has been updated. Any ideas? Here is the code. Oh and no errors came in the logcat.
ListView class.
package you.don't.need-to-know;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class WorldMenu extends ListActivity{
public static SharedPreferences prefs = null;
static String splitter;
String[] worldList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
splitter = "Create World," + prefs.getString("worldString", "");
worldList = splitter.split(",");
setListAdapter(new ArrayAdapter<String>(WorldMenu.this,
android.R.layout.simple_list_item_1, worldList));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
if(position == 0){
Intent openWorldNamer = new
Intent("you.don't.need-to-know");
startActivity(openWorldNamer);
}
}
}
The Updater:
package you.don't.need-to-know;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class WorldCreator extends Activity{
EditText worldNameEditor;
Button saver;
static String updater;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_worldcreator);
worldNameEditor = (EditText) findViewById(R.id.editText1);
saver = (Button) findViewById(R.id.button1);
updater = worldNameEditor.getText().toString() + ",";
saver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Editor editor = WorldMenu.prefs.edit();
editor.putString("worldString", updater);
editor.commit();
Intent openListWorld = new
Intent("you.don't.need.to-know");
startActivity(openListWorld);
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
Edit: New Code updated with closer to fixing. Updater and List Activity
Updater:
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class WorldCreator extends Activity{
EditText worldNameEditor;
Button saver;
SharedPreferences prefs;
OnSharedPreferenceChangeListener listener;
String updater;
Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_worldcreator);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
worldNameEditor = (EditText) findViewById(R.id.hello);
saver = (Button) findViewById(R.id.button1);
updater = worldNameEditor.getText().toString() + ",";
saver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
listener = new SharedPreferences.OnSharedPreferenceChangeListener()
{
public void onSharedPreferenceChanged(SharedPreferences
prefs, String key) {
editor = prefs.edit();
editor.putString("worldString", updater);
editor.commit();
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
Intent openListWorld = new
Intent("");
startActivity(openListWorld);
}});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
}
List Activity:
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class WorldMenu extends ListActivity{
SharedPreferences prefs = null;
String splitter;
String[] worldList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
prefs = PreferenceManager.getDefaultSharedPreferences(this);
splitter = "Create World," + prefs.getString("worldString", "hello");
worldList = splitter.split(",");
setListAdapter(new ArrayAdapter<String>(WorldMenu.this,
android.R.layout.simple_list_item_1, worldList));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
if(position == 0){
Intent openWorldNamer = new
Intent("");
startActivity(openWorldNamer);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
It doesn't look like you are monitoring for changes in the shared preferences. see:
http://developer.android.com/reference/android/content/SharedPreferences.OnSharedPreferenceChangeListener.html
final SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// update your listview.
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
So when you get that callback, it will tell you what key changed. Then you could update the adapter for your listview to have the new contents and call onDataSetChanged() in the adapter.
Alternatively, you could move your adapter setting code into the onResume() function. This would make it so when your activity resumes, you check the status of the shared preferences and set the adapter. Be warned though, if the user has scrolled down the list some distance and you call setAdapter() again in the resume, they will lose their scroll position.
EDIT:
Try:
Updater (this shouldn't need to start a new activity, this can just finish()):
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class WorldCreator extends Activity{
EditText worldNameEditor;
Button saver;
SharedPreferences prefs;
OnSharedPreferenceChangeListener listener;
String updater;
Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_worldcreator);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
worldNameEditor = (EditText) findViewById(R.id.hello);
saver = (Button) findViewById(R.id.button1);
updater = worldNameEditor.getText().toString() + ",";
saver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor = prefs.edit();
editor.putString("worldString", updater);
editor.commit();
finish();
}});
}
ListView:
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class WorldMenu extends ListActivity{
SharedPreferences prefs = null;
String splitter;
String[] worldList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// update your listview.
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
splitter = "Create World," + prefs.getString("worldString", "hello");
worldList = splitter.split(",");
setListAdapter(new ArrayAdapter<String>(WorldMenu.this,
android.R.layout.simple_list_item_1, worldList));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
if(position == 0){
Intent openWorldNamer = new
Intent("");
startActivity(openWorldNamer);
}
}
}
Prefrences are defined at the activity level. I'll have my bounty please.
Call getActivity() to get the callers activity then use that to get the prefrences.
If you want structure send results back via interface. Implement the interface and use the interface to find the activity. Eclipse creates stubs for you.
Here is the complete class that just changes a prefrence save's it and immediately sends the result back to the calling class. It uses getActivity() so the two classes share the same prefrences. It calls back through an interface.
It's from my app com.gosylvester.bestrides
package com.gosylvester.bestrides;
import com.google.android.gms.maps.GoogleMap;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
//...
public class MapSettings extends DialogFragment implements
OnCheckedChangeListener {
public static final String MAP_TYPE = "com.gosylvester.bestrides.settings.maptype";
private int _mapType = -1;
BestRidesSettingsDialogListener activity;
SharedPreferences sharedpref;
public interface BestRidesSettingsDialogListener {
void onMapSettingsChange(int mapType);
}
public MapSettings() {
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// the activity may be null if this is called without implementing the
// BestRidesSettingsDialogListener (The settings object saves the
// setting so the
// call back may not be needed.
activity = (BestRidesSettingsDialogListener) getActivity();
getDialog().setTitle(R.string.app_name);
View view = inflater.inflate(R.layout.activity_map_settings, container);
RadioGroup rg = (RadioGroup) view.findViewById(R.id.radioGroup1);
// initialize to the shared preferences value
rg.clearCheck();
sharedpref = getActivity().getPreferences(Context.MODE_PRIVATE);
int x = sharedpref.getInt(MAP_TYPE, GoogleMap.MAP_TYPE_NORMAL);
RadioButton rb = null;
switch (x) {
case GoogleMap.MAP_TYPE_HYBRID:
rb = (RadioButton) view.findViewById(R.id.RDOHybrid);
rb.setChecked(true);
break;
case GoogleMap.MAP_TYPE_NORMAL:
rb = (RadioButton) view.findViewById(R.id.RDORoad);
rb.setChecked(true);
break;
case GoogleMap.MAP_TYPE_SATELLITE:
rb = (RadioButton) view.findViewById(R.id.RDOSatelite);
rb.setChecked(true);
break;
case GoogleMap.MAP_TYPE_TERRAIN:
rb = (RadioButton) view.findViewById(R.id.RDOTerrain);
rb.setChecked(true);
break;
}
// set the listener after setting up
rg.setOnCheckedChangeListener(this);
return view;
}
public int getMapType() {
return _mapType;
}
public void setMapType(int mapType) {
this._mapType = mapType;
}
#Override
public void onCheckedChanged(RadioGroup rg, int checkId) {
// TODO Auto-generated method stub
int mapType = 0;
switch (checkId) {
case R.id.RDORoad:
mapType = GoogleMap.MAP_TYPE_NORMAL;
break;
case R.id.RDOHybrid:
mapType = GoogleMap.MAP_TYPE_HYBRID;
break;
case R.id.RDOSatelite:
mapType = GoogleMap.MAP_TYPE_SATELLITE;
break;
case R.id.RDOTerrain:
mapType = GoogleMap.MAP_TYPE_TERRAIN;
break;
}
// run the activity onchange
// if the activity is null there is no listener to take action on the
// settings
if (activity != null) {
activity.onMapSettingsChange(mapType);
}
// save the settings
if (sharedpref == null) {
sharedpref = getActivity().getPreferences(Context.MODE_PRIVATE);
}
sharedpref.edit().putInt(MAP_TYPE, mapType).commit();
}
}
/* here's a snipet of the other class */
public class KmlReader extends FragmentActivity implements
BestRidesSettingsDialogListener {
...
mMap.setMapType(sharedPref.getInt(
com.gosylvester.bestrides.MapSettings.MAP_TYPE,
GoogleMap.MAP_TYPE_NORMAL));
...
#Override
public void onMapSettingsChange(int mapType) {
// TODO Auto-generated method stub
if (mMap != null) {
mMap.setMapType(mapType);
}
}
Good Luck
Shared prefernces are meant to be used in multiple classes if all classes are in same process. You do not have to use static explicitely. Just use the same sharedprefernce in both classes.
when you go back to the original class it doesn't guarantee onCreate mothod of the original class can perform ,like other answers say ,you can put the code into onResume mothod ,or after startActivity(intent) add method finish() to finish current activity

Turn on/off sound button not working

I have it in my settings activity that when a user clicks the ToggleButton it's supposed to mute the sound throughout my application but it's not working.The SoundPool onClick button sounds I putted in my Tutorial classes are still playing sound onClick.I already specified my Shared Preferences with the ToggleButton.
Here is my code,
package com.fullfrontalgames.numberfighter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ToggleButton;
public class Settings extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
Button Notifications = (Button) findViewById(R.id.Notifications);
Button Done = (Button) findViewById(R.id.done);
Button AccountSettings = (Button) findViewById(R.id.AccountSettings);
final ToggleButton AT = (ToggleButton) findViewById(R.id.AudioToggle);
AT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences appPrefs =
getSharedPreferences("com.fullfrontalgames.numberfighter.Settings_preferences",
MODE_PRIVATE);
SharedPreferences.Editor editor = appPrefs.edit();
editor.putBoolean("atpref", AT.isChecked()); //value to store
editor.commit();
if ((AT.isChecked())) {
AT.setSoundEffectsEnabled(true);
} else {
AT.setSoundEffectsEnabled(false);
}
}
});
SharedPreferences appPrefs =
getSharedPreferences("com.fullfrontalgames.numberfighter.Settings_preferences",
MODE_PRIVATE);
boolean atpref = appPrefs.getBoolean("atpref", true); //default is true
AT.setChecked(atpref);
Done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent Intent = new Intent(Settings.this,activity_main.class);
Intent.setFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(Intent);
}
});
Notifications.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.fullfrontalgames.numberfighter.Notifications"));
}
});
AccountSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.fullfrontalgames.numberfighter.AccountSettings"));
}
});
}
according to doc of setSoundEffectsEnabled
Set whether this view should have sound effects enabled for events
such as clicking and touching.
You may wish to disable sound effects for a view if you already play
sounds, for instance, a dial key that plays dtmf tones.
So this function is supposed to set on off of the sound effect of the view (like click or touch). Not to set on off of the device sound.
For your purpose check AudioManager

Error when checking Internet Connection in Android

The idea is when there is no internet connection available, show my custom dialog to users which indicates there is no connection. Otherwise, when page is loading in WebView, show a ProgressDialog to show that page is loading and dismiss when loading is done. When there is an internet connection this code works, but if there is no, it crashes and I can't find where the error is.
package com.tariknotebook;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
public class NoteBook extends Activity {
/** Called when the activity is first created. */
WebView web;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
web = (WebView) findViewById(R.id.browserMine);
web.setWebViewClient(new HelloWebViewClient());
web.getSettings().setJavaScriptEnabled(true);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
web.loadUrl("http://m.seslisozluk.com");
}
ProgressDialog dialog;
Dialog connDialog;
#Override
protected Dialog onCreateDialog(int id) {
switch(id)
{
case 1:
dialog = ProgressDialog.show(NoteBook.this, "Loading",
"Loading.. Please wait.");
break;
case 2:
connDialog = new Dialog(getApplicationContext());
connDialog.setContentView(R.layout.connection);
connDialog.setTitle("No Internet Connection");
Button closeButton = (Button) findViewById(R.id.closeButton);
closeButton.setOnClickListener(new closeButtonOnClickListener());
connDialog.show();
break;
}
return super.onCreateDialog(id);
}
private class closeButtonOnClickListener implements OnClickListener
{
public void onClick(View v) {
connDialog.dismiss();
};
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
ConnectivityManager conStatus = (ConnectivityManager) view.getContext().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if(conStatus.getActiveNetworkInfo().isConnected() && conStatus.getActiveNetworkInfo() != null)
showDialog(1);
else
showDialog(2);
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
dialog.dismiss();
}
}
}
And this is the error log as well :
When you post error messages, you should tell us which line of the source corresponds.
By pasting your code into a text editor, I believe line 83 is:
if(conStatus.getActiveNetworkInfo().isConnected() && conStatus.getActiveNetworkInfo() != null)
This strongly suggests that conStatus is null and you are trying to call a method of non-existent object.
You should check that it's non-null first.

Categories

Resources