how to add a Custom adapter to listview in android - android

This is my code to scan a near by bluetooth device but when i add a custom adapter to it it throwing an error..
public class MainActivity extends Activity {
ListView listDevicesFound;
Button btnScanDevice;
BluetoothAdapter bluetoothAdapter;
int REQUEST_CODE = 1;
MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnScanDevice = (Button)findViewById(R.id.scan);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
listDevicesFound = (ListView)findViewById(R.id.list);
listDevicesFound.setAdapter(adapter);
CheckBlueToothState();
btnScanDevice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
adapter.clear();
if(bluetoothAdapter.startDiscovery())
{
Toast.makeText(getBaseContext(),"Scanning", Toast.LENGTH_LONG).show();
}
}
});
registerReceiver(ActionFoundReceiver,new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
#Override
protected void onDestroy() {
super.onDestroy();unregisterReceiver(ActionFoundReceiver);
}
private void CheckBlueToothState()
{
if (bluetoothAdapter == null)
{
Toast.makeText(getBaseContext(),"Bluetooth Not Supported",Toast.LENGTH_LONG).show();
}
else
{
if (bluetoothAdapter.isEnabled())
{
if(bluetoothAdapter.isDiscovering())
{
Toast.makeText(getBaseContext(),"Bluetooth is currently in device discover process",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getBaseContext(),"Bluetooth is Enabled",Toast.LENGTH_LONG).show();
btnScanDevice.setEnabled(true);
}
}
else
{
Toast.makeText(getBaseContext(), "Bluetooth is not Enabled", Toast.LENGTH_LONG).show();
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_CODE);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE)
{
CheckBlueToothState();
}
}
private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
adapter.add(device.getName() + "\n" + device.getAddress());
adapter.notifyDataSetChanged();
}
}};
}
Custom adapter
public class MyAdapter extends ArrayAdapter<BlueDevices>
{
Context context;
int resources;
ArrayList<BlueDevices> Devices = null;
public MyAdapter(Context context, int resource,ArrayList<BlueDevices> Devices) {
super(context, resource, Devices);
this.context=context;
this.resources=resource;
this.Devices=Devices;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = new TextView(getContext());
BlueDevices item = getItem(position);
textView.setTextColor(Color.BLACK);
textView.setText(item.Name+" : "+item.Mac +" date :"+item.getDateFormatted());
return textView;
}
public List<BlueDevices> getAllItem() {
List<BlueDevices> result = new ArrayList<>();
for (int i = 0; i < getCount(); i++) {
Log.e("fef", "getAllItem: " );
result.add(getItem(i));
}
return result;
}
}
BlueDevice:
public class BlueDevices {
public String Name;
public String Mac;
public Date date;
public BlueDevices(String Name)
{
this.Name=Name;
this.Mac=Mac;
this.date=date;
}
private SimpleDateFormat format = new SimpleDateFormat("dd MMMM yyyy");
public String getDateFormatted() {
if (date == null){
return " no date ";
}
return format.format(date);
}
}
this line throwing an error adapter.add(device.getName() + "\n" + device.getAddress());

There are many problems in your code.
Change in Bean file BlueDevices
change constructor to take two arguments.
public BlueDevices(String Name, String Mac)
{
this.Name=Name;
this.Mac=Mac;
}
you no need to set data because you already created method to get data.
change in onCreate method in activity class
In your adapter class constructor take three arguments.
MyAdapter(Context context, int resource,ArrayList<BlueDevices> Devices);
so you have context that get from getApplicationContext(), resource is your layout and Devices is arraylist of your bean class. for that you have to create one layout in your res/layout and one ArrayList with bean typecase.
ArrayList<BlueDevices> list = new ArrayList<>();
add your all devices in to this list using.
list.add(new BlueDevices("Device1","ASDF234SDFSADF"));
list.add(new BlueDevices("Device2","GSDFG34SAF32DF"));
Now create object of adapter class
MyAdapter adapter = new MyAdapter(getApplicationContext(),R.layout.list_items,list);
set this adapter to your ListView using
listview.setAdapter(adapter);
Now create method in adapter class
public BlueDevices getDevices(int position) {return Devices.get(position);}
Add getter method in BlueDevices
public String getName(){
return Name;
}
public String getMac(){
return Mac;
}
Get devices list from adapter in list onItemClickListener
BlueDevices bean = adapter.getDevices(position);
String name = bean.getName();
String mac = bean.getMac();

Related

Android - Adding objects to a list view from another activity

I've got a custom list view with my own adapter. I can add objects to this list within the same activity, but what I want to do is add objects from another activity. In this other activity there are two Edit Text boxes. One is responsible for Main text, second for Description, and two radio buttons that are determining image. At the bottom is Add button, that should add entered data to the list view.
I tried to do this with Parcelable, but I don't know exactly how to implement it. Below is my ListView class:
public class Activity_4 extends AppCompatActivity {
private ListView listView;
private myAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_4);
listView = (ListView)findViewById(R.id.listView4);
ArrayList<Object> objectList = new ArrayList<>();
objectList.add(new Object(R.drawable.row_img, "After Earth" , "2013"));
objectList.add(new Object(R.drawable.row_img, "After Earth" , "2013"));
objectList.add(new Object(R.drawable.row_img, "After Earth" , "2013"));
objectList.add(new Object(R.drawable.row_img, "After Earth" , "2013"));
objectList.add(new Object(R.drawable.row_img, "After Earth" , "2013"));
objectList.add(new Object(R.drawable.row_img, "After Earth" , "2013"));
mAdapter = new myAdapter(this,objectList);
listView.setAdapter(mAdapter);
}
public class Object implements Parcelable {
int imageID;
String mainText;
String description;
public Object (int imageID, String mainText, String description) {
this.imageID = imageID;
this.mainText = mainText;
this.description = description;
}
public Object() {
}
public int getImageID() {
return imageID;
}
public void setImageID(int imageID) {
this.imageID = imageID;
}
public String getMainText () {
return mainText;
}
public void setMainText() {
this.mainText = mainText;
}
public String getDescription() {
return description;
}
public void setDescription() {
this.description = description;
}
public Object(Parcel in) {
this.imageID = in.readInt();
this.mainText = in.readString();
this.description = in.readString();
}
public final Parcelable.Creator<Object> CREATOR = new Parcelable.Creator<Object>() {
#Override
public Object createFromParcel(Parcel in) {
return new Object(in);
}
#Override
public Object[] newArray(int size) {
return new Object[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(imageID);
dest.writeString(mainText);
dest.writeString(description);
}
}
public class myAdapter extends ArrayAdapter<Object> {
private Context mContext;
private List<Object> objectList = new ArrayList<>();
public myAdapter(#NonNull Context context, ArrayList<Object> list) {
super(context,0,list);
mContext = context;
objectList = list;
}
#NonNull
#Override
public View getView (int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItem = convertView;
if (listItem == null)
listItem = LayoutInflater.from(mContext).inflate(R.layout.list_row, parent, false);
Object currentObject = objectList.get(position);
ImageView image = (ImageView) listItem.findViewById(R.id.row_image);
image.setImageResource(currentObject.getImageID());
TextView mainTxt = (TextView) listItem.findViewById(R.id.row_tv1);
mainTxt.setText(currentObject.getMainText());
TextView description = (TextView) listItem.findViewById(R.id.row_tv2);
description.setText(currentObject.getDescription());
return listItem;
}
}
Can anyone help with this problem?
Thanks
You can other Activity using startActivityForResult() and pass data in bundle as result on click of add button from other Activity, so current activity will add the data to it's list.
Calling Other Activity to add
startActivityForResult(intent,reqCode);
On Result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null && requestCode == reqCode) {
Object object = new Object();
object.setImageID(data.getIntExtra("image_id"));
object.setMainText(data.getStringExtra("main_text");
object.setDescription(data.getStringExtra("desc");
objectlist.add(object);
mAdapter.notifyDataSetChanged();
}
}
Other Activity
public void onAddClick(){
Intent intent = new Intent();
intent.putIntExtra("image_id",*<value>*);
intent.putStringExtra("main_text",*<value>*);
intent.putStringExtra("desc",*<value>*);
setResult(intent);
finish();
}
A good starting point might be to start your EditText activity using startActivityForResult and pass the updates to the list to your adapter through the result, after you added everything you wanted by calling setResult with your new data. For further reference see Getting a Result from an Activity. Good luck!
When opening 2nd Activity from 1st Activity
do
Intent mIntent=new Intent(this,YourSecondActivity.class);
startActivityForResult(mIntent,SOME_STATIC_INT)
In another activity
on click of AddButton
Intent mIntent=new Intent(this,YourFirstActivity.class);
mIntent.putExtra("DATA",Object)
setResult(SOME_STATIC_INT,mIntent)
now in 1st Activity
Override onActivity Result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null && requestCode == SOME_STATIC_INT) {
Object object = data.getParcelableExtra("DATA")
objectlist.add(object);
mAdapter.notifyDataSetChanged();
}
}

Transferring data into a separate ArrayList and displaying in RecyclerView

I have two ArrayLists from which I am trying to insert data into separate static ArrayList in another class and display in RecyclerView, but the recycler is not getting populated though the same was being done with a dummy ArrayList.Please help me with this problem.
My Class where I am inserting data from phoneContactNos and phoneContactName in two separate ArrayList: Common.selectedContactNos and Common.selectedContactName.
public void displayMatchedContacts()
{
try {
for (int i = 1; i < phoneContactNos.size(); i++) {
if (phoneContactNos.contains(registeredContactNos.get(i))) {
if (registeredContactNos.get(i) != null) {
try {
indexOfRegNumber = phoneContactNos.indexOf(registeredContactNos.get(i));
//Common.indexPosition_contacts=indexOfRegNumber;
Toast.makeText(this, "index" + String.valueOf(indexOfRegNumber), Toast.LENGTH_LONG).show();
if ((phoneContactNos.get(indexOfRegNumber) != null) &&(phoneContactName.get(indexOfRegNumber) != null)) {
//String regName="";
//String regContact="";
Common.selectedContactNos.add(phoneContactNos.get(indexOfRegNumber));
//Toast.makeText(this,selectedContactNos.get(i).toString(),Toast.LENGTH_SHORT).show();
//Toast.makeText(this,phoneContactNos.get(indexOfRegNumber).toString(),Toast.LENGTH_SHORT).show();
Common.selectedContactName.add(phoneContactName.get(indexOfRegNumber));
//Toast.makeText(this,selectedContactName.get(i).toString(),Toast.LENGTH_SHORT).show();
//Toast.makeText(this, phoneContactName.get(indexOfRegNumber).toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "null index no", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.i("Contacts display error", e.getLocalizedMessage());
e.printStackTrace();
}
}
}
}
}catch (Exception e)
{
Log.i("Contacts error in loop", e.getLocalizedMessage());
e.printStackTrace();
}
}
My Common class
public final class Common {
public static ArrayList<String> selectedContactNos=new ArrayList<>();
public static ArrayList<String> selectedContactName=new ArrayList<>();
public static String fcmId="";
public static int position;
public static String contacts_list="";
public static int indexPosition_contacts;
}
My RecyclerView populating code
public void populateList() {
Log.i("Populate List","Entered");
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this);
recyclerView_contacts.setLayoutManager(mLinearLayoutManager);
displayRecyclerAdapter = new DisplayRecyclerAdapter(this);
recyclerView_contacts.setAdapter(displayRecyclerAdapter);
}
My Adapter Class
public class DisplayRecyclerAdapter extends RecyclerView.Adapter<DisplayRecyclerAdapter.displayViewHolder> {
private LayoutInflater mInflater;
private Context context;
Fragment fragment;
FragmentTransaction ft;
FrameLayout container;
public DisplayContacts displayContacts;
public DisplayRecyclerAdapter(Context context) {
this.mInflater = LayoutInflater.from(context);
this.context = context;
ft = ((AppCompatActivity) context).getSupportFragmentManager().beginTransaction();
//displayContacts = new DisplayContacts();
}
#Override
public displayViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.contacts_row, parent, false);
displayViewHolder holder = new displayViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(displayViewHolder holder, int position) {
holder.setData(position);
//Common.position = position;
holder.setListeners();
//for(int i=0;i<((DisplayContacts)context).selectedContactName.size();i++)
for(int i=0;i<Common.selectedContactName.size();i++)
{
//String contactName=((DisplayContacts)context).selectedContactName.get(i);
String contactName=Common.selectedContactName.get(i);
//String contactNumber=((DisplayContacts)context).selectedContactNos.get(i);
String contactNumber=Common.selectedContactNos.get(i);
Toast.makeText(context,contactName+","+contactNumber,Toast.LENGTH_SHORT).show();
}
}
class displayViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
int position;
//ImageView productSearchImg;
TextView name_contactList;
Button call_contact;
public displayViewHolder(View itemView) {
super(itemView);
name_contactList = (TextView) itemView.findViewById(R.id.contactlist_name);
call_contact = (Button) itemView.findViewById(R.id.contactlist_call);
}
public void setData(int position) {
this.position = position;
//String displayContacts=((DisplayContacts) context).selectedContactName.get(position);
String displayContacts=Common.selectedContactName.get(position);
Toast.makeText(context,"name to display"+ displayContacts,Toast.LENGTH_SHORT).show();
//name_contactList.setText(((DisplayContacts) context).selectedContactName.get(position));
//name_contactList.setText(displayContacts);
name_contactList.setText("dummy text");
}
#Override
public void onClick(View v) {
//sendPushNotification();
startAudioCall();
}
public void setListeners() {
call_contact.setOnClickListener(displayViewHolder.this);
}
}
public void startAudioCall() {
Intent i = new Intent(context, AudioCallActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
#Override
public int getItemCount() {
return ((DisplayContacts) context).selectedContactName.size();
}
}
can be one of two things:
1.you are not attaching the adapter with data,hence empty
2.or you are updating your data but not calling notifyDataSetChanged()
try to pass the list data in your Adapter class while you are creating it,then attach it to the recyelerview.
//to give a vary basic example
List dataList;
RvAdapter(Context c,List data){
this.dataList=data;
}
onBidViewHolder(Viewholder holder,int position){
holder.tvName.setText(dataList.get(position).getName());
.......
}
//in your activity/fragment
RvAdapter adapter=new RavAdapter(context,dataList);
recylerview.setAdapter(adapter);
//if you change your data
adapter.notifyDataSetChanged()

Not able to populate the data in my recyclerview.!

This is my Adapter class:
public class ItemsAdapter extends RecyclerView.Adapter<ItemsAdapter.RecyclerViewHolder> {
ArrayList<Item> arrayList=new ArrayList<>();
public ItemsAdapter(ArrayList<Item> arrayList, Context context) {
this.arrayList = arrayList;
this.context = context;
}
Context context;
public void update(ArrayList<Item> items)
{
this.arrayList=items;
this.notifyDataSetChanged();
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=LayoutInflater.from(context).inflate(R.layout.displays_searchitems,parent,false);
RecyclerViewHolder recyclerViewHolder=new RecyclerViewHolder(view);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
Item item=arrayList.get(position);
holder.ets_ean1.setText(item.getItem_ean());
holder.ets_company.setText(item.getItem_company());
holder.ets_name.setText(item.getItem_name());
holder.ets_desc.setText(item.getItem_desc());
holder.ets_brand.setText(item.getItem_brand());
}
#Override
public int getItemCount() {
return arrayList.size();
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder{
EditText ets_company,ets_name,ets_desc,ets_brand,ets_ean1;
public RecyclerViewHolder(View view) {
super(view);
ets_company= (EditText) view.findViewById(R.id.ets_company);
ets_name=(EditText) view.findViewById(R.id.ets_name);
ets_desc=(EditText) view.findViewById(R.id.ets_desc);
ets_brand=(EditText) view.findViewById(R.id.ets_brand);
ets_ean1=(EditText) view.findViewById(R.id.ets_ean1);
}
}
My POJO class:
public class Item {
private int item_number;
private String item_ean;
private String item_desc;
private String item_name;
private String item_company;
private String item_brand;
public Item(int item_number, String item_ean, String item_desc, String item_name, String item_company, String item_brand) {
this.item_number = item_number;
this.item_ean = item_ean;
this.item_desc = item_desc;
this.item_name = item_name;
this.item_company = item_company;
this.item_brand = item_brand;
}
public Item() {
}
public int getItem_number() {
return item_number;
}
public void setItem_number(int item_number) {
this.item_number = item_number;
}
public String getItem_ean() {
return item_ean;
}
public void setItem_ean(String item_ean) {
this.item_ean = item_ean;
}
public String getItem_desc() {
return item_desc;
}
public void setItem_desc(String item_desc) {
this.item_desc = item_desc;
}
public String getItem_name() {
return item_name;
}
public void setItem_name(String item_name) {
this.item_name = item_name;
}
public String getItem_company() {
return item_company;
}
public void setItem_company(String item_company) {
this.item_company = item_company;
}
public String getItem_brand() {
return item_brand;
}
public void setItem_brand(String item_brand) {
this.item_brand = item_brand;
}
Activity class:
public class Search extends Activity {
TextView textView;
EditText editText,editText1;
ToggleButton toggleButton;
private DBController dbcontroller;
private SQLiteDatabase database;
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
private static final int CAMERA_PHOTO = 111;
private ImageView ImgPhoto;
private Uri imagaeToUploadUri;
ArrayList<HashMap<String, String>> selected = new ArrayList<>();
ArrayList<HashMap<String, String>> pselected = new ArrayList<>();
private ArrayList<Item> arrayList=new ArrayList<>();
ItemsAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
editText = (EditText) findViewById(R.id.et_sdata);
textView = (TextView) findViewById(R.id.textView);
dbcontroller = new DBController(this);
textView = (TextView) findViewById(R.id.txt_message);
toggleButton = (ToggleButton) findViewById(R.id.tggl_btn);
ImgPhoto = (ImageView) findViewById(R.id.imageView);
editText1 = (EditText) findViewById(R.id.ets_ean1);
recyclerView= (RecyclerView) findViewById(R.id.customList);
adapter=new ItemsAdapter(arrayList,this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
#Override
protected void onResume() {
super.onResume();
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String string = s.toString();
if (string.length() > 0 && string.charAt(string.length() - 1) == '\n') {
displayItems();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void displayItems() {
String s2 = editText.getText().toString();
ArrayList<HashMap<String, String>> allItems = dbcontroller.searchdata(s2);
//ArrayList<HashMap<String, String>> predicted = dbcontroller.getpdata(s4);
ArrayList<Item> itemList=new ArrayList<Item>();
s2 = s2.replace("\\n", "").replace("\n", "");
long ean_num=Long.parseLong(s2.trim());
Item item=new Item();
if (allItems.size() == 0) {
allItems = dbcontroller.getpdata(s2);
for (HashMap<String, String> map : allItems)
{
long ean_num_pred = Long.parseLong(map.get("EAN"));
selected=pselected;
selected.add(map);
item.setItem_ean(map.get("item_ean"));
item.setItem_company(map.get("item_company"));
item.setItem_name(map.get("item_name"));
item.setItem_brand(map.get("item_brand"));
item.setItem_desc(map.get("item_desc"));
itemList.add(item);
Log.d("Cpredictor","Items are"+item);
boolean isInserted = dbcontroller.insertReport(editText.getText().toString(), "2");
Log.d("coredictor", "the value is " + ean_num);
Log.d("coredictor", "the predicted value is " + ean_num_pred);
textView.setText("(S)"+s2+"(P)"+map.get("item_ean"));
textView.setTextColor(Color.GREEN);
editText.setText("");
if (isInserted = true)
{
Toast.makeText(Search.this, "Data inserted", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(Search.this, "Data not inserted", Toast.LENGTH_LONG).show();
}
toggleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (((ToggleButton) v).isChecked()) {
boolean isUpdated = dbcontroller.updatePrediction(editText.getText().toString(), "4");
Toast.makeText(getBaseContext(), "Toggle is on" + isUpdated, Toast.LENGTH_LONG).show();
editText.setText("");
} else {
boolean isUpdated = dbcontroller.updatePrediction(editText.getText().toString(), "3");
Toast.makeText(getBaseContext(), "Toggle is off", Toast.LENGTH_LONG).show();
editText.setText("");
}
}
});
}
} else {
for (HashMap<String, String> map : allItems)
{
if (map.get("EAN").equals(s2))
{
item=new Item();
item.setItem_ean(map.get("item_ean"));
item.setItem_company(map.get("item_company"));
item.setItem_name(map.get("item_name"));
item.setItem_brand(map.get("item_brand"));
item.setItem_desc(map.get("item_desc"));
itemList.add(item);
boolean isInserted = dbcontroller.insertReport(editText.getText().toString(), "1");
selected=pselected;
selected.add(map);
textView.setText("ITEM FOUND!!!!!");
textView.setTextColor(Color.BLUE);
editText.setText("");
if (isInserted = true)
Toast.makeText(Search.this, "Data inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(Search.this, "Data not inserted", Toast.LENGTH_LONG).show();
}
}
}
adapter.update(itemList);
//ListAdapter adapter = new SimpleAdapter(Search.this,selected,R.layout.displays_searchitems, new String[]{"EAN", "COMPANY", "NAME", "DESCRIPTION", "BRAND"}, new int[]{
// R.id.ets_ean1, R.id.ets_company, R.id.ets_name, R.id.ets_desc, R.id.ets_brand});
//tomList.setAdapter(adapter);
}
I'm trying to display the data from the database(sqlite).
The logic is working fine. I've put log and i can see it's showing the perfect data. But i dont know why the data is not displayed in my recyclerview.
Guys i need help.
Replace
adapter.update(itemList);
with
arrayList.clear();
arrayList.addAll(itemList);
adapter.notifyDataSetChanged()
inside displaysItem method.
Granular updates is better than Calling notifyDatasetchanged().Be specific and use notifyitem inserted.
public void addItems(List<T> Items)
{
for(T object:Items)
{
add(object);
}
}
public void add(final T object) {
arrayList.add(object);
notifyItemInserted(getItemCount() - 1);
}
#Override
public int getItemCount() {
return arrayList== null ? 0 : arrayList.size();
}

How to pass values from RecycleAdapter to MainActivity or Other Activities

I am working on a shopping cart app,Items are displayed as below.There is a plus, minus (+/-) buttons to choose the number of quantity.
If product quantity is changed, I need to pass "productname" and "quantity" to the main activity so that I could use them to prepare final cart. I got some suggestions to use database or some content providers,
I am not sure how to do it.., please help
MainActivity.java
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecycleAdapter recycleAdapter;
List<HashMap<String, String>> onlineData;
ProgressDialog pd;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyle_view);
toolbar= (Toolbar) findViewById(R.id.anim_toolbar);
setSupportActionBar(toolbar);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getBaseContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
final String url = "http://www.qa4.org/?json=get_recent_posts&count=45";
new AsyncHttpTask().execute(url);
}
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
pd=new ProgressDialog(MainActivity.this);
pd.requestWindowFeature(Window.FEATURE_NO_TITLE);
pd.setMessage("Loading please wait...");
pd.setCancelable(false);
pd.show();
}
#Override
protected Integer doInBackground(String... params) {
Integer result = 0;
HttpURLConnection urlConnection;
try {
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
// 200 represents HTTP OK
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
} else {
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
e.printStackTrace();
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result) {
// Download complete. Let us update UI
pd.dismiss();
if (result == 1) {
recycleAdapter = new RecycleAdapter(MainActivity.this,onlineData);
recyclerView.setAdapter(recycleAdapter);
} else {
Toast.makeText(MainActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show();
}
}
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("posts");
onlineData = new ArrayList<>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
HashMap<String, String> item = new HashMap<>();
item.put("title", post.optString("title"));
JSONArray jsonArray = post.getJSONArray("attachments");
JSONObject jsonObject1 = jsonArray.getJSONObject(0);
JSONObject jsonArrayImages = jsonObject1.getJSONObject("images");
JSONObject jsonArrayThumb = jsonArrayImages.getJSONObject("thumbnail");
item.put("thump", jsonArrayThumb.optString("url"));
onlineData.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
RecycleAdapter.java
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.ViewHolderRec> {
List<HashMap<String, String>> onlineData;
SQLiteDatabase db;
Context context;
RecycleAdapter(Context context,List<HashMap<String, String>> onlineData){
this.onlineData = onlineData;
this.context=context;
}
#Override
public ViewHolderRec onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolderRec( LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycle, parent, false));
}
#Override
public void onBindViewHolder(ViewHolderRec holder, int position) {
HashMap<String,String> map =onlineData.get(position);
//Download image using picasso library
Picasso.with(context).load(map.get("thump"))
.error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(holder.iv);
holder.tv.setText(map.get("title"));
}
#Override
public int getItemCount() {
return onlineData.size();
}
public class ViewHolderRec extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView iv;
TextView tv, quantity;
ImageView Add_Cart;
ImageView Remove_Cart;
public ViewHolderRec(View itemView) {
super(itemView);
iv = (ImageView) itemView.findViewById(R.id.thumbnail);
tv = (TextView) itemView.findViewById(R.id.title);
quantity = (TextView)itemView.findViewById(R.id.cart_qty);
Add_Cart = (ImageView)itemView.findViewById(R.id.cart_add);
Remove_Cart = (ImageView)itemView.findViewById(R.id.cart_remove);
itemView.setOnClickListener(this);
Add_Cart.setOnClickListener(this);
Remove_Cart.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == Add_Cart.getId()){
increment();
}
else if(v.getId() == Remove_Cart.getId()){
decrement();
}
}
public void increment(){
int currentNos = Integer.parseInt(quantity.getText().toString()) ;
quantity.setText(String.valueOf(++currentNos));
}
public void decrement(){
int currentNos = Integer.parseInt(quantity.getText().toString()) ;
quantity.setText(String.valueOf(--currentNos));
}
}
}
How to do this,
You should create interface, and activity implements this interface.
public interface OnItemClick {
void onClick (String value);
}
When you create adapter (last parameter is this interface)
public class MainActivity extends AppCompatActivity implements OnItemClick {
recycleAdapter = new RecycleAdapter(MainActivity.this,onlineData, this);
recyclerView.setAdapter(recycleAdapter);
#Override
void onClick (String value){
// value this data you receive when increment() / decrement() called
}
// In Adapter
private OnItemClick mCallback;
RecycleAdapter(Context context,List<HashMap<String, String>> onlineData,OnItemClick listener){
this.onlineData = onlineData;
this.context = context;
this.mCallback = listener;
}
....
public void increment(){
int currentNos = Integer.parseInt(quantity.getText().toString()) ;
quantity.setText(String.valueOf(++currentNos));
mCallback.onClick(quantity.getText().toString());
}
public void decrement(){
int currentNos = Integer.parseInt(quantity.getText().toString()) ;
quantity.setText(String.valueOf(--currentNos));
mCallback.onClick(quantity.getText().toString());
}
I failed to do it with both Interface and Observer pattern. But Local Broadcast worked for me.
In Adapter
String ItemName = tv.getText().toString();
String qty = quantity.getText().toString();
Intent intent = new Intent("custom-message");
// intent.putExtra("quantity",Integer.parseInt(quantity.getText().toString()));
intent.putExtra("quantity",qty);
intent.putExtra("item",ItemName);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
Main Activity
public void onCreate(Bundle savedInstanceState) {
...
// Register to receive messages.
// We are registering an observer (mMessageReceiver) to receive Intents
// with actions named "custom-message".
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-message"));
}
...
public BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String ItemName = intent.getStringExtra("item");
String qty = intent.getStringExtra("quantity");
Toast.makeText(MainActivity.this,ItemName +" "+qty ,Toast.LENGTH_SHORT).show();
}
};
Three popular ways to solve this problem
Interfaces
Phuoc Huynh has already explained how to use interfaces to solves this.
Observer pattern.
Try googling around observer to understand how it works. We will register the classes who want to receive events with the type of events they want to receive. There will be a manager classes to manage registering and unregistering of receivers and also to send the events to all receivers
public class EventManager {
private static EventManager eventManager;
private static Object syncObject = new Object();
private HashMap<String, ArrayList<EventListener>> listeners = new HashMap<>();
private EventManager(){}
public static EventManager getInstance() {
if (eventManager == null) {
synchronized (syncObject) {
if (eventManager == null) {
eventManager = new EventManager();
}
}
}
return eventManager;
}
public synchronized void registerListener(String event, EventListener listener) {
if (listeners.containsKey(event)) {
listeners.get(event).add(listener);
} else {
ArrayList<EventListener> arrayList = new ArrayList<>();
arrayList.add(listener);
listeners.put(event, arrayList);
}
}
public synchronized void unRegisterListener(String event, EventListener listener) {
if (listeners.containsKey(event)) {
listeners.get(event).remove(listener);
if (listeners.get(event).size() == 0) {
listeners.remove(event);
}
}
}
public void sendEvent(String event, Object o) {
if (listeners.containsKey(event)) {
ArrayList<EventListener> listener = listeners.get(event);
for (EventListener eventListener : listener) {
eventListener.onEvent(o);
}
}
}
}
Your MainActivity will register itself as a receiver of increment and decrement events and also implement onEvent method of IEventListener
public class MainActivity extends AppCompatActivity implements IEventListener{
#Override
protected void onCreate(Bundle onSavedInstanceState) {
EventManager.getInstance().registerEvent("increment", this);
EventManager.getInstance().registerEvent("decrement", this)
}
#Override
public void onEvent(String event) {
if (event.equals("increment") {
//increment
} else if (event.equals("decrement") {
//decrement
}
}
#Override
protected void onDestroy() {
EventManager.getInstance().unRegisterEvent("increment", this);
EventManager.getInstance().unRegisterEvent("decrement", this)
}
}
In you adapter class send the events
EventManager.getInstance().sendEvent("increment");
EventManager.getInstance().sendEvent("decrement");
LocalBroadcasts
LocalBroadcasts works the same way as the above example. you have get Instance of LocalBroadcastManger and send Broadcast on it. Define a broadcast receiver in the onCreate of the activity and register it using registerReceiver() in the Activity. Pass an intent filter in the register receiver with actiontype same as the broadcasts you want your activity to receive. Make sure you unregister the broadcasts whenever you don't need them or in the onDestroy of the activity
Simple solution using interface:
Create an interface with method containing objects/data as parameters:
public interface RecyclerViewDataPass {
public void pass(String productName, String quantity);
}
Implement interface method in Activity & pass it through RecyclerView Adapter:
RecyclerViewDataPass recyclerViewDataPass = new RecyclerViewDataPass() {
#Override
public void pass(String productName, String quantity) {
//we get data from adapter here
//assign parameters to activity variables or do the needed operations
}
};
recycleAdapter = new RecycleAdapter(MainActivity.this,onlineData,recyclerViewDataPass);
recyclerView.setAdapter(recycleAdapter);
Edit adapter's constructor:
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.ViewHolderRec> {
List<HashMap<String, String>> onlineData;
SQLiteDatabase db;
Context context;
RecyclerViewDataPass recyclerViewDataPass; //here is our data pass object
RecycleAdapter(Context context,List<HashMap<String, String>> onlineData, RecyclerViewDataPass recyclerViewDataPass){
this.onlineData = onlineData;
this.context=context;
this.recyclerViewDataPass=recyclerViewDataPass; //get data pass object from activity
}
Inside RecyclerView Adapter call pass function to send data to activity:
recyclerViewDataPass.pass(tv.getText().toString(), quantity.getText().toString());
Check out this. It works for me.
Just Paste in Your Activity or Fragment
rvSelectedProductList = Recyclerview
selcetedItemAdapter = RecyclerView Adapter
rvSelectedProductList.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
final int itemCount = selectedItemAdapter.getItemCount();
for (int i = 0; i < itemCount; i++) {
TextView tvSelling = rvSelectedProductList.getChildAt(i).findViewById(R.id.tvSelling);
TextView textViewDrawerTitle = rvSelectedProductList.getChildAt(i).findViewById(R.id.tvCartQty);
String totalamount = tvSelling.getText().toString();
String qty = textViewDrawerTitle.getText().toString();
System.out.println("qty" + qty);
System.out.println("total" + totalamount);
}
rvSelectedProductList.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
//Simply it works for me
//In onBindViewHolder of RecyclerAdapter write the following code on clickEvent of any view;
Intent intent = new Intent(tContext, TargetActivity.class);
intent.putExtra("key", "value");
tContext.startActivity(intent);
//TargetActivity.java
String str = getIntent().getStringExtra("key");
//You got the value as String :)
add these codes in onBindViewHolder
Intent intent = new Intent("message_subject_intent");
intent.putExtra("name" , String.valueOf(messageSubject.getname()));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
Add on MainActivity
public BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String name= intent.getStringExtra("name");
Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,new IntentFilter("message_subject_intent"));

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.

Categories

Resources