How to put timer in AlertDialog.Builder in android&? - android

I created an AlertDialog. And I need to put a timer there somehow.
Timer must show time from 90 seconds to 0 seconds.
Does someone know how to make that inscription in textView("90 sseconds to acceptance...") change every second with different text? ("90 sseconds to acceptance..." -> "89 sseconds to acceptance..." -> etc..)

Does this work for you?
/*
new CountDownUpdate((TextView)findViewById(R.id.accept_text), 90,
new CountDownUpdate.Callback(){
#Override
public void onCountDownComplete(TextView textView)
{
Toast.makeText(getApplicationContext(), "BOOM!", Toast.LENGTH_LONG).show();
}
});
*/
private static class CountDownUpdate implements Runnable
{
private Callback mCallback;
private int mFrom;
private TextView mView;
public CountDownUpdate(TextView view, int from, Callback callback)
{
mCallback = callback;
mFrom = from;
mView = view;
mView.post(this);
}
#Override
public void run()
{
mView.setText(mFrom + " seconds to acceptance...");
if(mFrom-- == 0){
if(mCallback != null){
mCallback.onCountDownComplete(mView);
}
}
else{
mView.postDelayed(this, 1000);
}
}
public static interface Callback
{
public void onCountDownComplete(TextView textView);
}
}

Related

How to use backbutton to unselect all item in gridview?

i'm using backbutton as interface from activity but it's not working properly for me because on backpress showing 0 size of arraylist
// here is the activity class from where i'm getting backbutton interface..
public class Multiple_Images extends AppCompatActivity {
#Override
public void onBackPressed() {
if(twice ==true){
Intent intent =new Intent(this,MainActivity.class);
startActivity(intent);
}ImageAdapter imageAdapter =new ImageAdapter(this);
imageAdapter.onBackPress();
Toast.makeText(this, "Press twice", Toast.LENGTH_SHORT).show();
twice =true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
twice =false; } }, 2000); }}
//here is the adapter class here i'm using backbutton
public class ImageAdapter extends BaseAdapter implements onBackPressListener {
ArrayList<String> selectedArraylist ;
#Override
public boolean onBackPress() {
selectedArraylist.clear();
Toast.makeText(context, "All values unselected", Toast.LENGTH_SHORT).show();
return true;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
urimodel=new ArrayList<>();
final ImageView imageGrid ;
Activity activity = (Activity) context;
actionMode = activity.startActionMode(new Actionmode());
final GridModel gridModel=(GridModel) this.getItem(i);
if(view==null) {
view = LayoutInflater.from(context).inflate(R.layout.model, null);
selectedArraylist =new ArrayList<>();
}
final CardView cardView= (CardView)view.findViewById(R.id.cardview_image);
imageGrid = (ImageView) view.findViewById(R.id.grid_image);
// gridText = (TextView) view.findViewById(R.id.grid_text);
imageGrid.setScaleType(ImageView.ScaleType.CENTER_CROP);
// imageGrid.setScaleType(ImageView.ScaleType.CENTER_CROP);
Picasso.get().load(gridModel.getImage()).resize(200,200).into(imageGrid);
if (selectedArraylist.contains(gridModel.getImage_text())) {
cardView.setCardBackgroundColor(CARD_SELECTED_COLOR);
}else {
cardView.setCardBackgroundColor(Color.WHITE);
}
return view;
}
}
Simply you can do this inside onBackPressed
#Override
public void onBackPressed() {
if (twice == true) {
super.onBackPressed(); //this backs to the previous activity, if you want to stay with Intent, add finish() after startActivity()
return;
} else {
for (int i = 0; i < list.size(); i++) {
if (gridView.isItemChecked(i)) {
gridView.setItemChecked(i, false);
}
}
//selectedArraylist.clear(); this is clearing your array of selected items
}
twice = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
twice = false;
}
}, 2000);
}
I don't know, why did you put selectedArraylist =new ArrayList<>(); in adapter getView() method. getView() is fired every time, when a new list item is inflated, that mean every time, when you are changing adapters source, scrolling list this method is called, and every time you are initialize you array, and all data inside lost. You should treat an adapter class just like a tool for displaying items, and all actions like above make outside adapter.
pretty much easy,
I give you my own project code, hope it help you.
StudentFragment.java:
private void MultiSelected_Student(int position) {
Student data = adapter_class.getItem(position);
if (data != null) {
if (selectedIds.contains(data)) selectedIds.remove(data);
else selectedIds.add(data);
}
}
private void Remove_MultiSelected() {
try {
selectedIds.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
public void Group_UnSelect() {
Remove_MultiSelected();
MultiSelected = false;
fab.setVisibility(View.GONE);
homeeActivity.studentsMultiSelect = false;
notifyy();
}
private void notifyy() {
adapter_class.notifyDataSetChanged();
}
HomeActivity.java:
public boolean studentsMultiSelect = false;
#Override
public void onBackPressed() {
if (studentsMultiSelect) {
studentFragment.Group_UnSelect();
} else {
super.onBackPressed();
}
}

Android kankan-wheel modification

I am making a slot machine app and using kankan's wheel for the same. I want to modify the library such that when the rotation stops the item it will point shoud be the one that I set . I have done this but there is a glitch that shows that we have changed the actual image to the one that we want . How to achieve this?
Update:
I have researched a lot on this and if I am right , android scroll is based on duration and distance not items . From kankan's wheel library I can get current item .Now , I am trying to stop the animation as well as scroll , as soon as a certain duration has been reached and the item is the one that I want (through index) . But this is not working .Please help!!
GameActivity
public class GameActivity extends Activity {
float mDeviceDensity;
String mUuid, mTitle, mContent, mReward;
ImageButton play;
SlotMachineAdapter slotAdapter;
private List<HashMap<String, Object>> slotImages = new ArrayList<HashMap<String, Object>>();
ArrayList<String> imagesWinId = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filler_up_game);
DisplayMetrics display = getResources().getDisplayMetrics();
mDeviceDensity = display.density;
slotAdapter = new SlotMachineAdapter(this);
getPassedData();
setSoundPlayer(R.raw.clicks,true);
initWheel(R.id.slot_1, false, 0);
initWheel(R.id.slot_2, false, 1);
initWheel(R.id.slot_3, true, 2);
play = (ImageButton) findViewById(R.id.btn_mix);
play.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
shuffle(R.id.slot_1, 5000);
shuffle(R.id.slot_2, 7000);
shuffle(R.id.slot_3, 9000);
}
});
}
protected ImageLoader imageLoader;
ArrayList<SlotItem> arrListSlotItems;
private void getPassedData() {
try {
mUuid = getIntent().getStringExtra(getString(R.string.FILLER_UP_UUID));
imageLoader = ImageLoader.getInstance();
Uuid slotImagesExtra = (Uuid) (getIntent()
.getSerializableExtra(getString(R.string.FILLER_UP_IMAGES)));
arrListSlotItems = slotImagesExtra.getArrSlotItemArray();
for (int i = 0; i < arrListSlotItems.size(); i++)
downloadSlotImages(arrListSlotItems.get(i).getSlotId(), arrListSlotItems.get(i).getImageUrl());
} catch (Exception e) {
e.printStackTrace();
}
}
// Wheel scrolled flag
private boolean wheelScrolled = false;
// Wheel scrolled listener
OnWheelScrollListener scrolledListener = new OnWheelScrollListener() {
public void onScrollingStarted(WheelView wheel) {
wheelScrolled = true;
}
public void onScrollingFinished(WheelView wheel) {
wheelScrolled = false;
setStatus(wheel.getId(), getWheel(wheel.getId()).getWinningIndex());
}
};
// Wheel changed listener
private OnWheelChangedListener changedListener = new OnWheelChangedListener() {
public void onChanged(WheelView wheel, int oldValue, int newValue) {
if (!wheelScrolled) {
}
}
};
/**
* Updates status
*/
private void updateStatus() {
myThread();
}
public void myThread(){
Thread th=new Thread(){
#Override
public void run(){
try
{
Thread.sleep(2000);
GameActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
showAlertDialogWithSingleButton(GameActivity.this, mTitle, mContent, success);
}
});
}catch (InterruptedException e) {
// TODO: handle exception
}
}
};
th.start();
}
android.content.DialogInterface.OnClickListener success = new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (mContent != null && mContent.contains("again"))
startHomeActivity();
else
startNewsActivity();
}
};
private void startHomeActivity() {
}
private void startNewsActivity() {
}
android.content.DialogInterface.OnClickListener fail = new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//
}
};
public void showAlertDialogWithSingleButton(final Activity ctx, final String title, final String message,
DialogInterface.OnClickListener onClickListener) {
// show dialog
}
private void initWheel(int id, boolean monitorScroll, int itemIndex) {
Random randomGenerator = new Random();
int index = randomGenerator.nextInt(arrListSlotItems.size());
WheelView wheel = getWheel(id);
wheel.setViewAdapter(slotAdapter);
wheel.setCurrentItem((index ));
wheel.setVisibleItems(1);
wheel.setWinningIndex(itemIndex);
wheel.addChangingListener(changedListener);
wheel.addScrollingListener(scrolledListener);
wheel.setCyclic(true);
wheel.setEnabled(false);
}
private WheelView getWheel(int id) {
return (WheelView) findViewById(id);
}
private void setStatus(int id, int item) {
int index = 0;
for (int i = 0; i < arrListSlotItems.size(); i++) {
SlotItem d = arrListSlotItems.get(i);
if (d.getSlotId() != 0 && d.getSlotId() == Integer.parseInt(imagesWinId.get(item)))
index = arrListSlotItems.indexOf(d);
}
getWheel(id).setCurrentItem(index, true);
if (id == R.id.slot_3) {
if(player.isPlaying())
{
stopBackgroundAudio();
}
updateStatus();
}
}
private void shuffle(int id, int duration) {
WheelView wheel = getWheel(id);
wheel.scroll(450 + (int) (Math.random() * 50), duration);
}
private class SlotMachineAdapter extends AbstractWheelAdapter {
final int IMAGE_WIDTH = getImageWidth(mDeviceDensity);
final int IMAGE_HEIGHT = getImageHeight(mDeviceDensity);
private Context context;
/**
* Constructor
*/
public SlotMachineAdapter(Context context) {
this.context = context;
}
/**
* Loads image from resources
*/
private Bitmap loadImage(Bitmap bitmap) {
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, IMAGE_WIDTH, IMAGE_HEIGHT, true);
return scaled;
}
#Override
public int getItemsCount() {
return slotImages.size();
}
// Layout params for image view
final LayoutParams params = new LayoutParams(IMAGE_WIDTH, IMAGE_HEIGHT);
#Override
public View getItem(int index, View cachedView, ViewGroup parent) {
ImageView img;
if (cachedView != null) {
img = (ImageView) cachedView;
} else {
img = new ImageView(context);
}
img.setPadding(0, 5, 0, 5);
img.setLayoutParams(params);
#SuppressWarnings("unchecked")
SoftReference<Bitmap> bitmapRef = (SoftReference<Bitmap>) slotImages.get(index).get("image");
Bitmap bitmap = bitmapRef.get();
if (bitmap == null) {
bitmap = loadImage(bitmap);
}
img.setImageBitmap(bitmap);
return img;
}
}
private int getImageWidth(float density) {
}
private int getImageHeight(float density) {
}
private void downloadSlotImages(final int id, String slotObj) {
//downloading slot images from server
}
}
This is the code. Through this code, when slot stops I want it to scroll some more untill it reaches the image position that I receaved from server. I can do this .But this is providing a lil glitch . Is there any way to stop scrolling when the image is reached as soon as certain duration is reached.
P.S. If you need anymore detail I can provide you.
P.P.S. Screenshots wont give you any detailed insight about the issue.
After days of searching I finally did it.All I had to do was set interpolater as LinearInterpolater and While setting setCurrentItem set animation as true.

chronometer in list view gets leaked sometimes

I have a chronometer in my list view. The problem is that sometimes it gets leaked i.e. i can see the OnChronometerTickListener executing every second even after i have navigated to another tab or scrolled the list view item out of view or even pressed the Home button. It seems a waste of resources, since i need it to run only when it is actually visible.
Is there a way to avoid this behaviour? Note that it happens only sometimes.
public class TimerLayout extends LinearLayout {
private static final String LOG_TAG = "TimerLayout";
Button btn_endTimer;
Button btn_cancelTimer;
Chronometer cmt_timer;
Runnable updateTimerThread;
Handler handler;
public TimerLayout(Context context, AttributeSet attrs) {
super(context,attrs);
setOrientation(LinearLayout.VERTICAL);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.timer, this, true);
cmt_timer = (Chronometer) getChildAt(0);
btn_endTimer = (Button) ((ViewGroup) getChildAt(1)).getChildAt(0);
btn_cancelTimer = (Button) ((ViewGroup) getChildAt(1)).getChildAt(1);
btn_endTimer.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view){
cmt_timer.stop();
}
});
btn_cancelTimer.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view){
cmt_timer.stop();
}
});
cmt_timer.setOnChronometerTickListener(new OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer arg0) {
if(BuildConfig.DEBUG){Log.d(LOG_TAG,"onChronometerTick.objectid=" + System.identityHashCode(TimerLayout.this));}
}
});
}
public void init(Date startTime){
cmt_timer.stop();
if(startTime!=null){
Date now = new Date();
long elapsedTime = now.getTime() - startTime.getTime();
cmt_timer.setBase(SystemClock.elapsedRealtime() - elapsedTime);
cmt_timer.start();
}
}
}
I call the init method of this class in the bindView() method of my cursorAdaptor to start it.
The trick is to stop the chronometers in the onPause() of the fragment/activity.
So i create a class to hold the chronometers :
public class ChronometerHolder {
private WeakHashMap<Date, Chronometer> chronometerMap;
private static final String LOG_TAG = "ChronometerHolder";
public ChronometerHolder() {
chronometerMap = new WeakHashMap<Date, Chronometer>();
}
public void add(Date dt_startTime, Chronometer chronometer){
chronometerMap.put(dt_startTime, chronometer);
}
public void remove(Date dt_startTime){
chronometerMap.remove(dt_startTime);
}
public int getCount(){
return chronometerMap.size();
}
public void startAll() {
// start any chronometers that were paused
if (chronometerMap.size() > 0) {
Set<Entry<Date, Chronometer>> set = chronometerMap.entrySet();
Iterator<Entry<Date, Chronometer>> iterator = set.iterator();
Entry<Date, Chronometer> entry;
while (iterator.hasNext()) {
entry = (Entry<Date, Chronometer>) iterator.next();
entry.getValue().start();
}
}
}
}
public void stopAll() {
// stop any chronometers that might be running
if (chronometerMap.size() > 0) {
Set<Entry<Date, Chronometer>> set = chronometerMap.entrySet();
Iterator<Entry<Date, Chronometer>> iterator = set.iterator();
Entry<Date, Chronometer> entry;
while (iterator.hasNext()) {
entry = (Entry<Date, Chronometer>) iterator.next();
entry.getValue().stop();
}
}
}
}
Then i make the below changes :
Return the chronometer object from init() :
public Chronometer init(Date startTime){
Chronometer obj = null;
cmt_timer.stop();
if(startTime!=null){
Date now = new Date();
long elapsedTime = now.getTime() - startTime.getTime();
cmt_timer.setBase(SystemClock.elapsedRealtime() - elapsedTime);
cmt_timer.start();
obj = cmt_timer;
}
return obj;
}
In the fragment, instantiate the holder class :
ChronometerHolder chronometerHolder = new ChronometerHolder();
Every time you initialize the chrononmeter( in the bindView() of the CursorAdapter), add it to the holder :
Chronometer tmpChronometer = viewHolder.myTimer.init(dt_hitSessionStartTime);
if(tmpChronometer != null){
chronometerHolder.add(dt_hitSessionStartTime, tmpChronometer);
}
In onPause(), stop all the chronometers :
chronometerHolder.stopAll();
In onResume(), start all the chronometers :
chronometerHolder.startAll();
When the you press the Home button instead of exiting the app, and then open the app again, the bindView() calls are not executed. That means the chronometers are in a stopped state. So it has to be started in onResume() as done in #5.

How to update a textview in a dialog fragment from an activity?

It may be a silly question but I didn't find a good way to update a dialogfragment's textview from an activity in my android app.
What I'd like to do is to update the textview every second with a counter value and once the time elapsed, a Runnable closes the dialog fragment.
The dialog is closed once the time is elapsed, no problem but I cannot update the textview I want.
Here's my code for the dialog:
public class AlertDialog extends DialogFragment {
private String message = null;
private String title = null;
private ImageView imgV = null;
private TextView msgTv = null;
private TextView counterTv = null;
private Button okBtn = null;
private int imageId = 0;
public static int AUTOMATIC_CLOSE = 100001;
private AlertDialogListener mDialogListener;
public void setImage(int i){
imageId = i;
}
public void setContent(String ttl, String msg){
message = msg;
title = ttl;
}
public boolean hasContent(){
return message != null && title != null;
}
public AlertDialog(){
}
public void performClick(){
okBtn.performClick();
}
public void updateField(String text){
counterTv.setText(text);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dialog, container);
msgTv = (TextView)v.findViewById(R.id.textDialog);
imgV = (ImageView)v.findViewById(R.id.imageDialog);
counterTv = (TextView)v.findViewById(R.id.timeCounterDialog);
if(imageId != 0)
imgV.setImageResource(imageId);
else
imgV.setImageResource(R.drawable.error_icon);
if(hasContent()){
msgTv.setText(message);
getDialog().setTitle(title);
}
else{
getDialog().setTitle("ERROR");
msgTv.setText("An unexcepted error occured");
}
okBtn = (Button)v.findViewById(R.id.validateButton);
okBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mDialogListener != null){
mDialogListener.onFinishedDialog();
}
}
});
return v;
}
#Override
public void onStart() {
mDialogListener.onStartedDialog();
super.onStart();
}
#Override
public void onAttach(Activity activity) {
mDialogListener = (AlertDialogListener) activity;
super.onAttach(activity);
}
#Override
public void onDetach() {
mDialogListener = null;
super.onDetach();
}
public interface AlertDialogListener{
void onStartedDialog();
void onFinishedDialog();
}
}
And this is how I launch it:
class myActivity extends Activity implements AlertDialogListener{
protected void onCreate(Bundle savedInstanceState){
"""some init stuff"""
button.setOnClickListener(new View.OnClickListener() {
showAlertDialog();
}
}
#Override
public void onStartedDialog() {
AutoCloseRunnable mAutoClose = new AutoCloseRunnable();
mHandler.postDelayed(mAutoClose, 1000);
}
#Override
public void onFinishedDialog() {
this.finish();
}
private void showAlertDialog(){
FragmentManager fm = getFragmentManager();
mAlertDialog = new AlertDialog();
mAlertDialog.setContent("No Connection available", "Please enable your internet connection.");
mAlertDialog.setImage(R.drawable.error_icon);
mAlertDialog.show(fm, "fragment_alert");
}
private void updateAlertDialog(String text){
mAlertDialog.updateField(text);
}
private void autoCloseAlertDialog(){
mAlertDialog.performClick();
}
public class AutoCloseRunnable implements Runnable{
#Override
public void run() {
int closeCpt = 10;
while(closeCpt >= 0){
try {
Thread.sleep(1000);
updateAlertDialog("Will close automatically in " + closeCpt + " seconds.");
closeCpt--;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
autoCloseAlertDialog();
}
}
}
Does anyone know how to proceed?
I solved it, simply use asynctask it's easier to handle UI updates like this.

How to save a List from an Adapter to a xml File in Android?

I have developed an app capable of detecting BLE signals and others parameters. I use a BaseAdapter to develop the ListView for showing each item. The problem is that I want to save those data in a xml file when the scan has finished (after a period of time I have established) but I donĀ“t know how to do it.
In this class I do the scan of BLE and is where I want to initiate the process of saving the List when it has passed the time of scanning:
public class ScanBleActivity extends ScanBaseActivity {
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler = new Handler();
//private List<BluetoothDevice> mydata;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 20000;
/* (non-Javadoc)
* #see com.zishao.bletest.ScanBaseActivity#initScanBluetooth()
*/
protected void initScanBluetooth() {
BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = manager.getAdapter();
startScanLen(true);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mScanning) {
startScanLen(false);
}
}
/**
*
* #param enable
*/
private void startScanLen(final boolean enable) {
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
try {
savedata(true);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
And here is my Adapter:
public class LeDeviceListAdapter extends BaseAdapter {
public List<BluetoothDevice> data;
private Activity context;
private final HashMap<BluetoothDevice, Integer> rssiMap = new HashMap<BluetoothDevice, Integer>();
public LeDeviceListAdapter(Activity context, List<BluetoothDevice> data) {
this.data = data;
this.context = context;
}
//public static List<BluetoothDevice> getAllData() {
// return data;
//}
public synchronized void addDevice(BluetoothDevice device, int rssi) {
if(!data.contains(device) ){
data.add(device);
}
rssiMap.put(device, rssi);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (null == convertView) {
LayoutInflater mInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.leaf_devices_list_item, null);
convertView.setTag(new DeviceView(convertView));
}
DeviceView view = (DeviceView) convertView.getTag();
view.init((BluetoothDevice) getItem(position));
return convertView;
}
public class DeviceView {
private TextView title;
private TextView status;
private TextView type;
private TextView address;
private TextView rssivalue;
public DeviceView(View view) {
title = (TextView) view.findViewById(R.id.device_name);
status = (TextView) view.findViewById(R.id.device_status_txt);
type = (TextView) view.findViewById(R.id.device_type_txt);
address = (TextView) view.findViewById(R.id.device_address_txt);
rssivalue = (TextView) view.findViewById(id.signal_intensity_txt);
}
public void init(BluetoothDevice device) {
title.setText(device.getName());
address.setText(device.getAddress());
setType(device.getType());
setStatus(device.getBondState());
rssivalue.setText(""+rssiMap.get(device)+" dBm");
}
public void setType(int status) {
switch(status) {
case BluetoothDevice.DEVICE_TYPE_CLASSIC:
type.setText("Bluetooth Signal");
break;
case BluetoothDevice.DEVICE_TYPE_LE:
type.setText("BLE Signal");
break;
case BluetoothDevice.DEVICE_TYPE_DUAL:
type.setText("Dual Mode - BR/EDR/LE");
break;
case BluetoothDevice.DEVICE_TYPE_UNKNOWN:
type.setText("Device Unknown");
break;
}
}
public void setStatus(int s) {
switch(s) {
case BluetoothDevice.BOND_NONE:
status.setText("Not Bonded");
break;
case BluetoothDevice.BOND_BONDED:
status.setText("Bonded");
break;
case BluetoothDevice.BOND_BONDING:
status.setText("Bonding");
break;
}
}
}
I want to save the title, address, type, status and rssivalue (shown in the code above) of each BLE signal that has been found during the scan to be saved in a xml file. I have provided only a part of the project but if it is necessarly I will edit and put the code that is missing.
Does anyone know how to do it?? Please help!!!!!
New code: This corresponds to the class ScanBaseActivity:
abstract public class ScanBaseActivity extends ListActivity {
protected LeDeviceListAdapter mLeDeviceListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_devices_scan);
mLeDeviceListAdapter = new LeDeviceListAdapter(this, new ArrayList<BluetoothDevice>());
this.setListAdapter(mLeDeviceListAdapter);
initScanBluetooth();
}
/**
* Start Scan Bluetooth
*
*/
abstract protected void initScanBluetooth();
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
BluetoothDevice device = (BluetoothDevice) mLeDeviceListAdapter.getItem(position);
ParcelUuid[] uuids = device.getUuids();
String uuidString = "Getting UUID's from " + device.getName() + ";UUID:";
if (null != uuids && uuids.length > 0) {
uuidString += uuids[0].getUuid().toString();
} else {
uuidString += "empty";
}
Toast.makeText(this, uuidString, Toast.LENGTH_LONG).show();
}
/**
* #param device
*/
protected synchronized void addDevice(final BluetoothDevice device, final int rssi) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLeDeviceListAdapter.addDevice(device, rssi);
mLeDeviceListAdapter.notifyDataSetChanged();
}
});
}
protected void savedata(boolean enable) throws FileNotFoundException{
String filename = "file.txt";
FileOutputStream fos;
Bundle extras = getIntent().getExtras();
long timestamp = extras.getLong("currentTime");
try {
fos= openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.write((int) timestamp);
out.writeObject(mLeDeviceListAdapter);
out.write(null);
out.close();
Toast.makeText(this, R.string.list_saved, Toast.LENGTH_SHORT).show();
savedata(false);
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
}
New!!: I have edited ScanBaseActivity and ScanBleActivity to introduce the xml saving but when I run the app, when the scan stops it causes an error (moment when the list has to be saved in the sml file). Does anyone know how to solve it or correct it??!!!
OK, first, you need to re-shape how you are dealing with your adapter, after that, everything should fall into place.
so for that, I'm going to outsource to vogella, the cardinal of good android design patterns
http://www.vogella.com/tutorials/AndroidListView/article.html
you could read up through section 3, eat some copypasta and come back here, but every extra line you grok is a good thing =]
Now you have an activity that has a list of data, and an adapter that takes that list and--somewhat dumbly in comparison to your code--applies it to a view of some sort. When you want to update that data, you do so by modifying the List object in the activity by your method somewhere that gets a list of Bluetoothdevices--and I'd take that process off thread with an AsyncTask.
Since you are passing a List to the adapter, you can wait until you've populated the data in your activity, then do an adapter.notifyDataSetChanged. You do not want to adapter.add
then you have a nice List of your data in the activity; you don't need to worry if it's the right list, because--given the update pattern--it's the only list!
then follow the link Merleverde posted to serialize that data into an xml, maybe in a utility class, but in your activity is fine.
edit:
here is a perfectly good adapter, this is part of the larger pattern that displays dynamically changing data:
public class AnchorListAdapter extends ArrayAdapter<String>
{
private final List<String> anchorNames;
public AnchorListAdapter(Context context, int textviewId, List<String> anchors){
super(context, textviewId, anchors);
anchorNames = anchors;
}
#Override
public String getItem( int i ) {
return anchorNames.get(i).toString();
}
}
Well, it's not that you are going to be saving it from the adapter, it's that the adater is going to be 'adapting' a data set that you will put into preferences.
as a feild:
private SharedPreferences saveHash;
in onCreate:
saveHash = getSharedPreferences( getString( R.string.save_hash ), MODE_PRIVATE );
then later:
public void onFinishedLoading(){
super.onPause();
SharedPreferences.Editor editor = saveHash.edit();
editor.clear();
for( String s: myData){
editor.putString(x, s);
}
editor.commit();
}
edit: realized you want to make a hash from a list; what do you want as the key?

Categories

Resources