sharedpreferences not loading or saving - java

I'm trying to used sharedpreferences for when a user chooses a specific custom image they want in their storage for a part of a grid of images. I want the image they chose to show up even after they close the application and reopen it. The problem I'm having is that the sharedpreferences don't seem to be working. Nothing shows up as the background image for the grid item they've selected once they've closed the app or even just pressed the back button.
Do I have to create a sharedpreferences file myself? I can't figure out how to get to it or create one if so using androidstudio.
Here's my code for the class (Sorry if it's long and messy...I am new to coding and still testing things):
public class editCreations extends Activity {
public int mPosition = 0;
protected static Sounds sound = new Sounds();
private static int RESULT_LOAD_IMAGE = 1;
private MediaRecorder mRecorder;
private MediaPlayer mPlayer;
private String mOutputFile = Environment.getExternalStorageDirectory().getAbsolutePath();
private Drawable mImageFileName;
private Button recordBtn;
private Button stopBtn;
private Button playBtn;
private Button stopPlayBtn;
private ImageButton imgBtn;
private Drawable bg;
private String mPicturePath;
private ImageAdapter img = new ImageAdapter(this);
View.OnClickListener playListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(editCreations.this, "test", Toast.LENGTH_SHORT);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mRecorder.setOutputFile(mOutputFile);
recordBtn = (Button)findViewById(R.id.create_record_button);
recordBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
start(view);
}
});
stopBtn = (Button)findViewById(R.id.create_stop_record_button);
stopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stop(view);
}
});
playBtn = (Button)findViewById(R.id.create_play_button);
playBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play(view);
}
});
stopPlayBtn = (Button)findViewById(R.id.create_stop_button);
stopPlayBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopPlay(view);
}
});
imgBtn = (ImageButton)findViewById(R.id.imageButton);
Intent extra = getIntent();
Bundle extras = extra.getExtras();
// gave mPosition a default int to debug and find problem -> found it
mPosition = extras.getInt("position");
getSelectedFile(mPosition);
imgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
public void start (View view) {
try {
mRecorder.prepare();
mRecorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recordBtn.setEnabled(false);
stopBtn.setEnabled(true);
Toast.makeText(editCreations.this, mPosition + "!", Toast.LENGTH_SHORT).show();
}
public void stop(View view){
try {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
stopBtn.setEnabled(false);
recordBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Stop recording...",
Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
public void play(View view) {
try{
mPlayer = new MediaPlayer();
mPlayer.setDataSource(mOutputFile);
mPlayer.prepare();
mPlayer.start();
playBtn.setEnabled(false);
stopPlayBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Start play the recording...",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopPlay(View view) {
try {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
playBtn.setEnabled(true);
stopPlayBtn.setEnabled(false);
Toast.makeText(getApplicationContext(), "Stop playing the recording...",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e){
e.printStackTrace();
}
}
public void getSoundPosition(int position) {
mOutputFile = mOutputFile + "/Lollatone_clip_" + mPosition + ".3gpp";
// use to get proper image and sound files and edit output file to proper name
}
public void getSelectedFile(int position) {
switch (mPosition) {
case 0:
imgBtn.setBackgroundResource(R.drawable.sample_0);
imgBtn.refreshDrawableState();
break;
case 1:
imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
imgBtn.refreshDrawableState();
break;
case 2:
imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
imgBtn.refreshDrawableState();
break;
case 3:
imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
imgBtn.refreshDrawableState();
break;
case 4:
imgBtn.setBackgroundResource(R.drawable.sample_4);
imgBtn.refreshDrawableState();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_creations, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mPicturePath = cursor.getString(columnIndex);
cursor.close();
imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
imgBtn.refreshDrawableState();
// String picturePath contains the path of
// selected image
}
}
protected void onPause() {
super.onPause();
//need an editor object to make preference changes
// all objects are from android.context.Context
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("img_" + mPosition, mPicturePath);
editor.commit();
}
protected void onResume() {
super.onResume();
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
mPicturePath = sharedPref.getString("img_" + mPosition, "img_" + mPosition);
}
}

You are using SharedPreferences correctly but you are not placing the code in the right activity lifecycle methods. You are reading the preference on onCreate() and saving on onStop() so maybe what you can do it save the preference on onPause() (to make sure it gets saved earlier) and reload on onResume() instead of onCreate() (the latter only occurs once in the life cycle of an activity).
Also, you might want to check if Context.getSharedPreferences() would be a better choice for this, since it's shared between more than just one activity.

Related

Scanning for bluetooth devices programmatically don't find anything in android 6+

I created an application which pairs a cellphone to a bluetooth module.
i tested this application with a 4.2 android cellphone and it worked quite well but in cellphones with android higher than 6 the device is not fidning anything when i press " Scan for new devices " button.
but when i go through my phone bluetooth itself, i can find the module i was looking for..
Bluetooth connection class :
public class BluetoothConnectionActivity extends AppCompatActivity {
private ProgressDialog mProgressDlg;
private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>();
private BluetoothAdapter mBluetoothAdapter;
BluetoothDevice device ;
private MediaPlayer mediaplayer = null ;
private Button bluetoothOnOff;
private Button viewpairedDevices;
private Button scanfornewDevices;
private Button blue2;
ImageView unMute;
View view1;
View view2;
private Activity context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetoothconnectionlayout);
bluetoothOnOff = (Button) findViewById(R.id.bluetoothOnOff);
viewpairedDevices = (Button) findViewById(R.id.viewpairedDevicesButton);
scanfornewDevices = (Button) findViewById(R.id.scanfornewDevicesButton);
blue2 = (Button) findViewById(R.id.bluetoothOnOff2);
view1 = findViewById(R.id.viewFader);
view2 = findViewById(R.id.viewFader2);
unMute = (ImageView) findViewById(R.id.settingStartupSecondary);
mediaplayer = MediaPlayer.create(getApplicationContext(),R.raw.sfxturnon);
Handler startup1 = new Handler();
startup1.postDelayed(new Runnable() {
#Override
public void run() {
view1.animate().alpha(1f).setDuration(500);
view2.animate().alpha(1f).setDuration(500);
}
},1000);
Handler startup2 = new Handler();
startup2.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().alpha(1f).setDuration(500);
viewpairedDevices.animate().alpha(1f).setDuration(500);
scanfornewDevices.animate().alpha(1f).setDuration(500);
unMute.animate().alpha(1f).setDuration(100);
}
},1000);
//
// settingBtn.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
//
//
// AudioManager amanager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
// amanager.setStreamMute(AudioManager.STREAM_NOTIFICATION, true);
//
//// settingBtn.setEnabled(false);
//// settingBtn.animate().alpha(0f);
//
// unMute.animate().alpha(1f);
// unMute.setEnabled(true);
//
//
// Toast.makeText(getApplicationContext(), " Application muted. ", Toast.LENGTH_SHORT).show();
//
//
// }
// });
Handler dawg = new Handler();
dawg.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().alpha(1f).setDuration(1500);
viewpairedDevices.animate().alpha(1f).setDuration(2500);
scanfornewDevices.animate().alpha(1f).setDuration(3000);
}
},500);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mProgressDlg = new ProgressDialog(this);
mProgressDlg.setMessage("Scanning, Please wait...");
mProgressDlg.setCancelable(false);
mProgressDlg.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mBluetoothAdapter.cancelDiscovery();
}
});}
if (mBluetoothAdapter.isEnabled()){
bluetoothOnOff.setText("Bluetooth is On");
blue2.setText("Bluetooth is On");
}else {
blue2.setText("Bluetooth is Off");
bluetoothOnOff.setText("Bluetooth is Off");
}
if (mBluetoothAdapter == null) {
showUnsupported();
} else {
viewpairedDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices == null || pairedDevices.size() == 0) {
Toast toast = Toast.makeText(getApplicationContext()," No paired device found.", Toast.LENGTH_SHORT);
View view3 = toast.getView();
view3.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view3.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
} else {
ArrayList<BluetoothDevice> list = new ArrayList<BluetoothDevice>();
list.addAll(pairedDevices);
Intent intent = new Intent(BluetoothConnectionActivity.this, DeviceList.class);
intent.putParcelableArrayListExtra("device.list", list);
startActivity(intent);
}
}
});
scanfornewDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mBluetoothAdapter.startDiscovery();
}
});
bluetoothOnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
showDisabled();
bluetoothOnOff.setText("Bluetooth is OFF");
final Handler handler6 = new Handler();
handler6.postDelayed(new Runnable() {
#Override
public void run() {
mediaplayer.start();
}
}, 500);
final Handler handler3 = new Handler();
handler3.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().translationY(-1f).setDuration(5000);
blue2.animate().translationY(-1f).setDuration(5000);
bluetoothOnOff.animate().alpha(1f).setDuration(3000);
blue2.animate().alpha(0f).setDuration(3000);
}
}, 500);
} else {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1000);
}}
});
blue2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
showDisabled();
bluetoothOnOff.setText("Bluetooth is OFF");
final Handler handler6 = new Handler();
handler6.postDelayed(new Runnable() {
#Override
public void run() {
mediaplayer.start();
}
}, 500);
final Handler handler3 = new Handler();
handler3.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().translationY(-1f).setDuration(5000);
blue2.animate().translationY(-1f).setDuration(5000);
bluetoothOnOff.animate().alpha(1f).setDuration(3000);
blue2.animate().alpha(0f).setDuration(3000);
}
}, 500);
} else {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1000);
}}
});
if (mBluetoothAdapter.isEnabled()) {
showEnabled();
} else {
showDisabled();
}
}
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
}
#Override
public void onPause() {
if (mBluetoothAdapter != null) {
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
}
super.onPause();
}
#Override
public void onBackPressed() {
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private void showEnabled() {
bluetoothOnOff.setEnabled(true);
viewpairedDevices.setEnabled(true);
viewpairedDevices.setBackgroundResource(R.drawable.selectorstylish);
scanfornewDevices.setEnabled(true);
scanfornewDevices.setBackgroundResource(R.drawable.selectorstylish);
}
private void showDisabled() {
bluetoothOnOff.setEnabled(true);
viewpairedDevices.setEnabled(false);
viewpairedDevices.setBackgroundResource(R.drawable.selectorstylish);
scanfornewDevices.setEnabled(false);
scanfornewDevices.setBackgroundResource(R.drawable.selectorstylish);
}
private void showUnsupported() {
Toast toast = Toast.makeText(getApplicationContext()," Bluetooth is not supported by this device.", Toast.LENGTH_SHORT);
View view3 = toast.getView();
view3.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view3.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
bluetoothOnOff.setEnabled(false);
viewpairedDevices.setEnabled(false);
viewpairedDevices.setBackgroundResource(R.drawable.selectorstylish);
scanfornewDevices.setEnabled(false);
scanfornewDevices.setBackgroundResource(R.drawable.selectorstylish);
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_ON) {
bluetoothOnOff.setText("Bluetooth is On");
blue2.setText("Bluetooth is On");
showEnabled();
final Handler handler5 = new Handler();
handler5.postDelayed(new Runnable() {
#Override
public void run() {
mediaplayer.start();
}
}, 500);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().translationY(150f).setDuration(5000);
blue2.animate().translationY(150f).setDuration(5000);
bluetoothOnOff.animate().alpha(0f).setDuration(3000);
blue2.animate().alpha(1f).setDuration(3000);
}
}, 500);
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
mDeviceList = new ArrayList<BluetoothDevice>();
mProgressDlg.show();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mProgressDlg.dismiss();
// Intent newIntent = new Intent(BluetoothConnectionActivity.this, DeviceList.class);
//
// newIntent.putParcelableArrayListExtra("device.list", mDeviceList);
//
// startActivity(newIntent);
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device);
Toast toast = Toast.makeText(getApplicationContext()," Found device" + device.getName(), Toast.LENGTH_SHORT);
View view3 = toast.getView();
view3.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view3.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.optionmenu,menu);
return super.onCreateOptionsMenu(menu);
}
}
Device list Class :
public class DeviceList extends AppCompatActivity {
private ListView mListView;
private AdapterClassBluetooth mAdapterClassBluetooth;
private ArrayList<BluetoothDevice> mDeviceList;
private BluetoothDevice device ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
mDeviceList = getIntent().getExtras().getParcelableArrayList("device.list");
mListView = (ListView) findViewById(R.id.lv_paired);
mAdapterClassBluetooth = new AdapterClassBluetooth(this);
mAdapterClassBluetooth.setData(mDeviceList);
mAdapterClassBluetooth.setListener(new AdapterClassBluetooth.OnPairButtonClickListener() {
#Override
public void onPairButtonClick(int position) {
BluetoothDevice device = mDeviceList.get(position);
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
unpairDevice(device);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "Pairing..." , Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
pairDevice(device);
}
}
});
mListView.setAdapter(mAdapterClassBluetooth);
registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
}
#Override
public void onDestroy() {
unregisterReceiver(mPairReceiver);
super.onDestroy();
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void unpairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
Toast toast = Toast.makeText(getApplicationContext()," Device are paired, please wait...", Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
Handler delaying = new Handler();
delaying.postDelayed(new Runnable() {
#Override
public void run() {
Intent communicate = new Intent(DeviceList.this,Security.class);
startActivity(communicate);
finish();
}
},1500);
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
Toast toast = Toast.makeText(getApplicationContext(),"Unpaired.", Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
}
mAdapterClassBluetooth.notifyDataSetChanged();
}
}
};}
Adapter class :
public class AdapterClassBluetooth extends BaseAdapter{
private LayoutInflater mInflater;
private List<BluetoothDevice> mData;
private OnPairButtonClickListener mListener;
public AdapterClassBluetooth(){
}
public AdapterClassBluetooth(Context context) {
super();
mInflater = LayoutInflater.from(context);
}
public void setData(List<BluetoothDevice> data) {
mData = data;
}
public void setListener(OnPairButtonClickListener listener) {
mListener = listener;
}
public int getCount() {
return (mData == null) ? 0 : mData.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.adapterlist, null);
holder = new ViewHolder();
holder.nameTv = (TextView) convertView.findViewById(R.id.tv_name);
holder.addressTv = (TextView) convertView.findViewById(R.id.tv_address);
holder.pairBtn = (Button) convertView.findViewById(R.id.btn_pair);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
BluetoothDevice device = mData.get(position);
holder.nameTv.setText(device.getName());
holder.addressTv.setText(device.getAddress());
holder.pairBtn.setText((device.getBondState() == BluetoothDevice.BOND_BONDED) ? "Unpair" : "Pair");
holder.pairBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
mListener.onPairButtonClick(position);
}
}
});
return convertView;
}
static class ViewHolder {
TextView nameTv;
TextView addressTv;
TextView pairBtn;
}
public interface OnPairButtonClickListener {
public abstract void onPairButtonClick(int position);
}
}
in an article i studied about this issue and find out that with this code :
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(context,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1);
i can make the application to support phones with android more than 6 so i can discover all nearby devices and pair with them,
The issue is, i don't know where should i exactly use this code..
i would really appreciate if you could tell me where to use it within the codes i showed here.
or simply tell me how to overcome this problem with any other code you may know.
In your AndroidManifest.xml file add this:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Then, instead of calling registerReceiver call this function:
private tryRegisterReceiver() {
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Here, permission is not granted
// after calling requestPermissions, the result must be treated in onRequestPermissionResult
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1000); // 100 or other desired code
} else {
// Permission has already been granted
// continue registering your receiver
registerReceiver();
}
}
To treat the result of the permission request
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case 1000: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
// continue registering your receiver
registerReceiver();
} else {
// permission denied
// show a message or finish your activity
}
return;
}
// other 'case' for other permissions if needed
}
}

Android studio app crashes while attempting to send file over bluetooth

Android bluetooth app crashes while trying to send data via bluetooth. I was able to turn on, make discoverable, and show paired devices. But, it crashes when i attempt the send file button. Im getting these errors in my Debugger.
Process: com.example.bluetooth_demoproject, PID: 31320
java.lang.NullPointerException: Attempt to get length of null
array
at com.example.bluetooth_demoproject.MainActivity.ListDir(MainActivity.java:253)
at com.example.bluetooth_demoproject.MainActivity.onPrepareDialog(MainActivity.java:228)
at android.app.Activity.onPrepareDialog(Activity.java:4000)
at android.app.Activity.showDialog(Activity.java:4063)
at android.app.Activity.showDialog(Activity.java:4014)
at
com.example.bluetooth_demoproject.MainActivity$1.onClick(MainActivity.java:75)
at android.view.View.performClick(View.java:6896)
at
android.widget.TextView.performClick(TextView.java:12689)
at android.view.View$PerformClick.run(View.java:26088)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at
android.app.ActivityThread.main(ActivityThread.java:6940)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Also here is my MainActivity. If theres a better way to sending files via
bluetooth please point it out or help with my code.
public class MainActivity extends Activity {
// Creating objects -----------------------------
private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_DISCOVER_BT_ = 1;
private static int CUSTOM_DIALOG_ID;
ListView dialog_ListView;
TextView mBluetoothStatus, mPairedDevicesList, mTextFolder;
ImageView mBluetoothIcon;
Button mOnButton, mOffButton, mDiscoverableButton, mPairedDevices,
mbuttonOpenDialog, msendBluetooth, mbuttonUp;
File root, fileroot, curFolder;
EditText dataPath;
private static final int DISCOVER_DURATION = 300;
private List<String> fileList = new ArrayList<String>();
// -------------------------------------------------------
BluetoothAdapter mBlueAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataPath =(EditText) findViewById(R.id.FilePath);
mTextFolder = findViewById(R.id.folder);
mBluetoothStatus = findViewById(R.id.BluetoothStatus);
mBluetoothIcon = findViewById(R.id.bluetoothIcon);
mOnButton = findViewById(R.id.onButton);
mOffButton = findViewById(R.id.offButton);
mDiscoverableButton = findViewById(R.id.discoverableButton);
mPairedDevices = findViewById(R.id.pairedDevices);
mPairedDevicesList = findViewById(R.id.pairedDeviceList);
mbuttonOpenDialog = findViewById(R.id.opendailog);
msendBluetooth = findViewById(R.id.sendBluetooth);
mbuttonUp = findViewById(R.id.up);
mbuttonOpenDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dataPath.setText("");
showDialog(CUSTOM_DIALOG_ID);
}
});
root = new
File(Environment.getExternalStorageDirectory().getAbsolutePath());
curFolder = root;
msendBluetooth.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
sendViaBluetooth();
}
});
//adapter
mBlueAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBlueAdapter == null){
mBluetoothStatus.setText("Bluetooth is not available");
return;
}
else {
mBluetoothStatus.setText("Bluetooth is available");
}
//if Bluetooth isnt enabled, enable it
if (!mBlueAdapter.isEnabled()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//set image according to bluetooth Status
if (mBlueAdapter.isEnabled()) {
mBluetoothIcon.setImageResource(R.drawable.action_on);
}
else {
mBluetoothIcon.setImageResource(R.drawable.action_off);
}
//on button Click
mOnButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (!mBlueAdapter.isEnabled()) {
showToast("Turning Bluetooth on...");
// intent to on bluetooth
Intent intent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_ENABLE_BT);
}
else {
showToast("Bluetooth is already on");
}
}
});
//discover Bluetooth button
mDiscoverableButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (!mBlueAdapter.isDiscovering()) {
showToast("Making device discoverable");
Intent intent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(intent, REQUEST_DISCOVER_BT_);
}
}
});
// off button click
mOffButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBlueAdapter.isEnabled()) {
showToast("Turning Bluetooth off...");
// intent to turn off bluetooth
mBluetoothIcon.setImageResource(R.drawable.action_off);
}
else{
showToast("Bluetooth is already off");
}
}
});
//get paired device button click
mPairedDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBlueAdapter.isEnabled()) {
mPairedDevices.setText("Paired Devices");
Set<BluetoothDevice> devices =
mBlueAdapter.getBondedDevices();
for (BluetoothDevice device : devices){
mPairedDevices.append("\nDevice: " + device.getName() +
"," + device );
}
}
else {
//bluetooth is off and cant get paired devices
showToast("Turn on bluetooth to get paired devices");
}
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
if (id == CUSTOM_DIALOG_ID) {
dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dailoglayout);
dialog.setTitle("File Selector");
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
mTextFolder = (TextView) dialog.findViewById(R.id.folder);
mbuttonUp = (Button) dialog.findViewById(R.id.up);
mbuttonUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListDir(curFolder.getParentFile());
}
});
dialog_ListView = (ListView) dialog.findViewById(R.id.dialoglist);
dialog_ListView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
File selected = new File(fileList.get(position));
if (selected.isDirectory()) {
ListDir(selected);
} else if (selected.isFile()) {
getSelectedFile(selected);
} else {
dismissDialog(CUSTOM_DIALOG_ID);
}
}
});
}
return dialog;
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
if (id == CUSTOM_DIALOG_ID) {
ListDir(curFolder);
}
}
public void getSelectedFile(File f) {
dataPath.setText(f.getAbsolutePath());
fileList.clear();
dismissDialog(CUSTOM_DIALOG_ID);
}
public void ListDir(File f) {
if (f.equals(root)) {
mbuttonUp.setEnabled(false);
}
else {
mbuttonUp.setEnabled(true);
}
curFolder = f;
mTextFolder.setText(f.getAbsolutePath());
dataPath.setText(f.getAbsolutePath());
File[] files = f.listFiles();
fileList.clear();
for (File file : files) {
fileList.add(file.getPath());
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, fileList);
dialog_ListView.setAdapter(directoryList);
}
// exits to app --------------------------------
public void exit(View V) {
mBlueAdapter.disable();
Toast.makeText(this, "*** Now bluetooth is off...",
Toast.LENGTH_LONG).show();
finish();
}
// send file via bluetooth ------------------------
public void sendViaBluetooth() {
if(!dataPath.equals(null)) {
if(mBlueAdapter == null) {
Toast.makeText(this, "Device doesnt support bluetooth",
Toast.LENGTH_LONG).show();
}
else {
enableBluetooth();
}
}
else {
Toast.makeText(this, "please select a file",
Toast.LENGTH_LONG).show();
}
}
public void enableBluetooth() {
showToast("Making device discoverable");
Intent intent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(intent, REQUEST_DISCOVER_BT_);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
if (resultCode == DISCOVER_DURATION && requestCode ==
REQUEST_DISCOVER_BT_) {
Intent i = new Intent();
i.setAction(Intent.ACTION_SEND);
i.setType("*/*");
File file = new File(dataPath.getText().toString());
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
PackageManager pm = getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(i, 0);
if (list.size() > 0) {
String packageName = null;
String className = null;
boolean found = false;
for (ResolveInfo info : list) {
packageName = info.activityInfo.packageName;
if (packageName.equals("com.android.bluetooth")) {
className = info.activityInfo.name;
found = true;
}
}
//CHECK BLUETOOTH available or not------------------------------
------------------
if (!found) {
Toast.makeText(this, "Bluetooth not been found",
Toast.LENGTH_LONG).show();
} else {
i.setClassName(packageName, className);
startActivity(i);
}
}
} else {
Toast.makeText(this, "Bluetooth is cancelled",
Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
//toast message function
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT) .show();
}
}

Zxing Bar code scanner issue in Android

I am working on a barcode scanner App where on button click in the first Activity, I am moving to the BarcodeScanner Activity where I am importing Zxing library functionalities. Once the scanning is completed, I am moving to a 3rd Activity where I am showing the scanned Results. On clicking a button in the 3rd activity, i am coming back to the 1st activity. For devices having Marshmallow, the code is running fine. But the issue is happening with devices having versions below marshmallow where after going back to the 1st activity from the 3rd Activity, when i am pressing again the button, the scanner activity is appearing but the camera is not starting. It just showing a blank page. Please help. Below I am posting my codes for all 3 Activities.
First Activity:
public class FirstActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(Color.parseColor("#FDB50A"));
}
ImageView Scan= (ImageView) findViewById(R.id.scanButton);
Scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirstActivity.this.finish();
Intent nextPage= new Intent(FirstActivity.this,MainActivity.class);
startActivity(nextPage);
}
});
ScannerActivity:
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
Integer response = 0 ;
int currentIndex=0;
Boolean flash=false;
DataBaseHelper dataBaseHelper;
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("onCreate", "onCreate");
checkPermissions();
mScannerView = new ZXingScannerView(this);
mScannerView.setResultHandler(this);
boolean cam= isCameraUsebyApp();
Log.d("cameraBar",cam+"");
if(cam)
{
mScannerView.stopCamera();
}
cam= isCameraUsebyApp();
Log.d("cameraBar",cam+"");
mScannerView.startCamera();
// FrameLayout frameLayout= new FrameLayout(this);
// FrameLayout.LayoutParams mainParam= new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
// frameLayout.setLayoutParams(mainParam);
// Button scanButton= new Button(this);
dataBaseHelper= new DataBaseHelper(this);
if(dataBaseHelper.checkDataBase()==false)
{
try {
dataBaseHelper.createDataBase();
} catch (IOException e)
{
e.printStackTrace();
}
}
else{
}
Log.d("AnimeshSQL","copy");
dataBaseHelper.openDataBase();
// List<String> data=dataBaseHelper.getQuotes("n",1);
// Log.d("AnimeshSQL",data.get(0).toString());
LayoutParams params =
new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
// scanButton.setBackground(getResources().getDrawable(R.drawable.round_button));
// scanButton.setText("Flash");
// scanButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// if(flash==false)
// {
// flash=true;
//
//
// }
// else
// {
// flash=false;
// }
// mScannerView.setFlash(flash);
// }
// });
// scanButton.setLayoutParams(params);
// frameLayout.addView(mScannerView);
// frameLayout.addView(scanButton);
// setContentView(mScannerView);
checkPermissions();
if(response == 1) {
mScannerView = null;
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
response = 0;
}
}
public boolean isCameraUsebyApp() {
Camera camera = null;
try {
camera = Camera.open();
} catch (RuntimeException e) {
return true;
} finally {
if (camera != null) camera.release();
}
return false;
}
private void checkPermissions() {
try {
for (int i = currentIndex; i < permissions.length; i++) {
currentIndex = currentIndex + 1;
int result = ContextCompat.checkSelfPermission(context, permissions[i]);
if (result == PackageManager.PERMISSION_GRANTED) {
} else {
requestPermission(permissions[i]);
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Activity activity = this;
Context context = this;
String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
private void requestPermission(String permission) {
//
ActivityCompat.requestPermissions(activity, new String[]{permission}, 101);
//
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 101:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//
checkPermissions();
} else {
try {
// FuncUtils.showToast(context, permissions[0] + " Denied!!!");
} catch (Exception e) {
e.printStackTrace();
}
//
///
}
break;
}
}
#Override
public void onResume() {
super.onResume();
if(response == 1) {
mScannerView = null;
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
response = 0;
}
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
public void onDestroy() {
super.onDestroy();
mScannerView.stopCamera();
}
#Override
protected void onRestart() {
super.onRestart();
Log.d("ani","onrestart");
}
#Override
public void handleResult(Result rawResult)
{
//Some codes to handle the result
Intent intent= new Intent(this,ScanResultActivity.class);
startActivity(intent);
//vbn
mScannerView.stopCamera();
MainActivity.this.finish();
}
}
Final Activity:
public class ScanResultActivity extends AppCompatActivity {
SharedPreferences prefs;
Button ok;
ImageView Hubbell,CI;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_result);
prefs = getSharedPreferences("ScanPref", MODE_PRIVATE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(Color.parseColor("#FDB50A"));
}
//Codes to show the data
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ScanResultActivity.this.finish();
Intent nextPage= new Intent(ScanResultActivity.this,FirstActivity.class);
startActivity(nextPage);
}
});
You can write Intent in OnActivityResult.
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String message=data.getStringExtra("MESSAGE");
textView1.setText(message);
}
}

Update sharedpreference that uses checkbox

I want to update the changes when I uncheck and check the checkbox in the preference activity but when I press the back button it doesn't work. It only works when I close the activity and then open it
Main activity
public class MainActivity extends ActionBarActivity {
private ToggleButton togle;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
private ShakeListener mShaker;
MediaPlayer mp;
ImageView anime;
int p=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
anime = (ImageView) findViewById(R.id.Animation);
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish(); }
});
alert.show();
return;}
getCamera();
togle = (ToggleButton) findViewById(R.id.ToggleButton01);
togle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean checked = ((ToggleButton) v).isChecked();
if (checked){
turnOffFlash();
}
else{
getCamera();
turnOnFlash();
}
}
});
SharedPreferences getprefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean stopshake = getprefs.getBoolean("checkbox", true);
if (stopshake == true ){
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
public void onShake()
{ if (!isFlashOn) {
Toast.makeText(MainActivity.this, "On" , Toast.LENGTH_SHORT).show();
getCamera();
turnOnFlash();
}
else{
turnOffFlash();
Toast.makeText(MainActivity.this, "Off" , Toast.LENGTH_SHORT).show();
} }
});
}
}
private void getCamera() {
// TODO Auto-generated method stub
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
} }
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
getCamera();
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
anime.setImageResource(R.drawable.anim);
anime.post(new Runnable() {
#Override
public void run() {
AnimationDrawable frameAnimation =
(AnimationDrawable) anime.getDrawable();
frameAnimation.start();
}
});
// changing button/switch image
}
}
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
isFlashOn = false;
anime.setImageResource(R.drawable.off);
// changing button/switch image
}
}
private void playSound() {
// TODO Auto-generated method stub
if(isFlashOn){
mp = MediaPlayer.create(MainActivity.this, R.raw.off1);
}else{
mp = MediaPlayer.create(MainActivity.this, R.raw.on1);
}
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
#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
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent(MainActivity.this, Prefsetting.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Preference activity
public class Prefsetting extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefset);
}
}
You access SharedPreferences in the onCreate() of your MainActivity, which is only called when that activity is created from scratch (i.e. when you first start your app). As you (presumably) navigate to and from your Prefsetting Activity fairly quickly, MainActivity is likely only in a paused or stopped state when it is resumed. Take a look at the diagram here to see what happens to Activity classes as they move into and out of the foreground.
You have a couple of options. Either place this:
#Override
public void onResume() {
super.onResume();
SharedPreferences getprefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean stopshake = getprefs.getBoolean("checkbox", true);
if (stopshake) {
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
public void onShake() {
if (!isFlashOn) {
Toast.makeText(MainActivity.this, "On" , Toast.LENGTH_SHORT).show();
getCamera();
turnOnFlash();
} else {
turnOffFlash();
Toast.makeText(MainActivity.this, "Off" , Toast.LENGTH_SHORT).show();
}
}
});
} else {
if (mShaker != null) {
mShaker.setOnShakeListener(null);
mShaker = null;
}
}
}
Into somewhere like onResume().
Or, use an EventBus like LocalBrodcastManager to update your Preferences when onPause() is called in your PreferenceActivity.
From the code snippet it appears that you never actually commit your changes to the SharedPreferences of the application. Somewhere in the code when that boolean is flipped you need to do something like this:
prefs.put("checkbox", currentBooleanState).commit();

Can't write in inflate layout

I'm using a broadcastreceiver in my DrawerActivity in which i can receive a notification from a service and then i would set the text of notification in a layout that is in a fragment (The first fragment of the navigation drawer). So my DrawerActivity is where i start the broadcastreceiver (i tried start it directly from the fragment but it doesn't work!) So this is the broadcastreceiver:
public BroadcastReceiver onNotice= new BroadcastReceiver() {
LinearLayout notificationLayout;
Drawable icon;
#Override
public void onReceive(Context context, Intent intent) {
final String pack = intent.getStringExtra("package");
String title = intent.getStringExtra("title");
String text = intent.getStringExtra("text");
View myView = getLayoutInflater().inflate(R.layout.activity_main, null);
notificationLayout = (LinearLayout)myView.findViewById(R.id.notificationLayout);
TextView notificationDescription = (TextView) myView.findViewById(R.id.notificationDesc);
TextView notificationTitle = (TextView) myView.findViewById(R.id.notificationTitle);
CircularImageView notificationImage = (CircularImageView) myView.findViewById(R.id.img_thumbnail);
Log.i("Notification ", title);
Toast.makeText(DrawerActivity.this, title, Toast.LENGTH_SHORT).show();
if(!pack.equals("") || !title.equals("") || !text.equals("")) {
notificationLayout.setVisibility(View.VISIBLE);
notificationTitle.setText("Ciao");
notificationDescription.setText(text);
try {
icon = DrawerActivity.this.getPackageManager().getApplicationIcon(pack);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
notificationImage.setImageDrawable(icon);
notificationLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
PackageManager pmi = DrawerActivity.this.getPackageManager();
Intent intent;
intent = pmi.getLaunchIntentForPackage(pack);
if (intent != null) {
DrawerActivity.this.startActivity(intent);
}
//LocalBroadcastManager.getInstance(MainActivity.instance).sendBroadcast(new Intent("collapseAfterClick"));
} catch (Exception ignored) {
}
}
});
notificationLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
notificationLayout.setVisibility(View.INVISIBLE);
return true;
}
});
} else {
notificationLayout.setVisibility(View.INVISIBLE);
}
}
};
in this way it's very strange!!! When a notification arrives the toast inside the Broadcastrecevier is fired but the settext in the inflate layout not! So i can see the notification from the Toast but not in my layout! How is possible?
The issue is the code doesnt enter the if statement.
*if(!pack.equals("") || !title.equals("") || !text.equals(""))*

Categories

Resources