I want to send an array list of object from one activity to another. I am extending my object class with Parcelable and transferred list using intent onActivityResult.
But the list shows null in second activity.
first activity :
public class PlanEventActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener,
DatePickerDialog.OnDateSetListener{
private boolean mHoursMode;
RelativeLayout chooseEvent,time,date;
EditText eventName;
TextView timeTextView,dateTextView,chooseEventText;
static final int CUSTOM_DIALOG_ID = 0;
ListView dialog_ListView;
private ImageView addOrganizer;
static final int PICK_CONTACT_REQUEST = 1;
private ArrayList<contact> mSelectedContacts;
private ListViewAdapter mAdapter;
private ListView mContactsList;
private ArrayList<Integer> selectedItemsPositions;
private boolean mContactListActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plan_event);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("");
TextView toolbarTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
toolbarTitle.setText("MeaVita");
setSupportActionBar(toolbar);
setUpUI();
mAdapter = new ListViewAdapter(this,mSelectedContacts);
mContactsList.setAdapter(mAdapter);
mAdapter.setMode(Attributes.Mode.Single);
mContactsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
((SwipeLayout)(mContactsList.getChildAt(position - mContactsList.getFirstVisiblePosition()))).open(true);
}
});
}
public void setUpUI()
{
chooseEvent = (RelativeLayout)findViewById(R.id.chooseEventLayout);
time = (RelativeLayout)findViewById(R.id.timeLayout);
date = (RelativeLayout)findViewById(R.id.dateLayout);
eventName = (EditText)findViewById(R.id.editTextEventName);
timeTextView = (TextView)findViewById(R.id.timeTextView);
dateTextView = (TextView)findViewById(R.id.dateTextView);
chooseEventText = (TextView)findViewById(R.id.chooseEventTextView);
addOrganizer = (ImageView)findViewById(R.id.addOrganizer);
mContactsList = (ListView)findViewById(R.id.selectedContactsList);
mSelectedContacts = new ArrayList<>();
contact contact = new contact();
contact.setContactid("1");
contact.setContactName("sid");
mSelectedContacts.add(contact);
contact.setContactid("2");
contact.setContactName("ssss");
mSelectedContacts.add(contact);
addOrganizer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pickContactIntent = new Intent(PlanEventActivity.this,ContactList.class);
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
Bundle bundle = data.getExtras();
mContactListActivity = bundle.getBoolean("contactListActivity",true);
mSelectedContacts = bundle.getParcelableArrayList("selectedContacts");
}
if(mContactListActivity)
{
addOrganizer.setVisibility(View.INVISIBLE);
mContactsList.setVisibility(View.VISIBLE);
}
else {
mContactsList.setVisibility(View.GONE);
}
}
}
Second activity :
public class ContactList extends AppCompatActivity {
private ArrayList<contact> contact_list = null;
private contactAdapter mContactAdapter = null;
private ArrayList<contact> items;
private ArrayList<contact> selectedContacts;
boolean[] isChecked;
Cursor mCursor;
ListView lv;
public int RQS_PICK_CONTACT = 1;
private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
ArrayList<Integer> selectedItemsPositions;
private ImageView done;
private boolean mContactListActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("");
TextView toolbarTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
toolbarTitle.setText("Select Contacts");
setSupportActionBar(toolbar);
done = (ImageView)findViewById(R.id.done);
contact_list = new ArrayList<contact>();
selectedContacts = new ArrayList<contact>();
lv = (ListView)findViewById(R.id.list);
showContacts();
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("selectd",String.valueOf(selectedItemsPositions));
mContactListActivity = true;
selectedContacts = new ArrayList<>();//to store selected items
for (Integer pos : selectedItemsPositions) {
selectedContacts.add(items.get(pos));
}
Intent i = new Intent(ContactList.this,PlanEventActivity.class);
Bundle b = new Bundle();
b.putSerializable("selectedContacts",(Serializable) selectedContacts);
i.putExtras(b);
setResult(RESULT_OK, i);
finish();
}
});
}
#SuppressWarnings("unused")
private void getContacts() {
String[] projection = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
ContactsContract.Contacts._ID };
mCursor = managedQuery(ContactsContract.Contacts.CONTENT_URI, null, null, null,null);
while (mCursor.moveToNext()) {
contact contact = new contact();
String contactId = mCursor.getString(mCursor.getColumnIndex(ContactsContract.Contacts._ID));
contact.setContactid(mCursor.getString(mCursor.getColumnIndex(ContactsContract.Contacts._ID)));
contact.setContactName(mCursor.getString(mCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
contact_list.add(contact);
}
isChecked = new boolean[mCursor.getCount()];
for (int i = 0; i < isChecked.length; i++) {
isChecked[i] = false;
}
this.mContactAdapter = new contactAdapter(this, R.layout.contact_list_item, contact_list);
lv.setAdapter(this.mContactAdapter);
// mCursor.close();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RQS_PICK_CONTACT) {
if (resultCode == RESULT_OK) {
getContacts();
}
}
}
public class contactAdapter extends ArrayAdapter<contact> {
public contactAdapter(Context context, int textViewResourceId, ArrayList<contact> items1) {
super(context, textViewResourceId, items1);
items = items1;
selectedItemsPositions = new ArrayList<>();
}
//to store all selected items position
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder mViewHolder;
if (convertView == null) {
mViewHolder = new ViewHolder();
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.contact_list_item, parent, false);
mViewHolder.cb = (CheckBox) convertView.findViewById(R.id.checkBox);
mViewHolder.name = (TextView) convertView.findViewById(R.id.name);
mViewHolder.cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean ischecked) {
int position = (int) mViewHolder.cb.getTag();
if (ischecked) {
//check whether its already selected or not
if (!selectedItemsPositions.contains(position))
selectedItemsPositions.add(position);
} else {
//remove position if unchecked checked item
selectedItemsPositions.remove((Object) position);
}
}
});
convertView.setTag(mViewHolder);
} else {
mViewHolder = (ViewHolder) convertView.getTag();
}
contact contacts = items.get(position);
mViewHolder.cb.setTag(position);
if (selectedItemsPositions.contains(position))
mViewHolder.cb.setChecked(true);
else
mViewHolder.cb.setChecked(false);
mViewHolder.name.setText(contacts.getContactName());
return convertView;
}
public class ViewHolder {
CheckBox cb;
TextView name;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission is granted
getContacts();
} else {
Toast.makeText(this, "Until you grant the permission, we canot display the names", Toast.LENGTH_SHORT).show();
}
}
}
private void showContacts()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
//After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method
}
else {
getContacts();
}
}
}
Object class:
public class contact implements Parcelable {
private String contactName;
private String contactId;
contact(){}
contact(String contactId,String contactName)
{
this.contactId = contactId;
this.contactName = contactName;
}
public contact(Parcel in) {
this();
contactId = in.readString();
contactName = in.readString();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(contactId);
dest.writeString(contactName);
}
public static final Parcelable.Creator<contact> CREATOR = new Parcelable.Creator<contact>()
{
public contact createFromParcel(Parcel in)
{
return new contact(in);
}
public contact[] newArray(int size)
{
return new contact[size];
}
};
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getContactid() {
return contactId;
}
public void setContactid(String contactId) {
this.contactId = contactId;
}
}
Not getting what's going wrong. Can anyone help please. Thank you..
When you receive the results from a startActivityForResult() call, the result Intent is passed into the onActivityResult() method as the last parameter. You're using the Intent returned from getIntent(), which is the Intent used to start the current Activity, so it will not have the extras you're looking for.
In onActivityResult(), get the Bundle from the data Intent passed into the method.
Bundle bundle = data.getExtras();
You'll also need to remove this line in onActivityResult():
mSelectedContacts = bundle.getParcelableArrayList("selectedContacts");
And replace it with:
ArrayList<contact> newContacts = bundle.getParcelableArrayList("selectedContacts");
mSelectedContacts.addAll(newContacts);
mAdapter.notifyDataSetChanged();
And make sure you've changed the b.putSerializable() call in ContactList to b.putParcelableArrayList("selectedContacts", selectedContacts).
USE THIS
Bundle b = this.getIntent().getExtras();
mSelectedContacts = b.getParcelableArrayList("selectedContacts");
INSTEAD OF
Intent i = getIntent();
Bundle bundle = i.getExtras();
mSelectedContacts = i.getParcelableArrayListExtra("selectedContacts");
I have checked your code and get some minor issues,
So may be by fixing it you can get results.
Follow below steps.
(1) In PlanEventActivity file, change onActivityResult by below,
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
Bundle bundle = data.getExtras();
mContactListActivity = bundle.getBoolean("contactListActivity",true);
mSelectedContacts = (ArrayList<contact>) bundle.getSerializable("selectedContacts");
mAdapter.notifyDataSetChanged();
}
if(mContactListActivity)
{
addOrganizer.setVisibility(View.INVISIBLE);
mContactsList.setVisibility(View.VISIBLE);
}
else {
mContactsList.setVisibility(View.GONE);
}
}
As you are getting result properly but without converting it in proper type you will get null, so you need to convert your result parcelable array list in your contact arraylist other wise it will not work. And also after getting list to display in list view you need to notify your adapter for dataset changed. Also you are paassing Serializable object then also get it by getSerializable method.
(2) Implement Serializable instead of parcelable for object, like below
public class contact implements Serializable.
And now try to run your app, almost done you will get result.
Do it like this:
Bundle b = new Bundle();
b.putSerializable("selectedContacts", selectedContacts);
i.putExtras(b);
EDIT 2: Retrieve it by :
Bundle bundle = i.getExtras();
mContactListActivity = i.getBooleanExtra("contactListActivity",true);
mSelectedContacts = (ArrayList<contact>) i.getSerializableExtra("selectedContacts");
And don't forget :
public class contact implements Serializable {...}
EDIT:
REMOVE (Serializable) :
Don't write this :
b.putSerializable("selectedContacts",(Serializable) selectedContacts);
write this :
b.putSerializable("selectedContacts",selectedContacts);
Related
When I delete an item from the RecyclerView, I am no longer able to delete another item. When I make an item I am also unable to delete that item and any other item in the RecyclerView.
Below is the code.
Home.java:
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
itemImage = findViewById(R.id.image_holder);
itemName = findViewById(R.id.add_item_name);
itemPrice = findViewById(R.id.add_price);
itemDesc = findViewById(R.id.add_desc);
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
addPhotoButton = findViewById(R.id.getCameraBtn);
addFileButton = findViewById(R.id.getGalleryBtn);
imageView = findViewById(R.id.image_holder);
addPhotoButton.setOnClickListener(this);
addFileButton.setOnClickListener(this);
itemList = new ArrayList<Item>();
// add item for testing
itemList.add(new Item(R.drawable.ic_logo, "Baby Stroller", "A stroller for baby", "59.99"));
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
adapter = new ItemAdapter(itemList);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new ItemAdapter.OnItemClickListener() {
#Override
public void onDeleteClick(int position) {
removeItem(position);
}
#Override
public void onEditClick(int position) {
editItem(position);
}
});
}
// log out back to start page
public void goToStart(View view){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.getCameraBtn:
//post a photo from the camera
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, CAMERA_CODE);
break;
case R.id.getGalleryBtn:
//post an image
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*"); //anything that is image related
startActivityForResult(galleryIntent, GALLERY_CODE);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_CODE && resultCode == RESULT_OK) {
if (data != null) {
imageUri = data.getData(); //we have the actual path
imageView.setImageURI(imageUri); //show image
}
} else if (requestCode == CAMERA_CODE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
}
}
public void addItem(View view){
if(itemName.getText().toString().trim().length() != 0 || itemPrice.getText().toString().trim().length() != 0 || itemDesc.getText().toString().trim().length() != 0){
itemList.add(new Item(R.drawable.ic_logo, itemName.getText().toString(), itemPrice.getText().toString(), itemDesc.getText().toString()));
adapter = new ItemAdapter(itemList);
recyclerView.setAdapter(adapter);
itemName.setText("");
itemPrice.setText("");
itemDesc.setText("");
}
else{
Toast.makeText(Home.this, "All fields must be filled when creating a new item.",
Toast.LENGTH_LONG).show();
}
}
public void removeItem(int position){
itemList.remove(position);
adapter.notifyItemChanged(position);
}
ItemAdapter.java:
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder>{
private ArrayList<Item> ItemList;
private OnItemClickListener Listener;
public void setOnItemClickListener(OnItemClickListener listener) {Listener = listener;}
public interface OnItemClickListener{
void onDeleteClick(int position);
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public ImageView item_image;
public TextView item_name;
public TextView item_desc;
public TextView item_price;
public ImageView deleteBtn;
public ImageView editBtn;
public ViewHolder(#NonNull View itemView, OnItemClickListener listener) {
super(itemView);
item_image = itemView.findViewById(R.id.item_image);
item_name = itemView.findViewById(R.id.item_name);
item_desc = itemView.findViewById(R.id.desc);
item_price = itemView.findViewById(R.id.price);
deleteBtn = itemView.findViewById(R.id.delete_item);
editBtn = itemView.findViewById(R.id.edit_item);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
listener.onDeleteClick(position);
}
}
}
});
}
}
public ItemAdapter(ArrayList<Item> itemList) {ItemList = itemList;}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_items, parent, false);
ViewHolder vh = new ViewHolder(v, Listener);
return vh;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Item currentItem = ItemList.get(position);
holder.item_image.setImageResource(currentItem.getItemImage());
holder.item_name.setText(currentItem.getItemName());
holder.item_desc.setText(currentItem.getItemDesc());
holder.item_price.setText(currentItem.getItemPrice());
}
#Override
public int getItemCount() {
return ItemList.size();
}
}
Item.java:
public class Item {
private int itemImage;
private String itemName;
private String itemDesc;
private String itemPrice;
public Item(int itemImage, String itemName, String itemDesc, String itemPrice){
this.itemImage = itemImage;
this.itemName = itemName;
this.itemDesc = itemDesc;
this.itemPrice = itemPrice;
}
public int getItemImage(){return itemImage;}
public String getItemName(){return itemName;}
public String getItemDesc(){return itemDesc;}
public String getItemPrice(){return itemPrice;}
}
When the user clicks the delete button, it will work the first time and remove that particular item but when another item needs to be removed, the button is not responding. The same happens when the user adds an item and is unable to delete any items. Not really sure what could cause this. Thanks.
Edit:
The delete function works correctly when I hardcode items into the RecyclerView. It is only when adding a new item, it doesn't work anymore including the hardcoded items.
In Home.java, you are setting the click listener:
adapter.setOnItemClickListener(new ItemAdapter.OnItemClickListener() {...}
In addItem(), you are creating a new adapter:
adapter = new ItemAdapter(itemList);
The problem is that you never set a click listener on this new adapter.
I would consider not creating a new adapter but calling a notify method to alert the adapter to a new item.
Try to change adapter.notifyItemChanged(position); to adapter.notifyItemRemoved(position);
You are telling the adapter that one item is changed, instead of that use:
notifyDataSetChanged()
this should reload all items
ello guys good day I'm trying to make an app using android java but I'm stuck any idea would be appreciated
I'm trying to access all pdf files in android device using the media store and cursor but it's not working the aim is to display all pdf files in a recycler view on a fragment the issue here is that it never displays meaning maybe the data wasn't passed because when the arraylist is populated manually it displays otherwise non I've checked the log but I can't seem to find anything.
This my fragment code
public class AllFragment extends Fragment {
View view;
private static final String TAG = "MyActivity";
ArrayList<String> pdfList;
private final int STORAGE_PERMISSION_CODE = 1;
private Activity mActivity;
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
mActivity = (Activity) context;
}
public void checkPermission(){
if ((ContextCompat.checkSelfPermission(mActivity, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED))
{
if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity, Manifest.permission.READ_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(mActivity)
.setTitle("Permission needed")
.setMessage("Allow "+getResources().getString(R.string.app_name)+" to access your storage?")
.setPositiveButton("ok", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which){
ActivityCompat.requestPermissions(mActivity,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
}
)
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which){
dialog.dismiss();
Toast.makeText(mActivity, "Please allow this permission!", Toast.LENGTH_SHORT).show();
}
})
.create().show();
} else {
ActivityCompat.requestPermissions(mActivity,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
}
}
//checkPermission();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.AllFragment, container, false);
//pdfList = getPdfList();
//buildData();
//LinearLayoutManager
//pdfList = new String[] {"one", "two", "three", "fou4", "five", "six"};
getPdfList();
initRecyclerView(view);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkPermission();
}
//RecyclerView
public void initRecyclerView(View view){
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.allPdfsRecyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
AllPdfAdapter adapter = new AllPdfAdapter(pdfList);
recyclerView.setAdapter(adapter);
}
public ArrayList<String> getPdfList() {
pdfList = new ArrayList<>();
Uri collection;
final String[] projection = new String[]{
MediaStore.Files.FileColumns.DISPLAY_NAME,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.MIME_TYPE,
};
final String sortOrder = MediaStore.Files.FileColumns.DATE_ADDED + " DESC";
final String selection = MediaStore.Files.FileColumns.MIME_TYPE + " = ?";
final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
final String[] selectionArgs = new String[]{mimeType};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
}else{
collection = MediaStore.Files.getContentUri("external");
}
try (Cursor cursor = getActivity().getContentResolver().query(collection, projection, selection, selectionArgs, sortOrder)) {
assert cursor != null;
if (cursor.moveToFirst()) {
int columnData = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
int columnName = cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME);
//ArrayList pdfList = new ArrayList<>();
do {
pdfList.add((cursor.getString(columnData)));
System.out.println(cursor.getString(columnData));
Log.d(TAG, "getPdf: " + cursor.getString(columnData));
//you can get your pdf files
} while (cursor.moveToNext());
}
}
return pdfList;
}
}
This my adapter code
public class AllPdfAdapter extends RecyclerView.Adapter<AllPdfAdapter.My_ViewHolder>
{
private ArrayList<String> data;
public AllPdfAdapter(ArrayList<String>data){
this.data = data;
}
#Override
public AllPdfAdapter.My_ViewHolder onCreateViewHolder(ViewGroup p1, int p2)
{
LayoutInflater li = LayoutInflater.from(p1.getContext());
View v = li.inflate(R.layout.allList,p1,false);
// TODO: Implement this method
return new My_ViewHolder(v);
}
#Override
public void onBindViewHolder(AllPdfAdapter.My_ViewHolder holder, int position)
{
// TODO: Implement this method
String title = data.get(position);
holder.ttt.setText(title);
}
#Override
public int getItemCount()
{
// TODO: Implement this method
return data.size();
}
public class My_ViewHolder extends RecyclerView.ViewHolder{
ImageView iii;
TextView ttt;
public My_ViewHolder (View v){
super(v);
iii = (ImageView) v.findViewById(R.id.img);
ttt = (TextView) v.findViewById(R.id.title);
}
}
}
Your answers will be appreciated.
My code is working fine when it comes to clicking items. But the problem arises when I try to open activities after filtering listview. It always opens activity 1.
Here is my source code.
navigate.java
public class navigate extends Activity {
// Declare Variables
ListView list;
ListViewAdapter adapter;
EditText editsearch;
String[] rank;
String[] names;
int[] flag;
ArrayList<Object> arraylist = new ArrayList<Object>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main);
// Generate sample data
rank = new String[] { "1", "2", "3", "4", "5","6","7","8","9","10","11"};
names = new String[] { "Animal Bite", "Asthma Attack", "Choking","CPR","Black eye",
"Drowning", "Fracture","Heart Attack","Insect Bite","Poisoning","Spinal Injury",};
flag = new int[] { R.drawable.animal,
R.drawable.asthma, R.drawable.choke, R.drawable.cpricon,
R.drawable.blckeye,R.drawable.drown,R.drawable.fracture,R.drawable.hrtattck,R.drawable.insect,R.drawable.poison,R.drawable.spinal };
// Locate the ListView in listview_main.xml
list = (ListView) findViewById(R.id.listview);
for (int i = 0; i < rank.length; i++)
{
Object wp = new Object(rank[i], names[i], flag[i]);
// Binds all strings into an array
arraylist.add(wp);
}
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(this, arraylist);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
// Locate the EditText in listview_main.xml
editsearch = (EditText) findViewById(R.id.search);
// Capture Text in EditText
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> listView, View view,
final int position, long id) {
switch ((int) adapter.getItemId(position)) {
case 0:
Intent newActivity = new Intent(navigate.this, animalbite.class);
startActivity(newActivity);
break;
case 1:Intent newActivity1 = new Intent(navigate.this, asthmaattack.class);
startActivity(newActivity1);
break;
case 2:Intent newActivity2 = new Intent(navigate.this, animalbite.class);
startActivity(newActivity2);
break;}
}
});
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<Object> objectList = null;
private ArrayList<Object> arraylist;
public ListViewAdapter(Context context,
List<Object> objectList) {
mContext = context;
this.objectList = objectList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<Object>();
this.arraylist.addAll(objectList);
}
public class ViewHolder {
TextView name;
ImageView flag;
}
#Override
public int getCount() {
return objectList.size();
}
#Override
public Object getItem(int position) {
return objectList.get(position);
}
public String getCountry(int position){return objectList.get(position).getCountry();}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
//holder.rank = (TextView) view.findViewById(R.id.rank);
holder.name = (TextView) view.findViewById(R.id.name);
// Locate the ImageView in listview_item.xml
holder.flag = (ImageView) view.findViewById(R.id.flag);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
//holder.rank.setText(objectList.get(position).getRank());
holder.name.setText(objectList.get(position).getCountry());
;
// Set the results into ImageView
holder.flag.setImageResource(objectList.get(position)
.getFlag());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
// Pass all data rank
// Start SingleItemView Class
switch (position) {
case 0:
Intent intent = new Intent(mContext, animalbite.class);
mContext.startActivity(intent);break;
case 1:
Intent i2 = new Intent(mContext, asthmaattack.class);
mContext.startActivity(i2);break;
case 2:
Intent i3 = new Intent(mContext, choking.class);
mContext.startActivity(i3);break;
case 3:
Intent i4 = new Intent(mContext, cpr.class);
mContext.startActivity(i4);break;
case 4:
Intent i5 = new Intent(mContext, lackeye.class);
mContext.startActivity(i5);break;
case 5:
Intent i6 = new Intent(mContext, drowning.class);
mContext.startActivity(i6);break;
case 6:
Intent i7 = new Intent(mContext, Fracture.class);
mContext.startActivity(i7);break;
case 7:
Intent i8 = new Intent(mContext, heartattack.class);
mContext.startActivity(i8);break;
case 8:
Intent i9 = new Intent(mContext, insectbite.class);
mContext.startActivity(i9);break;
case 9:
Intent i10 = new Intent(mContext, poisoning.class);
mContext.startActivity(i10);break;
case 10:
Intent i11 = new Intent(mContext, spinalinjury.class);
mContext.startActivity(i11);break;
}}});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
objectList.clear();
if (charText.length() == 0) {
objectList.addAll(arraylist);
} else {
for (Object wp : arraylist) {
if (wp.getCountry().toLowerCase(Locale.getDefault())
.contains(charText)) {
objectList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Object.java
public class Object {
private String rank;
private String country;
private int flag;
public Object(String rank, String country,
int flag) {
this.rank = rank;
this.country = country;
this.flag = flag;
}
public String getCountry() {
return this.country;
}
public int getFlag() {
return this.flag;
}
}
How can I open different activities while clicking on listview items after I filter them.
This is the sample code I used. Although it doesn't provide the functionality to open original activities through intent ,just some forged up activity,so I'm trying to change that.
http://www.androidbegin.com/tutorial/android-search-filter-listview-images-and-texts-tutorial/
I think your adapter has problem, this below sample code of my application is extended from Filterable and work fine
public class AdapterContacts extends BaseAdapter implements Filterable {
private LayoutInflater inflater;
private Context context;
private List<ContactLists> categoryArrayList;
private final ArrayList<ContactLists> originalList = new ArrayList<ContactLists>();
private NameFilter filter;
public AdapterContacts(ArrayList<ContactLists> array) {
categoryArrayList = array;
}
public AdapterContacts(Context context, List<ContactLists> array) {
this.context = context;
inflater = LayoutInflater.from(this.context);
categoryArrayList = array;
originalList.addAll(array);
}
#Override
public int getCount() {
return categoryArrayList.size();
}
#Override
public ContactLists getItem(int position) {
return categoryArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_contacts_list_item, null);
mViewHolder = new ViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (ViewHolder) convertView.getTag();
}
ContactLists item = getItem(position);
mViewHolder.fillItems(this, item, position);
return convertView;
}
private static class UI extends HelperUI {
public TextView tv_person_nickname_mobile_number;
public TextView btn_invite_message;
public ImageView img_contact_image;
public ImageView imgv_user_rank;
public TextView tv_contact_name;
public LinearLayout ll_root;
public UI(View view) {
parseUi(view);
}
}
private class ViewHolder {
private UI UI;
public ViewHolder(View view) {
UI = new UI(view);
}
public void fillItems(final AdapterContacts adapter, final ContactLists item, final int position) {
UI.tv_contact_name.setText(item.getContact_name());
if (item.getStatus() == 1) {
UI.btn_invite_message.setVisibility(View.GONE);
UI.imgv_user_rank.setVisibility(View.VISIBLE);
if (item.getRank() != null || !TextUtils.isEmpty(item.getRank())) {
//Picasso.with(G.context).load(item.getRank()).into(UI.imgv_user_rank);
}
UI.tv_person_nickname_mobile_number.setText(item.getNick_name());
//UI.ll_root.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.selector_button_actions));
if (item.getContact_image() == null || TextUtils.isEmpty(item.getContact_image())) {
Bitmap bitmap = UC.getContactPhoto(item.getMobile_number(), G.context.getContentResolver());
if (bitmap != null) {
UI.img_contact_image.setImageBitmap(bitmap);
} else {
UI.img_contact_image.setImageDrawable(G.context.getResources().getDrawable(R.drawable.no_avatar));
}
} else {
// show user avatar from web
//Picasso.with(G.context).load(item.getContact_image()).into(UI.img_contact_image);
UI.img_contact_image.setImageBitmap(BitmapFactory.decodeFile(G.DIR_IMAGE + "/" + item.getContact_image()));
}
} else {
// UI.ll_root.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.selector_invite_actions));
UI.btn_invite_message.setVisibility(View.VISIBLE);
UI.imgv_user_rank.setVisibility(View.GONE);
UI.btn_invite_message.setText(UC.getString(R.string.invite_person));
UI.btn_invite_message.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.shape_invite_button_default));
UI.tv_person_nickname_mobile_number.setText(item.getMobile_number());
Bitmap bitmap = UC.getContactPhoto(item.getMobile_number(), G.context.getContentResolver());
if (bitmap != null) {
UI.img_contact_image.setImageBitmap(bitmap);
} else {
UI.img_contact_image.setImageDrawable(G.context.getResources().getDrawable(R.drawable.no_avatar));
}
}
}
}
#Override
public Filter getFilter() {
if (filter == null) {
filter = new NameFilter();
}
return filter;
}
public class NameFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
String searchText = constraint.toString().toLowerCase();
ArrayList<ContactLists> newList = filterListBasedOnSearchText(searchText);
results.values = newList;
results.count = newList.size();
return results;
}
private ArrayList<ContactLists> filterListBasedOnSearchText(String constraint) {
ArrayList<ContactLists> newList = new ArrayList<ContactLists>();
int l = originalList.size();
for (int i = 0; i < l; i++) {
ContactLists nameList = originalList.get(i);
if (nameList.getContact_name().toString().contains(constraint)) {
newList.add(nameList);
}
}
return newList;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
categoryArrayList = (ArrayList<ContactLists>) results.values;
notifyDataSetChanged();
}
}
}
i'm very new to posting questions on this site as well as programming. Forgive me if i miss out on something or a wrong format and such. Putting my hands on android for a project, a restaurant order system. Using android eclipse to do it. I have been successful in making an app that scans QR and displays the results.
When you press scan, it opens the camera and scans a QR and displays the results under "Orders". What i haven't been able to figure out is how can i make it so that everytime i scan, it just adds a new result under the orders? Right now, everytime i scan, it replaces the current result with the new one. I want it to keep adding the results into the order.
This the current coding i have for the Main Activity
public class MainActivity extends Activity {
TextView tvResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvResult = (TextView) findViewById(R.id.tvResult);
Button scanBtn = (Button) findViewById(R.id.btnScan);
add:
scanBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
Intent intent = new Intent(
"com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE,PRODUCT_MODE");
startActivityForResult(intent, 0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "ERROR:" + e, 1).show();
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
tvResult.setText(intent.getStringExtra("SCAN_RESULT"));
} else if (resultCode == RESULT_CANCELED) {
tvResult.setText("Scan cancelled.");
}
}
}
A second question, after displaying the results which after scanning will display "51 Cheese Salami $6.90" for one result as example. The solution to the first question would allow it to be displayed as such
51 Cheese Salami $6.90
52 Charcoal Onion Beef $7.50
53 Salami Panini $6.30
and so on;
I have to send the results to a web service. What would be the best course of action? How would i be able to separate the results into specifics like ID, Name, Price. Parsing it? Adding it into a database first? Is it possible to not involve the use of database? Please correct my question if it doesn't make sense.
I suggest using ListView with custom adapter to display the results of the scan. See example here and here
ActivityMain
public class MainActivity extends Activity {
private Adapter a;
private ArrayList<Car> list;
private TabHost tabhost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListView();
}
private void addListView() {
list = new ArrayList<Car>();
// fill list view with Car objects
a = new Adapter(list, this);
final ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(a);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
list.add(new Car(/*fill with proper data*/));
adapter.notifyDataSetChanged(); // to update the listview
} else if (resultCode == RESULT_CANCELED) {
// handle somehow
}
}
}
CustomAdapter
private class Adapter extends BaseAdapter {
private ArrayList ls;
private Context c;
public Adapter(ArrayList<Car> ls, Context c) {
this.ls = ls;
this.c = c;
}
#Override
public int getCount() {
return ls.size();
}
#Override
public Object getItem(int position) {
return ls.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = null;
Container cont;
if (convertView == null) {
v = View.inflate(c, R.layout.component, null);
cont = new Container();
cont.txtName = (TextView) v.findViewById(R.id.view_name);
cont.txtPrice = (TextView) v.findViewById(R.id.view_price);
cont.txtId = (ImageView) v.findViewById(R.id.view_id);
v.setTag(cont);
} else {
v = convertView;
cont = (Container) v.getTag();
}
(cont.txtName).setText(ls.get(position).name);
(cont.txtPrice).setText(ls.get(position).price);
(cont.txtId).setText(ls.get(position).id);
return v;
}
}
private class Container {
TextView txtName, txtPrice, txtId;
}
private class Car {
String name, price;
int id;
public Car(String name, String price, int id) {
this.name = name;
this.price = price;
this.id = id;
}
}
I have this weird bug that I cannot seem to diagnose, I have 2 fields one is getting the value from the DB and the other one is not.
My problem is that "friends[position].userPresence" isn't returning any values from DB, but an Identical one called "friends[position].userStatus" is returning values, but when I assign userPresence's column name to userStatus, then userStatus is returning the correct info for the column.
Any help would be highly appreciated!
public class FriendList extends ListActivity {
private static final int ADD_NEW_FRIEND_ID = Menu.FIRST;
private static final int EXIT_APP_ID = Menu.FIRST + 1;
private IAppManager imService = null;
private FriendListAdapter friendAdapter;
public String ownusername = new String();
private class FriendListAdapter extends BaseAdapter {
class ViewHolder {
TextView text;
TextView status;
ImageView avatar;
ImageView onlstatus;
}
private LayoutInflater mInflater;
private Bitmap mOnlineIcon;
private Bitmap mOfflineIcon;
private Bitmap mAwayIcon;
private Bitmap mPersonPic;
private FriendInfo[] friends = null;
public FriendListAdapter(Context context) {
super();
mInflater = LayoutInflater.from(context);
mOnlineIcon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.online);
mOfflineIcon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.offline);
mAwayIcon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.away);
mPersonPic = BitmapFactory.decodeResource(context.getResources(),
R.drawable.no_photo_icon_big);
}
public void setFriendList(FriendInfo[] friends) {
this.friends = friends;
}
#Override
public int getCount() {
return friends.length;
}
#Override
public FriendInfo getItem(int position) {
return friends[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid
// unneccessary calls
// to findViewById() on each row.
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is
// no need
// to reinflate it. We only inflate a new View when the convertView
// supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.friend_list_screen,
null);
// Creates a ViewHolder and store references to the two children
// views
// we want to bind data to.
holder = new ViewHolder();
holder.text = (TextView) convertView
.findViewById(R.id.userName);
holder.status = (TextView) convertView
.findViewById(R.id.userStatusMsg);
holder.onlstatus = (ImageView) convertView
.findViewById(R.id.icon_status);
holder.avatar = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
// Bind the data efficiently with the holder.
holder.text.setText(friends[position].userName);
holder.onlstatus
.setImageBitmap(friends[position].userStatus == "Available" ? mOnlineIcon :
friends[position].userStatus == "Busy" ? mOfflineIcon : mAwayIcon);
holder.avatar.setImageBitmap(mPersonPic);
holder.status.setText(friends[position].userPresence);
/*
* holder.icon .setImageBitmap(friends[position].status ==
* STATUS.ONLINE ? mOnlineIcon : mOfflineIcon);
*/
return convertView;
}
}
FriendInfo
public class FriendList extends ListActivity {
private static final int ADD_NEW_FRIEND_ID = Menu.FIRST;
private static final int EXIT_APP_ID = Menu.FIRST + 1;
private IAppManager imService = null;
private FriendListAdapter friendAdapter;
public String ownusername = new String();
private class FriendListAdapter extends BaseAdapter {
class ViewHolder {
TextView text;
TextView status;
ImageView avatar;
ImageView onlstatus;
}
private LayoutInflater mInflater;
private Bitmap mOnlineIcon;
private Bitmap mOfflineIcon;
private Bitmap mAwayIcon;
private Bitmap mPersonPic;
private FriendInfo[] friends = null;
public FriendListAdapter(Context context) {
super();
mInflater = LayoutInflater.from(context);
mOnlineIcon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.online);
mOfflineIcon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.offline);
mAwayIcon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.away);
mPersonPic = BitmapFactory.decodeResource(context.getResources(),
R.drawable.no_photo_icon_big);
}
public void setFriendList(FriendInfo[] friends) {
this.friends = friends;
}
#Override
public int getCount() {
return friends.length;
}
#Override
public FriendInfo getItem(int position) {
return friends[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid
// unneccessary calls
// to findViewById() on each row.
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is
// no need
// to reinflate it. We only inflate a new View when the convertView
// supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.friend_list_screen,
null);
// Creates a ViewHolder and store references to the two children
// views
// we want to bind data to.
holder = new ViewHolder();
holder.text = (TextView) convertView
.findViewById(R.id.userName);
holder.status = (TextView) convertView
.findViewById(R.id.userStatusMsg);
holder.onlstatus = (ImageView) convertView
.findViewById(R.id.icon_status);
holder.avatar = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
// Bind the data efficiently with the holder.
holder.text.setText(friends[position].userName);
holder.onlstatus
.setImageBitmap(friends[position].userStatus == "Available" ? mOnlineIcon :
friends[position].userStatus == "Busy" ? mOfflineIcon : mAwayIcon);
holder.avatar.setImageBitmap(mPersonPic);
holder.status.setText(friends[position].userPresence);
/*
* holder.icon .setImageBitmap(friends[position].status ==
* STATUS.ONLINE ? mOnlineIcon : mOfflineIcon);
*/
return convertView;
}
}
public class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Broadcast receiver ", "received a message");
Bundle extra = intent.getExtras();
if (extra != null) {
String action = intent.getAction();
if (action.equals(IMService.FRIEND_LIST_UPDATED)) {
// taking friend List from broadcast
// String rawFriendList =
// extra.getString(FriendInfo.FRIEND_LIST);
// FriendList.this.parseFriendInfo(rawFriendList);
FriendList.this.updateData(
FriendController.getFriendsInfo(),
FriendController.getUnapprovedFriendsInfo());
}
}
}
};
public MessageReceiver messageReceiver = new MessageReceiver();
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((IMService.IMBinder) service).getService();
FriendInfo[] friends = FriendController.getFriendsInfo(); // imService.getLastRawFriendList();
if (friends != null) {
FriendList.this.updateData(friends, null); // parseFriendInfo(friendList);
}
// setTitle(imService.getUsername() + "'s friend list");
CommonUtility.setCustomTitlebar(FriendList.this, imService);
ownusername = imService.getUsername();
((LinearLayout)findViewById(R.id.actionbar_layout)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(FriendList.this,UserProfile.class));
}
});
}
#Override
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(FriendList.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.list_screen);
friendAdapter = new FriendListAdapter(this);
}
public void updateData(FriendInfo[] friends, FriendInfo[] unApprovedFriends) {
if (friends != null) {
friendAdapter.setFriendList(friends);
setListAdapter(friendAdapter);
}
if (unApprovedFriends != null) {
NotificationManager NM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (unApprovedFriends.length > 0) {
String tmp = new String();
for (int j = 0; j < unApprovedFriends.length; j++) {
tmp = tmp.concat(unApprovedFriends[j].userName).concat(",");
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher) // TODO Redo
// friend
// notification
.setContentTitle(
getText(R.string.new_friend_request_exist));
/*
* Notification notification = new
* Notification(R.drawable.stat_sample,
* getText(R.string.new_friend_request_exist),
* System.currentTimeMillis());
*/
Intent i = new Intent(this, UnApprovedFriendList.class);
i.putExtra(FriendInfo.FRIEND_LIST, tmp);
PendingIntent contentIntent = PendingIntent.getActivity(this,
0, i, 0);
mBuilder.setContentText("You have new friend request(s)");
/*
* notification.setLatestEventInfo(this,
* getText(R.string.new_friend_request_exist),
* "You have new friend request(s)", contentIntent);
*/
mBuilder.setContentIntent(contentIntent);
NM.notify(R.string.new_friend_request_exist, mBuilder.build());
} else {
// if any request exists, then cancel it
NM.cancel(R.string.new_friend_request_exist);
}
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, Messaging.class);
FriendInfo friend = friendAdapter.getItem(position);
i.putExtra(FriendInfo.USERNAME, friend.userName);
i.putExtra(FriendInfo.PORT, friend.port);
i.putExtra(FriendInfo.IP, friend.ip);
startActivity(i);
}
#Override
protected void onPause() {
unregisterReceiver(messageReceiver);
unbindService(mConnection);
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
bindService(new Intent(FriendList.this, IMService.class), mConnection,
Context.BIND_AUTO_CREATE);
IntentFilter i = new IntentFilter();
// i.addAction(IMService.TAKE_MESSAGE);
i.addAction(IMService.FRIEND_LIST_UPDATED);
registerReceiver(messageReceiver, i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
menu.add(0, ADD_NEW_FRIEND_ID, 0, R.string.add_new_friend);
menu.add(0, EXIT_APP_ID, 0, R.string.exit_application);
return result;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case ADD_NEW_FRIEND_ID: {
Intent i = new Intent(FriendList.this, AddFriend.class);
startActivity(i);
return true;
}
case EXIT_APP_ID: {
imService.exit();
finish();
return true;
}
}
return super.onMenuItemSelected(featureId, item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
The XML Handler
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
if (localName == "friend") {
FriendInfo friend = new FriendInfo();
friend.userName = attributes.getValue(FriendInfo.USERNAME);
String status = attributes.getValue(FriendInfo.STATUS);
friend.ip = attributes.getValue(FriendInfo.IP);
friend.port = attributes.getValue(FriendInfo.PORT);
friend.userPresence = attributes.getValue(FriendInfo.USER_PRESENCE);
friend.userStatus = attributes.getValue(FriendInfo.USER_STATUS);
friend.userDisplayName = attributes.getValue(FriendInfo.USER_DISPNAME);
friend.userKey = attributes.getValue(FriendInfo.USER_KEY);
friend.expire = attributes.getValue("expire");
if (status != null && status.equals("online")) {
friend.status = STATUS.ONLINE;
mOnlineFriends.add(friend);
} else if (status.equals("unApproved")) {
friend.status = STATUS.UNAPPROVED;
mUnapprovedFriends.add(friend);
} else {
friend.status = STATUS.OFFLINE;
mFriends.add(friend);
}
} else if (localName == "user") {
this.userKey = attributes.getValue(FriendInfo.USER_KEY);
} else if (localName == "message") {
MessageInfo message = new MessageInfo();
message.userid = attributes.getValue(MessageInfo.USERID);
message.sendt = attributes.getValue(MessageInfo.SENDT);
message.messagetext = attributes.getValue(MessageInfo.MESSAGETEXT);
Log.i("MessageLOG", message.userid + message.sendt
+ message.messagetext);
mUnreadMessages.add(message);
}
super.startElement(uri, localName, name, attributes);
}
FriendInfo Class
public class FriendInfo {
public static final String FRIEND_LIST = "friendList";
public static final String USERNAME = "username";
public static final String IP = "IP";
public static final String PORT = "port";
public static final String USER_KEY = "userKey";
public static final String USER_DISPNAME = "displayname";
public static final String MESSAGE = "message"; // this should not be in
// here
public static final String STATUS = "status";
public static final String USER_STATUS = "status_msg";
public static final String USER_PRESENCE = "status_msg2";
public STATUS status;
public String userStatus;
public String userPresence;
public String userDisplayName;
public String userName;
public String ip;
public String port;
public String userKey;
public String expire;
};
I don't see what the solution is. However, I would suggest you flood your program with System.out.println() statements to see what values are throughout your program. Alternately (and better) is to use your IDE's debugger and set breakpoints to examine values.