show bluetooth Le devices on baseAdapter - android

I have created an adapter to show the scanned devices in my Custom Dialog. The custom dialog appears but even after none of the devices appears.
Whenever I check the logcat there are devices present from Bluetooth Le Scanner.
The code for the custom dialog is below
public class CustomDialog extends Dialog{
private LeDeviceListAdapter mLeDeviceListAdapter;
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler;
private AppCompatButton Scan;
private AppCompatButton Stop;
Context mContext;
TextView textStatus;
BluetoothLeScanner mLeScanner;
private static final int REQUEST_ENABLE_BT = 1;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 10000;
ProgressBar contentLoadingProgressBar;
public CustomDialog(#NonNull Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_dialog);
contentLoadingProgressBar = (ProgressBar) findViewById(R.id.contentLoading);
contentLoadingProgressBar.setVisibility(View.GONE);
textStatus = findViewById(R.id.textStatus);
textStatus.setVisibility(View.GONE);
Scan = (AppCompatButton) findViewById(R.id.scanButton);
Scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
contentLoadingProgressBar.setVisibility(View.VISIBLE);
Scan.setVisibility(View.GONE);
textStatus.setVisibility(View.VISIBLE);
BlueteethManager.with(getContext()).scanForPeripherals(10000, blueteethDevices -> {
for (BlueteethDevice device : blueteethDevices) {
if (!TextUtils.isEmpty(device.getBluetoothDevice().getName())) {
mLeDeviceListAdapter.addDevice(device);
mLeDeviceListAdapter.notifyDataSetChanged();
Timber.d("%s - %s", device.getName(), device.getMacAddress());
}
}
contentLoadingProgressBar.setVisibility(View.GONE);
textStatus.setVisibility(View.GONE);
Scan.setVisibility(View.VISIBLE);
});
}
});
final BluetoothManager bluetoothManager =
(BluetoothManager) getContext().getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
}
// Adapter for holding devices found through scanning.
private class LeDeviceListAdapter extends BaseAdapter {
private ArrayList<BlueteethDevice> mLeDevices;
private LayoutInflater mInflator;
public LeDeviceListAdapter() {
super();
mLeDevices = new ArrayList<BlueteethDevice>();
mInflator = getLayoutInflater();
}
public void addDevice(BlueteethDevice device) {
if (!mLeDevices.contains(device)) {
mLeDevices.add(device);
}
}
public void clear() {
mLeDevices.clear();
}
#Override
public int getCount() {
return mLeDevices.size();
}
#Override
public Object getItem(int i) {
return mLeDevices.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
CustomDialog.viewHolder viewHolder;
// General ListView optimization code.
if (view == null) {
view = mInflator.inflate(R.layout.custom_dialog, null);
viewHolder = new CustomDialog.viewHolder();
viewHolder.cardDevice=view.findViewById(R.id.cardDevice);
viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
view.setTag(viewHolder);
} else {
viewHolder = (CustomDialog.viewHolder) view.getTag();
}
BlueteethDevice device = mLeDevices.get(i);
final String deviceName = device.getName();
if (deviceName != null && deviceName.length() > 0)
viewHolder.deviceName.setText(deviceName);
else
viewHolder.deviceName.setText("Unknown Device");
viewHolder.deviceAddress.setText(device.getMacAddress());
viewHolder.deviceAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
device.connect(true, isConnected -> {
Timber.d("Is the peripheral connected? %s", Boolean.toString(isConnected));
if (isConnected){
Toast.makeText(mContext, "BLE device Connected", Toast.LENGTH_SHORT).show();
textStatus.setText("Connected");
textStatus.setVisibility(View.VISIBLE);
Scan.setVisibility(View.GONE);
contentLoadingProgressBar.setVisibility(View.GONE);
}
else {
Toast.makeText(mContext, "Failed to connect", Toast.LENGTH_SHORT).show();
}
});
}
});
return view;
}
}
static class viewHolder {
TextView deviceName;
TextView deviceAddress;
CardView cardDevice;
}
}
I am using a third party library for scanning devices. It works correctly though but didn't get any of the device name or address appears on the custom dialog. does the Layout Inflator cause problems to me or what.

Related

RecyclerView messes up when scrolling

I never asked any question before but hope you'll get my point.
I am making a chat app in which I am using a RecyclerView to show messages. The problem is when I scroll the RecyclerView some of the items disappear from the top and the whole items messes up when I try to add a message it doesn't even scroll to bottom nor added in the ListView.
Here is my RecyclerView:
<android.support.v7.widget.RecyclerView
android:id="#+id/conversation_recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:layout_above="#id/typingConversationLayout"
android:layout_below="#id/topLayout_conversation_activity"
android:layout_marginBottom="-5dp"
android:paddingBottom="7dp" />
Initializing and setting the RecycerView:
linearLayoutManager = new LinearLayoutManager(this);
adapter = new ConversationRecyclerViewAdapter();
conversationRecyclerView.setAdapter(adapter);
conversationRecyclerView.setLayoutManager(linearLayoutManager);
linearLayoutManager.setStackFromEnd(true);
conversationRecyclerView.setHasFixedSize(true);
conversationRecyclerView.setNestedScrollingEnabled(false);
Here is my Adapter class:
private class ConversationRecyclerViewAdapter
extends RecyclerView.Adapter<ConversationRecyclerViewAdapter.ConversationViewHolder> {
#NonNull
#Override
public ConversationViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
Log.d(TAG, "onCreateViewHolder: Users Find started");
View conversationsView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.layout_message_received, parent, false);
return new ConversationViewHolder(conversationsView);
}
#Override
public void onBindViewHolder(#NonNull final ConversationViewHolder holderConversation, int i) {
Log.d(TAG, "onBindViewHolder: Users Find started at position is " + i);
final int position = holderConversation.getAdapterPosition();
if (mOwnUser_1.get(position)) {
holderConversation.receivedMsgLayout.setVisibility(View.GONE);
holderConversation.sentProfileImg.setImageResource(mUserProfileImg_2.get(position));
holderConversation.sentMsg.setText(mUserText_3.get(position));
} else {
holderConversation.sentMsgLayout.setVisibility(View.GONE);
holderConversation.receivedProfileImg.setImageResource(mUserProfileImg_2.get(position));
holderConversation.receivedMsg.setText(mUserText_3.get(position));
}
Log.d(TAG, "onBindViewHolder: completed at " + position);
}
#Override
public int getItemCount() {
return mOwnUser_1.size();
}
public class ConversationViewHolder extends RecyclerView.ViewHolder {
RelativeLayout receivedMsgLayout, sentMsgLayout;
EmojiTextView receivedMsg, sentMsg;
CircleImageView receivedProfileImg, sentProfileImg;
public ConversationViewHolder(#NonNull View v) {
super(v);
receivedMsgLayout = v.findViewById(R.id.received_message_layout);
sentMsgLayout = v.findViewById(R.id.sent_message_layout);
receivedMsg = v.findViewById(R.id.received_message_text);
sentMsg = v.findViewById(R.id.sent_message_text);
receivedProfileImg = v.findViewById(R.id.received_message_user__profile_image);
sentProfileImg = v.findViewById(R.id.sent_message_user__profile_image);
}
}
}
Here I am adding data to ListView and displaying to the RecyclerView:
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = editText.getText().toString().trim();
if (TextUtils.isEmpty(msg)) {
editText.setError("Please add a message");
editText.requestFocus();
} else {
Log.d(TAG, "onClick: send Btn ADDED TEXT.. ");
mOwnUser_1.add(user);
mUserProfileImg_2.add(image);
mUserText_3.add(message);
editText.setText("");
editText.requestFocus();
adapter.notifyItemInserted(mOwnUser_1.size());
conversationRecyclerView.scrollToPosition(mOwnUser_1.size() - 1);
}
}
});
I don't know what i am doing wrong but it does not seem to work as i wanted.
Update Code:
The three listviews:
private ArrayList<Boolean> mOwnUser_1 = new ArrayList<>();
private ArrayList<Integer> mUserProfileImg_2 = new ArrayList<>();
private ArrayList<String> mUserText_3 = new ArrayList<>();
And the way of adding data to adapter:
mOwnUser_1.add(true);
mUserProfileImg_2.add(R.drawable.boy);
mUserText_3.add(edittext.getText().toString().trim());
adapter.notifyItemInserted(mOwnUser_1.size());
conversationRecyclerView.scrollToPosition(mOwnUser_1.size() - 1);
My Whole Conversation Activity Class:
public class ConversationActivity extends AppCompatActivity {
private static final String TAG = "ConversationActivity";
private EditText editText;
private LinearLayout linearLayout;
private LinearLayoutManager linearLayoutManager;
private ImageView sendBtn;
private ImageView emojiImage;
private View rootView;
private Boolean popUpShown = false;
private Boolean micShown = false;
private ImageView micBtn;
private RelativeLayout micLayout;
private RecyclerView conversationRecyclerView;
// Array Lists for Find USERS
private ArrayList<Boolean> mOwnUser_1 = new ArrayList<>();
private ArrayList<Integer> mUserProfileImg_2 = new ArrayList<>();
private ArrayList<String> mUserText_3 = new ArrayList<>();
private ConversationRecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: started");
super.onCreate(savedInstanceState);
EmojiManager.install(new TwitterEmojiProvider());
setContentView(R.layout.activity_conversation);
editText = findViewById(R.id.conversationEditText);
linearLayout = findViewById(R.id.optionsOther);
emojiImage = findViewById(R.id.emojiIconOther);
rootView = findViewById(R.id.root_view_conversation);
micBtn = findViewById(R.id.microphoneBtn);
micLayout = findViewById(R.id.microphoneLayout);
conversationRecyclerView = findViewById(R.id.conversation_recyclerView);
sendBtn = findViewById(R.id.sendBtnConversation);
if (!(Build.VERSION.SDK_INT >= 21))
findViewById(R.id.typingConversationLayout).setBackgroundResource(R.drawable.edit_text_conversation_background_below_api);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = editText.getText().toString().trim();
if (TextUtils.isEmpty(msg)) {
editText.setError("Please add a message");
editText.requestFocus();
} else {
Log.d(TAG, "onClick: send Btn ADDED TEXT.. ");
addData(true, R.drawable.boy0, msg);
}
}
});
initConversationArrayList();
}
private void addData(Boolean user, int image, String message) {
mOwnUser_1.add(user);
mUserProfileImg_2.add(image);
mUserText_3.add(message);
editText.setText("");
editText.requestFocus();
adapter.notifyItemInserted(mOwnUser_1.size());
conversationRecyclerView.scrollToPosition(mOwnUser_1.size() - 1);
}
private void initConversationArrayList() {
Log.d(TAG, "initConversationArrayList: created");
mOwnUser_1.add(true);
mUserProfileImg_2.add(R.drawable.boy0);
mUserText_3.add("Hello How are you?");
Log.d(TAG, "initConversationArrayList: completed");
initConversationRecyclerView();
}
private void initConversationRecyclerView() {
Log.d(TAG, "initConversationRecyclerView: started");
linearLayoutManager = new LinearLayoutManager(this);
adapter = new ConversationRecyclerViewAdapter();
conversationRecyclerView.setAdapter(adapter);
conversationRecyclerView.setLayoutManager(linearLayoutManager);
linearLayoutManager.setStackFromEnd(true);
conversationRecyclerView.setHasFixedSize(true);
conversationRecyclerView.setNestedScrollingEnabled(false);
Log.d(TAG, "initConversationRecyclerView: completed");
}
Currently I am also working on chat module, let me show you how am I doing this. I am going to show you in steps.
Step 1: make two separate layout for recyclerview items, one for message that has been sent from your side and one for message received from another side.
Step 2 : make two view holders to populate different layout according to your scenario, made in above step, like this:
public class ChatNewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Chat> chats;
public ChatNewAdapter(List<Chat> chats) {
this.chats = chats;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 0) {
View viewSend = (View) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_message_send, parent, false);
return new ViewHolderSend(viewSend);
} else {
View viewReceive = (View) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_message_received, parent, false);
return new ViewHolderReceive(viewReceive);
}
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case 0:
ViewHolderSend viewHolderSend = (ViewHolderSend) holder;
viewHolderSend.messageSend.setText(chats.get(position).getMessage());
break;
case 1:
ViewHolderReceive viewHolderReceive = (ViewHolderReceive) holder;
viewHolderReceive.messageReceived.setText(chats.get(position).getMessage());
break;
}
}
#Override
public int getItemCount() {
return chats.size();
}
#Override
public int getItemViewType(int position) {
if (chats != null && !chats.get(position).fromAdmin) {
return 0;
} else
return 1;
}
class ViewHolderSend extends RecyclerView.ViewHolder {
TextView messageSend;
public ViewHolderSend(View itemView) {
super(itemView);
messageSend = (TextView) itemView.findViewById(R.id.messageSend);
}
}
class ViewHolderReceive extends RecyclerView.ViewHolder {
TextView messageReceived;
public ViewHolderReceive(View itemView) {
super(itemView);
messageReceived = (TextView) itemView.findViewById(R.id.messageReceived);
}
}
public int addMessages(Chat chat) {
chats.add(chat);
notifyDataSetChanged();
return chats.size();
}
Step 3 : now in your activity:
public class Test extends AppCompatActivity {
RecyclerView chatList;
RecyclerView.LayoutManager mLayoutManager;
ChatNewAdapter adapter;
ImageView sendButton;
EditText messageEditText;
boolean keyboardUp = false;
boolean isRunning = false;
ArrayList<Chat> chats;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
isRunning = true;
setUpComponents();
}
public void setUpComponents() {
chatList = (RecyclerView) findViewById(R.id.chat_list);
chatList.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
chatList.setLayoutManager(mLayoutManager);
messageEditText = (EditText) findViewById(R.id.messageText);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
sendButton = (ImageView) findViewById(R.id.send);
adapter = new ChatNewAdapter(chats);
chatList.setAdapter(adapter);
chatList.scrollToPosition(chatList.getAdapter().getItemCount() - 1);
messageEditText.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (keyboardShown(messageEditText.getRootView())) {
Log.d("keyboard", "keyboard UP");
if (keyboardUp == false) {
if (chats.size() > 0)
chatList.smoothScrollToPosition(chats.size() + 1);
keyboardUp = true;
}
} else {
Log.d("keyboard", "keyboard Down");
keyboardUp = false;
}
}
});
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String message = messageEditText.getText().toString().trim();
if (!message.equals("")) {
Chat chat = new Chat();
String name = message;
chat.setMessage(name);
messageEditText.setText("");
adapter.addMessages(chat);
chatList.scrollToPosition(chatList.getAdapter().getItemCount() - 1);
} else {
Log.d("sending message Error", "error fetching dates");
}
}
});
}
private boolean keyboardShown(View rootView) {
final int softKeyboardHeight = 100;
Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);
DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
int heightDiff = rootView.getBottom() - r.bottom;
return heightDiff > softKeyboardHeight * dm.density;
}
And this is my model class, ignore #PrimaryKey and #Required annotation it just because I am using Realm for local DB. In your case you wont required these annotation.
public class Chat extends RealmObject {
#PrimaryKey
#Required
public Long id;
public boolean fromAdmin;
#Required
public String message;
public int type;
public boolean isRead;
public boolean isSent;
public Date date;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public boolean isFromAdmin() {
return fromAdmin;
}
public void setFromAdmin(boolean fromAdmin) {
this.fromAdmin = fromAdmin;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public boolean isRead() {
return isRead;
}
public void setRead(boolean read) {
isRead = read;
}
public boolean isSent() {
return isSent;
}
public void setSent(boolean sent) {
isSent = sent;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
I hope it will be helpful for you, you can ask further if you want to know anything else related to code.
RecyclerView as the name stands recycles the views. When binding data to a view, you need to ensure you set or reset all views that are touched in the adapter. Messups typically occur when there's data that is set only conditionally for some but not all items.
In particular:
if (mOwnUser_1.get(position)) {
holderConversation.receivedMsgLayout.setVisibility(View.GONE);
holderConversation.sentProfileImg.setImageResource(mUserProfileImg_2.get(position));
holderConversation.sentMsg.setText(mUserText_3.get(position));
} else {
holderConversation.sentMsgLayout.setVisibility(View.GONE);
holderConversation.receivedProfileImg.setImageResource(mUserProfileImg_2.get(position));
holderConversation.receivedMsg.setText(mUserText_3.get(position));
}
Both of these branches will need to reset the other layout back to visible.
Anyway with this kind of two-layout approach you are likely better off by having them as separate view types in your adapter. See How to create RecyclerView with multiple view type?

Deleting all items in a page one by one in Android recyclerview does not load the next set of data

I have implemented recyclerview and it loads 10 tasks at a time. Once every task is completed, I am removing the task with a completed button. It loads the 11th item if I scroll to the bottom at one condition there has to be atleast one uncompleted task present on the page. If I clear all 10 items it just shows me loading animation and nothing happens. I have to close the app and open again to load the tasks again.
I have implemented a PaginationActivity, PaginationAdapter and scroll listener for the page. It loads data from a local database whenever you have reached the end of the page and you have got more tasks to load.
PaginationActivity.java
public class PaginationActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
PaginationAdapter adapter;
LinearLayoutManager linearLayoutManager;
public static ArrayList<String> reasonsdata = new ArrayList<String>();
public static String rslt="";
public static String[] reasons;
public static boolean chk = true;
public static String payTypeSelected;
public static String reasonSelected;
public static HashMap<String, EditText> drivernotesMap = new HashMap<String, EditText>();
public static HashMap<String, EditText> paynoteMap = new HashMap<String, EditText>();
public static HashMap<String, String> paytypeMap = new HashMap<String, String>();
RecyclerView rv;
ProgressBar progressBar;
private static final int PAGE_START = 0;
private boolean isLoading = false;
private boolean isLastPage = false;
private int TOTAL_PAGES;
private int currentPage = PAGE_START;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pagination_main);
fillspinner();
rv = (RecyclerView) findViewById(R.id.main_recycler);
progressBar = (ProgressBar) findViewById(R.id.main_progress);
adapter = new PaginationAdapter(this);
linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
rv.setLayoutManager(linearLayoutManager);
rv.setItemAnimator(new DefaultItemAnimator());
rv.setAdapter(adapter);
rv.addOnScrollListener(new PaginationScrollListener(linearLayoutManager) {
#Override
protected void loadMoreItems() {
isLoading = true;
currentPage += 1;
// mocking network delay for API call
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
loadNextPage();
}
}, 1000);
}
#Override
public int getTotalPageCount() {
return TOTAL_PAGES;
}
#Override
public boolean isLastPage() {
return isLastPage;
}
#Override
public boolean isLoading() {
return isLoading;
}
});
// mocking network delay for API call
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
loadFirstPage();
}
}, 1000);
}
private void fillspinner() {
reasonsdata.clear();
try
{
rslt="START";
CallReasons cr = new CallReasons();
cr.join();
cr.start();
while(rslt=="START") {
try {
Thread.sleep(10);
}catch(Exception ex) {
}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
if(rslt == "Success"){
reasonsdata.add("<--- Select Reason --->");
for(int i =0; i< reasons.length;i++){
reasonsdata.add(reasons[i]);
}
}
}
public void loadFirstPage() {
Log.d(TAG, "loadFirstPage: ");
TOTAL_PAGES = Run.getTotalPages();
//List<Run> runs = Run.createRuns(adapter.getItemCount());
List<Run> runs = Run.createRuns(adapter.getMaxID());
progressBar.setVisibility(View.GONE);
adapter.addAll(runs);
if (currentPage <= TOTAL_PAGES) adapter.addLoadingFooter();
else isLastPage = true;
}
public void loadNextPage() {
Log.d(TAG, "loadNextPage: " + currentPage);
//List<Run> runs = Run.createRuns(adapter.getItemCount());
List<Run> runs = Run.createRuns(adapter.getMaxID());
adapter.removeLoadingFooter();
isLoading = false;
adapter.addAll(runs);
if (currentPage != TOTAL_PAGES) adapter.addLoadingFooter();
else isLastPage = true;
}
}
PaginationAdapter.java
public class PaginationAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int ITEM = 0;
private static final int LOADING = 1;
private List<Run> runs = new ArrayList<>();
private Context context;
private boolean isLoadingAdded = false;
private String cash = "CASH";
private String cheque = "CHEQUE";
SQLiteDatabase db;
//PaginationActivity func_call;
public PaginationAdapter(Context context) {
this.context = context;
runs = new ArrayList<>();
//func_call = new PaginationActivity();
}
public List<Run> getRuns() {
return runs;
}
public void setRuns(List<Run> runs) {
this.runs = runs;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case ITEM:
viewHolder = getViewHolder(parent, inflater);
break;
case LOADING:
View v2 = inflater.inflate(R.layout.item_progress, parent, false);
viewHolder = new LoadingVH(v2);
//viewHolder = getViewHolder(parent, inflater);
//func_call.loadNextPage();
break;
}
return viewHolder;
}
#NonNull
private RecyclerView.ViewHolder getViewHolder(ViewGroup parent, LayoutInflater inflater) {
RecyclerView.ViewHolder viewHolder;
View v1 = inflater.inflate(R.layout.activity_main, parent, false);
viewHolder = new RunVH(v1);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Run run = runs.get(position);
switch (getItemViewType(position)) {
case ITEM:
final RunVH runVH = (RunVH) holder;
//adding text areas to show data
//Completed task button
runVH.btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(context, "Mark as Completed", Toast.LENGTH_LONG).show();
remove(run);
}
}
} catch (Exception ex) {
//pbbar.setVisibility(View.GONE);
ex.printStackTrace();
}
}
});
break;
case LOADING:
break;
}
}
#Override
public int getItemCount() {
return runs == null ? 0 : runs.size();
}
//#Override
public int getMaxID() {
if(runs == null || runs.size() == 0){
return 0;
}else{
Run test = runs.get(runs.size()-2);
int maxid = (int) test.getProperty(0);
return maxid;
}
}
#Override
public int getItemViewType(int position) {
return (position == runs.size() - 1 && isLoadingAdded) ? LOADING : ITEM;
}
public void add(Run run) {
runs.add(run);
notifyItemInserted(runs.size() - 1);
}
public void addAll(List<Run> runList) {
for (Run run : runList) {
add(run);
}
}
public void remove(Run run) {
int position = runs.indexOf(run);
if (position > -1) {
runs.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, runs.size());
}
/*if(runs.size() < 0){
clear();
func_call.loadNextPage();
}*/
}
public void clear() {
isLoadingAdded = false;
while (getItemCount() > 0) {
remove(getItem(0));
}
}
public boolean isEmpty() {
return getItemCount() == 0;
}
public void addLoadingFooter() {
isLoadingAdded = true;
add(new Run());
}
public void removeLoadingFooter() {
isLoadingAdded = false;
int position = runs.size() - 1;
Run item = getItem(position);
if (item != null) {
runs.remove(position);
notifyItemRemoved(position);
}
}
public Run getItem(int position) {
return runs.get(position);
}
protected class RunVH extends RecyclerView.ViewHolder {
private TextView textEsky;
private TextView textAdjusted;
private TextView textAddress;
private TextView textNew;
private TextView textTrusted;
private TextView textName;
private TextView textMobile;
private TextView textHome;
private TextView textWork;
private TextView payType;
private EditText textPayNote;
private EditText textDeliveryInst;
private EditText textDriverNotes;
private final Spinner reasons;
private RadioGroup rg;
private Button btnSave;
private CheckBox IsDriverData;
public RunVH(View itemView) {
super(itemView);
textEsky = (TextView) itemView.findViewById(R.id.idEsky);
textAdjusted = (TextView) itemView.findViewById(R.id.idAdjusted);
textAddress = (TextView) itemView.findViewById(R.id.idAddress);
textNew = (TextView) itemView.findViewById(R.id.idNew);
textTrusted = (TextView) itemView.findViewById(R.id.idTrusted);
textName = (TextView) itemView.findViewById(R.id.idName);
textMobile = (TextView) itemView.findViewById(R.id.idMobile);
textHome = (TextView) itemView.findViewById(R.id.idHome);
textWork = (TextView) itemView.findViewById(R.id.idWork);
payType = (TextView) itemView.findViewById(R.id.idPayType);
textPayNote = (EditText) itemView.findViewById(R.id.idPayNoteText);
textDeliveryInst = (EditText) itemView.findViewById(R.id.idDeliInsText);
textDriverNotes = (EditText) itemView.findViewById(R.id.idDriverNotesText);
IsDriverData = (CheckBox) itemView.findViewById(R.id.idCheckBox);
reasons = (Spinner) itemView.findViewById(R.id.idReason);
rg = (RadioGroup) itemView.findViewById(R.id.Radiogroup);
btnSave = (Button) itemView.findViewById(R.id.button);
}
}
protected class LoadingVH extends RecyclerView.ViewHolder {
public LoadingVH(View itemView) {
super(itemView);
}
}
}
PaginationScrollListener.java
public abstract class PaginationScrollListener extends RecyclerView.OnScrollListener {
LinearLayoutManager layoutManager;
public PaginationScrollListener(LinearLayoutManager layoutManager) {
this.layoutManager = layoutManager;
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visibleItemCount = layoutManager.getChildCount();
int totalItemCount = layoutManager.getItemCount();
int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
if (!isLoading() && !isLastPage()) {
if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
&& firstVisibleItemPosition >= 0) {
loadMoreItems();
}
}
}
protected abstract void loadMoreItems();
public abstract int getTotalPageCount();
public abstract boolean isLastPage();
public abstract boolean isLoading();
}
I could be wrong, but it looks to me like the only time you call loadNextPage() is when the RecyclerView gets a scroll event. Removing ViewHolders doesn't cause scroll events iirc.
If you register an AdapterDataObserver on the PaginationAdapter, you can listen in on removal/add events and trigger loads when there aren't any tasks left. You could probably do the same thing with some small changes to that commented-out code in remove(Run):
if (runs.isEmpty()) {
func_call.loadNextPage();
}
EDIT:
Btw, you see where you called adapter = new PaginationAdapter(this); in the PaginationActivity.onCreate method? The this here is your PaginationActivity, which means you can assign it to a PaginationAdapter field like so:
/**
* #param context the activity this adapter will appear in
*/
public PaginationAdapter(Context context) {
this.context = context;
runs = new ArrayList<>();
func_call = (PaginationActivity)context;
}
That should be enough to prevent crashes. For better separation of concerns, you'll probably want to switch over to AdapterDataObserver-based logic (I think this is called the open/closed principle? Maybe?).

Setting user interface for android BLE scanning project

The app displays the scanned BLE devices. The app screen looks like:
PROBLEM
I want the screen to show a button when the app is opened and below the button should be the text box which will display scanned device.
The code snap is as below:
public class MainActivity extends ListActivity {
private static final String LOG_TAG = "BLEScan";
private LeDeviceListAdapter mLeDeviceListAdapter;
private Handler mHandler;
private boolean mScanning;
private BluetoothAdapter mBluetoothAdapter;
private static final int REQUEST_ENABLE_BT = 1;
private static final long SCAN_PERIOD = 10000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
getActionBar().setTitle(R.string.title_devices);
mHandler = new Handler();
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// Checks if Bluetooth is supported on the device.
if (mBluetoothAdapter == null) {
Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
finish();
return;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
if (!mScanning) {
menu.findItem(R.id.menu_stop).setVisible(false);
menu.findItem(R.id.menu_scan).setVisible(true);
menu.findItem(R.id.menu_refresh).setActionView(null);
} else {
menu.findItem(R.id.menu_stop).setVisible(true);
menu.findItem(R.id.menu_scan).setVisible(false);
menu.findItem(R.id.menu_refresh).setActionView(
R.layout.actionbar_indeterminate_progress);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_scan:
mLeDeviceListAdapter.clear();
scanLeDevice(true);
break;
case R.id.menu_stop:
scanLeDevice(false);
break;
}
return true;
}
#Override
protected void onResume() {
super.onResume();
// Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled,
// fire an intent to display a dialog asking the user to grant permission to enable it.
if (!mBluetoothAdapter.isEnabled()) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
// Initializes list view adapter.
mLeDeviceListAdapter = new LeDeviceListAdapter();
setListAdapter(mLeDeviceListAdapter);
scanLeDevice(true);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// User chose not to enable Bluetooth.
if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
finish();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onPause() {
super.onPause();
scanLeDevice(false);
mLeDeviceListAdapter.clear();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
if (device == null) return;
}
private void scanLeDevice(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);
invalidateOptionsMenu();
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
// int ble_value=TypeManufacturerData.class.;
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
invalidateOptionsMenu();
}
static class ViewHolder {
TextView deviceName;
TextView deviceAd;
TextView deviceRssi;
TextView deviceAddress;
}
class DeviceHolder {
BluetoothDevice device;
String additionalData;
int rssi;
public DeviceHolder(BluetoothDevice device, String additionalData, int rssi) {
this.device = device;
this.additionalData = additionalData;
this.rssi = rssi;
}
}
// Adapter for holding devices found through scanning.
private class LeDeviceListAdapter extends BaseAdapter {
private ArrayList<BluetoothDevice> mLeDevices;
private ArrayList<DeviceHolder> mLeHolders;
private LayoutInflater mInflator;
public LeDeviceListAdapter() {
super();
mLeDevices = new ArrayList<BluetoothDevice>();
mLeHolders = new ArrayList<DeviceHolder>();
mInflator = MainActivity.this.getLayoutInflater();
}
public void addDevice(DeviceHolder deviceHolder) {
if(!mLeDevices.contains(deviceHolder.device)) {
mLeDevices.add(deviceHolder.device);
mLeHolders.add(deviceHolder);
}
}
public BluetoothDevice getDevice(int position) {
return mLeDevices.get(position);
}
public void clear() {
mLeDevices.clear();
mLeHolders.clear();
}
#Override
public int getCount() {
return mLeDevices.size();
}
#Override
public Object getItem(int i) {
return mLeDevices.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
// General ListView optimization code.
if (view == null) {
view = mInflator.inflate(R.layout.listitem_device, null);
viewHolder = new ViewHolder();
viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
viewHolder.deviceAd = (TextView) view.findViewById(R.id.device_ad);
viewHolder.deviceRssi = (TextView) view.findViewById(R.id.device_rssi);
viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
BluetoothDevice device = mLeDevices.get(i);
DeviceHolder deviceHolder = mLeHolders.get(i);
final String deviceName = device.getName();
if (deviceName != null && deviceName.length() > 0)
viewHolder.deviceName.setText(deviceName);
else
viewHolder.deviceName.setText(R.string.unknown_device);
viewHolder.deviceAddress.setText(device.getAddress());
viewHolder.deviceAd.setText(deviceHolder.additionalData);
viewHolder.deviceRssi.setText("rssi: "+Integer.toString(deviceHolder.rssi));
return view;
}
}
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
String deviceName = device.getName();
StringBuffer b = new StringBuffer();
int byteCtr = 0;
for( int i = 0 ; i < scanRecord.length ; ++i ) {
if( byteCtr > 0 )
b.append( " ");
b.append( Integer.toHexString( ((int)scanRecord[i]) & 0xFF));
++byteCtr;
if( byteCtr == 8 ) {
Log.d( LOG_TAG, new String( b ));
byteCtr = 0;
b = new StringBuffer();
}
}
ArrayList<AdElement> ads = AdParser.parseAdData(scanRecord);
StringBuffer sb = new StringBuffer();
for( int i = 0 ; i < ads.size() ; ++i ) {
AdElement e = ads.get(i);
if( i > 0 )
sb.append(" ; ");
sb.append(e.toString());
}
String additionalData = new String( sb );
Log.d(LOG_TAG, "additionalData: "+additionalData);
DeviceHolder deviceHolder = new DeviceHolder(device,additionalData,rssi);
runOnUiThread(new DeviceAddTask( deviceHolder ) );
}
};
class DeviceAddTask implements Runnable {
DeviceHolder deviceHolder;
public DeviceAddTask( DeviceHolder deviceHolder ) {
this.deviceHolder = deviceHolder;
}
public void run() {
mLeDeviceListAdapter.addDevice(deviceHolder);
mLeDeviceListAdapter.notifyDataSetChanged();
}
}
}
The xml layout is:
listitem_device.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#f44336"
>
<TextView android:id="#+id/device_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="24dp"/>
<TextView android:id="#+id/device_ad"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="12dp"/>
<TextView android:id="#+id/device_rssi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="12dp"/>
<TextView android:id="#+id/device_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="12dp"/>
actionbar_indeterminate_progress.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="56dp"
android:minWidth="56dp"
android:background="#f48fb1">
<ProgressBar android:layout_width="32dp"
android:layout_height="32dp"
android:layout_gravity="center"/>

How to send character from android phone to arduino through Bluetooth?

Currently I am using an Arduino nano to receive data and transmit it to android phone through Bluetooth. I want to set some button on my smart phone, and then after I pressed it, it will transmit a character to arduino.
I have tested my arduino that if I give certain command in serial monitor , it will give me the analog read signal.
I wanna ask how can I transmit a character(like "E") from my phone to arduino?
The following code is associated to bluetooth connection. What else can I add to achieve my goal?
Bluetooth code in arduino
public class Homescreen extends Activity {
private Button mBtnSearch;
private Button mBtnConnect;
private ListView mLstDevices;
private BluetoothAdapter mBTAdapter;
private static final int BT_ENABLE_REQUEST = 10; // This is the code we use for BT Enable
private static final int SETTINGS = 20;
private UUID mDeviceUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Standard SPP UUID
// (http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createInsecureRfcommSocketToServiceRecord%28java.util.UUID%29)
private int mBufferSize = 50000; //Default
public static final String DEVICE_EXTRA = "com.blueserial.SOCKET";
public static final String DEVICE_UUID = "com.blueserial.uuid";
private static final String DEVICE_LIST = "com.blueserial.devicelist";
private static final String DEVICE_LIST_SELECTED = "com.blueserial.devicelistselected";
public static final String BUFFER_SIZE = "com.blueserial.buffersize";
private static final String TAG = "BlueTest5-Homescreen";
public String isECG;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homescreen);
ActivityHelper.initialize(this); //This is to ensure that the rotation persists across activities and not just this one
Log.d(TAG, "Created");
Intent i = getIntent();
if (i.hasExtra("isECG")){
isECG = i.getStringExtra("isECG");
}
TextView tv1 = (TextView)findViewById(R.id.tv1);
tv1.setText(isECG);
mBtnSearch = (Button) findViewById(R.id.btnSearch);
mBtnConnect = (Button) findViewById(R.id.btnConnect);
mLstDevices = (ListView) findViewById(R.id.lstDevices);
Button btBack = (Button) findViewById(R.id.btBack);
btBack.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(Homescreen.this, StartScreen.class);
startActivity(intent);
}
});
/*
*Check if there is a savedInstanceState. If yes, that means the onCreate was probably triggered by a configuration change
*like screen rotate etc. If that's the case then populate all the views that are necessary here
*/
if (savedInstanceState != null) {
ArrayList<BluetoothDevice> list = savedInstanceState.getParcelableArrayList(DEVICE_LIST);
if(list!=null){
initList(list);
MyAdapter adapter = (MyAdapter)mLstDevices.getAdapter();
int selectedIndex = savedInstanceState.getInt(DEVICE_LIST_SELECTED);
if(selectedIndex != -1){
adapter.setSelectedIndex(selectedIndex);
mBtnConnect.setEnabled(true);
}
} else {
initList(new ArrayList<BluetoothDevice>());
}
} else {
initList(new ArrayList<BluetoothDevice>());
}
mBtnSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mBTAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBTAdapter == null) {
Toast.makeText(getApplicationContext(), "Bluetooth not found", Toast.LENGTH_SHORT).show();
} else if (!mBTAdapter.isEnabled()) {
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, BT_ENABLE_REQUEST);
} else {
new SearchDevices().execute();
}
}
});
mBtnConnect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
BluetoothDevice device = ((MyAdapter) (mLstDevices.getAdapter())).getSelectedItem();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra(DEVICE_EXTRA, device);
intent.putExtra(DEVICE_UUID, mDeviceUUID.toString());
intent.putExtra(BUFFER_SIZE, mBufferSize);
intent.putExtra("isECG", isECG);
intent.setClass(Homescreen.this, MainActivity.class);
startActivity(intent);
}
});
}
/**
* Called when the screen rotates. If this isn't handled, data already generated is no longer available
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
MyAdapter adapter = (MyAdapter) (mLstDevices.getAdapter());
ArrayList<BluetoothDevice> list = (ArrayList<BluetoothDevice>) adapter.getEntireList();
if (list != null) {
outState.putParcelableArrayList(DEVICE_LIST, list);
int selectedIndex = adapter.selectedIndex;
outState.putInt(DEVICE_LIST_SELECTED, selectedIndex);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case BT_ENABLE_REQUEST:
if (resultCode == RESULT_OK) {
msg("Bluetooth Enabled successfully");
new SearchDevices().execute();
} else {
msg("Bluetooth couldn't be enabled");
}
break;
case SETTINGS: //If the settings have been updated
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String uuid = prefs.getString("prefUuid", "Null");
mDeviceUUID = UUID.fromString(uuid);
Log.d(TAG, "UUID: " + uuid);
String bufSize = prefs.getString("prefTextBuffer", "Null");
mBufferSize = Integer.parseInt(bufSize);
String orientation = prefs.getString("prefOrientation", "Null");
Log.d(TAG, "Orientation: " + orientation);
if (orientation.equals("Landscape")) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else if (orientation.equals("Portrait")) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else if (orientation.equals("Auto")) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
}
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Quick way to call the Toast
* #param str
*/
private void msg(String str) {
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
/**
* Initialize the List adapter
* #param objects
*/
private void initList(List<BluetoothDevice> objects) {
final MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.list_item, R.id.lstContent, objects);
mLstDevices.setAdapter(adapter);
mLstDevices.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapter.setSelectedIndex(position);
mBtnConnect.setEnabled(true);
}
});
}
/**
* Searches for paired devices. Doesn't do a scan! Only devices which are paired through Settings->Bluetooth
* will show up with this. I didn't see any need to re-build the wheel over here
* #author ryder
*
*/
private class SearchDevices extends AsyncTask<Void, Void, List<BluetoothDevice>> {
#Override
protected List<BluetoothDevice> doInBackground(Void... params) {
Set<BluetoothDevice> pairedDevices = mBTAdapter.getBondedDevices();
List<BluetoothDevice> listDevices = new ArrayList<BluetoothDevice>();
for (BluetoothDevice device : pairedDevices) {
listDevices.add(device);
}
return listDevices;
}
#Override
protected void onPostExecute(List<BluetoothDevice> listDevices) {
super.onPostExecute(listDevices);
if (listDevices.size() > 0) {
MyAdapter adapter = (MyAdapter) mLstDevices.getAdapter();
adapter.replaceItems(listDevices);
} else {
msg("No paired devices found, please pair your serial BT device and try again");
}
}
}
/**
* Custom adapter to show the current devices in the list. This is a bit of an overkill for this
* project, but I figured it would be good learning
* Most of the code is lifted from somewhere but I can't find the link anymore
* #author ryder
*
*/
private class MyAdapter extends ArrayAdapter<BluetoothDevice> {
private int selectedIndex;
private Context context;
private int selectedColor = Color.parseColor("#abcdef");
private List<BluetoothDevice> myList;
public MyAdapter(Context ctx, int resource, int textViewResourceId, List<BluetoothDevice> objects) {
super(ctx, resource, textViewResourceId, objects);
context = ctx;
myList = objects;
selectedIndex = -1;
}
public void setSelectedIndex(int position) {
selectedIndex = position;
notifyDataSetChanged();
}
public BluetoothDevice getSelectedItem() {
return myList.get(selectedIndex);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public BluetoothDevice getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView tv;
}
public void replaceItems(List<BluetoothDevice> list) {
myList = list;
notifyDataSetChanged();
}
public List<BluetoothDevice> getEntireList() {
return myList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if (convertView == null) {
vi = LayoutInflater.from(context).inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.tv = (TextView) vi.findViewById(R.id.lstContent);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if (selectedIndex != -1 && position == selectedIndex) {
holder.tv.setBackgroundColor(selectedColor);
} else {
holder.tv.setBackgroundColor(Color.WHITE);
}
BluetoothDevice device = myList.get(position);
holder.tv.setText(device.getName() + "\n " + device.getAddress());
return vi;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.homescreen, menu);
return true;
}
}
in my android code I have these global variables:
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
And then I get my paired bluetooth devices in a similar way to what you did:
#Override
protected List<BluetoothDevice> doInBackground(Void... params) {
Set<BluetoothDevice> pairedDevices = mBTAdapter.getBondedDevices();
List<BluetoothDevice> listDevices = new ArrayList<BluetoothDevice>();
for (BluetoothDevice device : pairedDevices) {
listDevices.add(device);
}
return listDevices;
}
Then when I select the correct bluetooth device, I set it equal to mmDevice:
mmDevice = device;
Then I use this method to open a bluetooth connection:
void openBT() throws IOException{
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
//Optional
System.out.println("Bluetooth Opened");
Toast.makeText(getApplicationContext(), "Bluetooth Opened", Toast.LENGTH_SHORT).show();
}
The mmOutputStream sends data to the bluetooth module and the mmInputStream reads the incoming data from the bluetooth module. I have this method to send data to the bluetooth module:
void sendData(String m) throws IOException{
String msg = m;
mmOutputStream.write(msg.getBytes());
System.out.println("Data Sent");
}
This converts a string to bytes and sends it to the Arduino. On the Arduino side, you can either say
if(bluetooth.available())
{
char c = bluetooth.read();
Serial.println(c);
}
If you are just reading a single char or say:
if(bluetooth.available())
{
int data = bluetooth.parseInt();
Serial.println(data);
}
To read an integer value that you sent over bluetooth. Hope this helps. If you need anything, don't hesitate to ask.

How to save a ListView into a xml file in Android?

I am developing an android app capable of detecting BLE signals and list them in a ListView. After an Scan period of time it will stop scanning. Here is the code (it is the same as in the developers page):
ScanBleActivity.class (extends from ScanBaseActivty):
public class ScanBleActivity extends ScanBaseActivity {
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler = new Handler();
// 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);
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
addDevice(device, rssi);
}
};
AddDevice is implemented in other class, in this case ScanBaseActivity:
ScanBaseActivity (which extends from ListActivity):
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();
}
});
}
}
All the information I detect (name, address, rssi, etc) is listed in a Listview. For the ListView I have implemented an Adapter called BaseAdapter. Part of the code of the Adapter is the following:
public class LeDeviceListAdapter extends BaseAdapter {
private 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 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), null);
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);
}
When the scan finishes I would like to save the ListView into a file (if it is possible into a xml file) but I donĀ“t know where and what code I should use in the project to save it. It would be imortant also to use a timestamp in the file to know when it was saved. Can anyone help me or give me any clues??
New: Code Edited to show All code from ScanBaseActivity and ScanBleActivity!!!
I see one problem with your constructor.
public LeDeviceListAdapter(Activity context, List<BluetoothDevice> data) {
//EDIT::
//add the following line
super(context, R.layout.leaf_devices_list_item, data);
this.data = data;
this.context = context;
}
Calling the super constructor passes the reference of data to the BaseAdapter. Then, BaseAdapter will be able to handle any changes in the list.
I am going to make a couple of assumptions here, so correct me if I am wrong.
You have access to your Adapter from the class that is scanning for the devices. I assume this is how you are adding devices to the adapter using add device. You could make a call from here to the adapter when scanning completes to get the List of devices you have stored, by creating a public method on the Adapter which returns a BluetoothDevice List.
The second option you have is to just create the xml file you want in the adapter whenever you add a device to the list. There should not be many devices around, so you should have a fairly small number of read writes. Writing to an xml file should follow the procedure in this answer.
Android creating and writing xml to file
(edit)
You would be looking at something like:
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
//Add the call here to save the file
// You should be able to access the list adapter from your base class
// that will give you the devices
}
}, SCAN_PERIOD);

Categories

Resources