ListView itemId is always 0 - java

The value returned by id parameter of setOnItemClickListener is always 0(zero) no matter which position i click on the value returned is always 0
but the value of position of correct and i have also tried adapterView.getItemIdAtPosition(i) and still the value on clicking each item in list is zero
public class ListFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{
ListView onlineList;
FloatingActionButton onlineListFab;
private static final int mLoaderId = 1;
ListAdapter listAdapter;
public ListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_list, container, false);
initilize(v);
return v;
}
private void initilize(View v) {
onlineList = (ListView)v.findViewById(R.id.onlineList);
onlineListFab = (FloatingActionButton)v.findViewById(R.id.onlineListFab);
onlineListFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(),AddItem.class));
}
});
listAdapter = new ListAdapter(getActivity(),null);
onlineList.setAdapter(listAdapter);
onlineList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent details = new Intent(getActivity(),AddItem.class);
details.setData(Uri.withAppendedPath(TableName.mContentUri,String.valueOf(l)));
Toast.makeText(getActivity(),l+"",Toast.LENGTH_SHORT).show();
//startActivity(details);
}
});
loadItems();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
switch (id){
case mLoaderId:
return new CursorLoader(getContext(), TableName.mContentUri,null,null,null,null);
}
return null;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
listAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
listAdapter.swapCursor(null);
}
private void loadItems() {
if (getActivity().getSupportLoaderManager().getLoader(mLoaderId) == null) {
getActivity().getSupportLoaderManager().initLoader(mLoaderId, null, this).forceLoad();
} else {
getActivity().getSupportLoaderManager().restartLoader(mLoaderId, null, this).forceLoad();
}
}
}
AdapterCode :
public class ListAdapter extends CursorAdapter{
public ListAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = LayoutInflater.from(context).inflate(R.layout.item_layout,parent,false);
return v;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView name,price;
name = (TextView)view.findViewById(R.id.itemName);
price = (TextView)view.findViewById(R.id.itemPrice);
name.setText(cursor.getString(cursor.getColumnIndex(TableName.table1.mName)));
price.setText(String.valueOf(cursor.getInt(cursor.getColumnIndex(TableName.table1.mPrice))));
}
}

You're doing new ListAdapter(getActivity(),null); which is a custom class seeing as you can't do that with an interface. Have you updated the default getItemId method? I'd gamble not.
Off the top of my head, your adapter will need an implementation similar to:
#Override
public long getItemId(int position) {
long result = 0;
if (mCursor.moveToPosition(position)) {
Log.d("SO", DatabaseUtils.dumpCurrentRowToString(mCursor);
result = mCursor.getLong(mCursor.getColumnIndex(TableName.table1.mId));
}
return result;
}
If you can't resolve the problem take a look at the data itself in your cursors using DatabaseUtils

Related

Couldn't use bundle in Adapter - Java Android Studio

I'm on a project that, i'm getting datas from Json output. And showing them in my app. Json output includes categories in categories. I'm showing categories with listView, therefore i'm using adapters. It's all ok with FirstPageAdapter but when I switch the other, I can't get datas from FirstPageAdapter with using intent. That question(How to call getIntent() in adapter class) didn't helped me well btw.
FirstPageAdapter.java:
public class FirstPageAdapter extends BaseAdapter {
List<ResponseDTO> responseDTOList;
Context context;
Activity activity;
public FirstPageAdapter(List<ResponseDTO> responseDTOList, Context context, Activity activity) {
this.responseDTOList = responseDTOList;
this.context = context;
this.activity = activity;
}
#Override
public int getCount() {
return responseDTOList.size();
}
#Override
public Object getItem(int i) {
return responseDTOList.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = LayoutInflater.from(context).inflate(R.layout.layout_main_act, viewGroup, false);
TextView id, idCategory, parent_id, categoryName, filters, brands;
Button categoriesButton, specsButton;
id = view.findViewById(R.id.id);
idCategory = view.findViewById(R.id.idCategory);
parent_id = view.findViewById(R.id.parent_id);
categoryName = view.findViewById(R.id.categoryName);
filters = view.findViewById(R.id.filters);
brands = view.findViewById(R.id.brands);
categoriesButton = view.findViewById(R.id.childCategories);
specsButton = view.findViewById(R.id.specs);
id.setText("ID : "+responseDTOList.get(i).getId());
idCategory.setText("Category ID: "+responseDTOList.get(i).getIdcategory());
parent_id.setText("Parent ID: "+responseDTOList.get(i).getParentId());
categoryName.setText("Category name : "+responseDTOList.get(i).getCategoryName());
filters.setText("Filters : "+responseDTOList.get(i).getFilters());
brands.setText("Brands : "+responseDTOList.get(i).getBrands());
final String post = "" + responseDTOList.get(i).getId();
final String id_category = "" + responseDTOList.get(i).getIdcategory();
categoriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(activity, ChildCategoriesAdapter.class);
intent.putExtra("post_id",post);
intent.putExtra("id_category",id_category);
activity.startActivity(intent);
}
});
specsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(activity, ChildCategoriesAdapter.class);
intent.putExtra("post_id",post);
intent.putExtra("id_category",id_category);
activity.startActivity(intent);
}
});
return view;
}
}
ChildCategoriesAdapter.java:
public class ChildCategoriesAdapter extends BaseAdapter {
List<ResponseDTO> responseDTOList;
Context context;
Activity activity;
public ChildCategoriesAdapter(List<ResponseDTO> responseDTOList, Context context, Activity activity) {
this.responseDTOList = responseDTOList;
this.context = context;
this.activity = activity;
}
#Override
public int getCount() {
return responseDTOList.size();
}
#Override
public Object getItem(int i) {
return responseDTOList.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
defVars(view, viewGroup);
return null;
}
public void defVars(View view, ViewGroup viewGroup)
{
view = LayoutInflater.from(context).inflate(R.layout.layout_activity_child, viewGroup, false);
Button variationsButton;
TextView id, idCategory, parent_id, categoryName, filters, brands;
id = view.findViewById(R.id.id);
idCategory = view.findViewById(R.id.idCategory);
parent_id = view.findViewById(R.id.parent_id);
categoryName = view.findViewById(R.id.categoryName);
filters = view.findViewById(R.id.filters);
brands = view.findViewById(R.id.brands);
variationsButton = view.findViewById(R.id.variationsButton);
}
public void request()
{
responseDTOList = new ArrayList<>();
//Call<List<ResponseDTO>> call = ManagerAll
}
}
I have their Activities apart from these.
MainActivity.java(FirstPageAdapter):
public class MainActivity extends AppCompatActivity {
FirstPageAdapter adp;
List<ResponseDTO> list;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
defVars();
request();
}
public void defVars()
{
listView = findViewById(R.id.listView);
}
public void request()
{
list = new ArrayList<>();
Call<List<ResponseDTO>> call = ManagerAll.getInstance().bringCall();
call.enqueue(new Callback<List<ResponseDTO>>() {
#Override
public void onResponse(Call<List<ResponseDTO>> call, Response<List<ResponseDTO>> response) {
if (response.isSuccessful())
{
list = response.body();
adp = new FirstPageAdapter(list, getApplicationContext(), MainActivity.this);
listView.setAdapter(adp);
}
}
#Override
public void onFailure(Call<List<ResponseDTO>> call, Throwable t) {
}
});
}
}
Nothing important in ChildCategories.java

Adding click listener to two buttons in PagerAdpater CardViews

In my project, I have a PagerAdapter to inflate CardViews that hold text objects created by the user.
On each CardView I have edit and delete buttons to access methods to do with the ArrayList holding the text objects.
I have coded an interface in my adapter to handle clicks made within the text object creation activity. However, my instatiateItem method in my adapter is now showing on the #Override annotation "Method does not override method from its superclass". When I remove the #Override annotation I get an error in my Logcat:
java.lang.UnsupportedOperationException: Required method instantiateItem was not overridden
How do I implement a click listener for buttons on a CardView in a PagerAdapter?
Adapter code:
public class CreateAdapter extends PagerAdapter {
private List<PdfPage> pagesList;
private LayoutInflater layoutInflater;
private Context context;
private onItemClickListener mListener;
public interface onItemClickListener{
//click method for edit button
void onEditClick(int position);
//click method for delete button
void onDeleteClick(int position);
}
public void setOnItemClickListener(onItemClickListener listener){
mListener = listener;
}
public CreateAdapter(List<PdfPage> pagesList, Context context) {
this.pagesList = pagesList;
this.context = context;
}
#Override
public int getCount() {
return pagesList.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view.equals(object);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, final int position, final onItemClickListener listener) {
layoutInflater = LayoutInflater.from(context);
View view = null;
if(pagesList.get(position).getPageType() == "Text") {
view = layoutInflater.inflate(R.layout.create_text_cardview, container, false);
TextView inputText = view.findViewById(R.id.inputTextView);
ImageButton editButton = view.findViewById(R.id.imageButtonEdit);
ImageButton deleteButton = view.findViewById(R.id.imageButtonDelete);
//if this works, see 12:30 of video for image getter
inputText.setText(pagesList.get(position).getPageText());
//edit click listener
editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null){
int position2 = pagesList.indexOf(pagesList.get(position));
listener.onEditClick(position2);
}
}
});
//delete click listener
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null){
int position3 = pagesList.indexOf(pagesList.get(position));
listener.onDeleteClick(position3);
}
}
});
container.addView(view, 0);
}
//put else statement here for image cardView
assert view != null;
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View)object);
}
Activity code:
public class CreateActivity extends AppCompatActivity {
ViewPager viewPager;
CreateAdapter createAdapter;
List<PdfPage> pdfPageList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
pdfPageList = new ArrayList<>();
createAdapter = new CreateAdapter(pdfPageList, this);
viewPager = findViewById(R.id.viewPager);
viewPager.setAdapter(createAdapter);
viewPager.setPadding(130, 0, 130, 0);
}
#Override
protected void onStart() {
super.onStart();
createAdapter = new CreateAdapter(pdfPageList, this);
viewPager = findViewById(R.id.viewPager);
viewPager.setAdapter(createAdapter);
viewPager.setPadding(130, 0, 130, 0);
createAdapter.setOnItemClickListener(new CreateAdapter.onItemClickListener() {
#Override
public void onEditClick(int position) {
}
#Override
public void onDeleteClick(int position) {
pdfPageList.remove(position);
}
});
}
Your instantiateItem method does not override from it's superclass because you added an extra argument final onItemClickListener listener.
As you are using the same clickListener for all entries and passing the item position as an argument, I suggest that you pass the onItemClickListener in the adapter constructor, or just set it via
public void setOnItemClickListener(onItemClickListener listener){
mListener = listener;
}
Adapter code:
public class CreateAdapter extends PagerAdapter {
private List<PdfPage> pagesList;
private LayoutInflater layoutInflater;
private Context context;
private onItemClickListener mListener;
public interface onItemClickListener{
//click method for edit button
void onEditClick(int position);
//click method for delete button
void onDeleteClick(int position);
}
public void setOnItemClickListener(onItemClickListener listener){
mListener = listener;
}
public CreateAdapter(List<PdfPage> pagesList, Context context) {
this.pagesList = pagesList;
this.context = context;
}
#Override
public int getCount() {
return pagesList.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view.equals(object);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, final int position) {
layoutInflater = LayoutInflater.from(context);
View view = null;
if(pagesList.get(position).getPageType() == "Text") {
view = layoutInflater.inflate(R.layout.create_text_cardview, container, false);
TextView inputText = view.findViewById(R.id.inputTextView);
ImageButton editButton = view.findViewById(R.id.imageButtonEdit);
ImageButton deleteButton = view.findViewById(R.id.imageButtonDelete);
//if this works, see 12:30 of video for image getter
inputText.setText(pagesList.get(position).getPageText());
//edit click listener
editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mlistener != null){
int position2 = pagesList.indexOf(pagesList.get(position));
mlistener.onEditClick(position2);
}
}
});
//delete click listener
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mlistener != null){
int position3 = pagesList.indexOf(pagesList.get(position));
mlistener.onDeleteClick(position3);
}
}
});
container.addView(view, 0);
}
//put else statement here for image cardView
assert view != null;
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View)object);
}
And your Activity code could stay as it is.

How to add new item on button press in Base Adapter

I'm trying to crate something that creates a new ListView item on button press, I thing I have somewhere some bug, but as I'm new to this topic I don't know where.
I've tried rewriting the code several times, I've tried to use notifyDataSetChanged(); - it does nothing
tried googling looking on other topics here...
Here is my MainActivity.java:
public Button btn;
private ListView lv;
private CustomeAdapter customeAdapter;
public ArrayList<EditModel> editModelArrayList;
int populateListMaxNum =3;
int listNumber = populateListMaxNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView);
btn = (Button) findViewById(R.id.btn);
editModelArrayList = populateList();
customeAdapter = new CustomeAdapter(this,editModelArrayList);
lv.setAdapter(customeAdapter);
/* TODO activate button */
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addToList();
Toast.makeText(getApplicationContext(), "button", Toast.LENGTH_LONG).show();
}
});
}
private ArrayList<EditModel> populateList(){ //this part works perfectly
ArrayList<EditModel> list = new ArrayList<>();
for(int i = 0; i < populateListMaxNum; i++){
EditModel editModel = new EditModel();
//editModel.setEditTextValue(String.valueOf(i));
list.add(editModel);
}
return list;
}
/*TODO make it work = expand */
private void addToList(){ // this part doesn't work nor it doesn't fail
EditModel editModel = new EditModel();
editModelArrayList.add(editModel);
customeAdapter.notifyDataSetChanged();
}
}
Here is my CustomeAdapter.java class:
public class CustomeAdapter extends BaseAdapter {
private Context context;
public static ArrayList<EditModel> editModelArrayList;
public CustomeAdapter(Context context, ArrayList<EditModel> editModelArrayList) {
this.context = context;
CustomeAdapter.editModelArrayList = editModelArrayList;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
return editModelArrayList.size();
}
#Override
public Object getItem(int position) {
return editModelArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.lv_item, null, true);
holder.editText = convertView.findViewById(R.id.editid);
convertView.setTag(holder);
}else {
// the getTag returns the viewHolder object set as a tag to the view
holder = (ViewHolder)convertView.getTag();
}
holder.editText.setText(editModelArrayList.get(position).getEditTextValue());
holder.editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
editModelArrayList.get(position).setEditTextValue(holder.editText.getText().toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return convertView;
}
private class ViewHolder {
protected EditText editText;
}
}
I expect to create a new list item (EditText + TextView) but nothing happens (except the Toast message)
(After some tweaks the app crashes due to arrayindexoutofboundsexception length=3 index=3 error, but not in this setting)
here are up to all files nessessary: https://gist.github.com/Atingas/52778a247a78131e5b8cb0239fa30965
Main linear layout in lv_item.xml has match_parent height. Try change it to wrap_content. It seems like one row is just taking whole screen.

query() method of Content provider returns data twice in recycler View adapter

I am working on a android project, here i have a class CategoryProvider which extends ContentProvider class and i also implements LoaderManager.LoaderCallbacks<Cursor> in my main Activity and I also have CategoryAdapter class which extends RecyclerView.Adapter<CategoryAdapter.ViewHolder>. I have 3 records in my Sqlite database, now after initialization of Loader in main Activity when data is loading in the adapter it loads each record twice so how to fix that.
CategotyAdapter.java
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder> {
Cursor dataCursor;
Context context;
String global_lang = "English";
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView name;
ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.titleText);
imageView = (ImageView) itemView.findViewById(R.id.icons);
}
}
public CategoryAdapter(Activity mContext, Cursor cursor) {
dataCursor = cursor;
context = mContext;
}
#Override
public CategoryAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View cardview = LayoutInflater.from(parent.getContext())
.inflate(R.layout.option_layout, parent, false);
return new ViewHolder(cardview);
}
#Override
public void onBindViewHolder(CategoryAdapter.ViewHolder holder, int position) {
dataCursor.moveToPosition(position);
String imagePath = dataCursor.getString(dataCursor.getColumnIndex(CategoryContract.CategoryEntry.COLUMN_IMAGE_PATH));
String cEn_name = dataCursor.getString(dataCursor.getColumnIndex(CategoryContract.CategoryEntry.COLUMN_CONTENT_EN));
String cHi_name = dataCursor.getString(dataCursor.getColumnIndex(CategoryContract.CategoryEntry.COLUMN_CONTENT_HI));
if(global_lang.equals("English"))
holder.name.setText(cEn_name);
else
holder.name.setText(cHi_name);
Glide.with(context)
.load(imagePath)
.apply(new RequestOptions()
.placeholder(R.drawable.loading))
.into(holder.imageView);
}
public Cursor swapCursor(Cursor cursor) {
if(dataCursor == cursor) {
return null;
}
Cursor oldCursor = dataCursor;
this.dataCursor = cursor;
if(cursor != null) {
this.notifyDataSetChanged();
}
return oldCursor;
}
#Override
public int getItemCount() {
if(dataCursor != null)
Log.d("datacursor count", " " +dataCursor.getCount());
else
Log.d("datacursor count", "datacursor is null");
return (dataCursor == null) ? 0 : dataCursor.getCount();
}
public void changeLang(String lang) {
this.global_lang = lang;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstTimeUser();
ActivityToolbar = (Toolbar) findViewById(R.id.toolbar);
ActivitySpinner = (Spinner) findViewById(R.id.spinner);
ActivityToolbar.setTitle(R.string.app_name);
ActivityAdapter = ArrayAdapter.createFromResource(this, R.array.languages, R.layout.drop_menu);
ActivityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ActivitySpinner.getBackground().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
ActivitySpinner.setAdapter(ActivityAdapter);
listeners();
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
}
categoryAdapter = new CategoryAdapter(this, null);
recyclerView.setAdapter(categoryAdapter);
getLoaderManager().initLoader(CATEGORY_LOADER, null, this);
}
public void listeners() {
ActivitySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
categoryAdapter.changeLang(ActivitySpinner.getSelectedItem().toString());
getLoaderManager().restartLoader(CATEGORY_LOADER, null, MainActivity.this);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] data = {
CategoryContract.CategoryEntry._ID,
CategoryContract.CategoryEntry.COLUMN_IMAGE_PATH,
CategoryContract.CategoryEntry.COLUMN_CONTENT_EN,
CategoryContract.CategoryEntry.COLUMN_CONTENT_HI
};
return new CursorLoader(
this,
CategoryContract.CategoryEntry.CONTENT_URI,
data,
null,
null,
null
);
}
#Override
protected void onResume() {
super.onResume();
loader_flag = 0;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
categoryAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
categoryAdapter.swapCursor(null);
}
Thanks!!
Ok, I got it after a lot of debugging. Here I am using Sync Adapter framework in my App which syncs the data at the background, when it trying to reload data the duplicate data is synced rapidly with new ID and it was rendered by recyclerView. so now I am using some constraints and changing my Database structure.

List found beacons in ListView

I'm trying to make a simple application in Android that displays all the beacons that are found in a ListView by using the AltBeacon library. The problem that I'm having is that no beacon is shown, I keep on getting a blank screen without any beacons.
Any ideas what could be wrong with my code?
This is the code I have:
MainActivity.java:
public class MainActivity extends Activity implements BeaconConsumer, RangeNotifier {
public BeaconManager mBeaconManager;
public List<Beacon> beaconlijst;
ListView lijst;
public BeaconListAdapter listAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
beaconlijst = new ArrayList<>();
lijst = (ListView)findViewById(R.id.listViews);
listAdapter = new BeaconListAdapter(this, beaconlijst);
lijst.setAdapter(listAdapter);
mBeaconManager = BeaconManager.getInstanceForApplication(this.getApplicationContext());
mBeaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("s:0-1=feaa,m:2-2=00,p:3-3:-41,i:4-13,i:14-19"));
mBeaconManager.bind(this);
}
#Override
public void onBeaconServiceConnect() {
Region region = new Region("all-beacons-region", null, null, null);
try {
mBeaconManager.startRangingBeaconsInRegion(region);
}catch(RemoteException e) {
e.printStackTrace();
}
mBeaconManager.setRangeNotifier(this);
}
#Override
public void didRangeBeaconsInRegion(final Collection<Beacon> beacons, Region region) {
runOnUiThread(new Runnable() {
#Override
public void run() {
beaconlijst = new ArrayList<>(beacons);
listAdapter.notifyDataSetChanged();
}
});
}
public void onPause() {
super.onPause();
mBeaconManager.unbind(this);
}
}
BeaconListAdapter.java:
public class BeaconListAdapter extends BaseAdapter {
private Activity activity;
private List<Beacon> beacons;
private static LayoutInflater inflater = null;
public BeaconListAdapter(Activity _activity, List<Beacon> _beacons) {
this.activity = _activity;
this.beacons = _beacons;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return beacons.size();
}
#Override
public Object getItem(int position) {
return beacons.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(convertView == null ) {
view = inflater.inflate(R.layout.tupple_monitoring, null);
}
TextView uuid = (TextView)view.findViewById(R.id.BEACON_uuid);
TextView rssi = (TextView)view.findViewById(R.id.BEACON_rssi);
TextView txpower = (TextView)view.findViewById(R.id.BEACON_txpower);
Beacon beacon = beacons.get(position);
if(beacon != null) {
uuid.setText(beacon.getId2().toString());
rssi.setText(beacon.getRssi());
txpower.setText(beacon.getTxPower());
}
return view;
}
}
Any help would greatly be appreciated.

Categories

Resources