Android create a button inside a Fragment from an Activity - java

So I am trying to pickup Java and especially Android programming. But I am pretty new to this so please have patience :-) This is probably very simple for you Android and Java experts.
What I want to accomplish is loop through all of my friends and create a button for each one of them. The looping part works, the creating of a button does not. You can see in the code what I already tried. The facebook example is using two Activities: MainActivity, PickerActivity and two Fragments: SplashFragment, SelectFragment. I have a a layout for the each Activity and each Fragment. I want to place the button on the selection.xml layout but I am not sure on how to do it. I hope I made myself clear :-)
What I did is, use the facebook sdk and the Scrumptious example I am trying to enhance the friendpicker. The example and especially the friendpicker already works. It shows all my friends I can select them and upon clicking okay I can get them using friendPickerFragment.getSelection();
code from PickerActivity.java:
friendPickerFragment.setOnDoneButtonClickedListener(
new PickerFragment.OnDoneButtonClickedListener() {
#Override
public void onDoneButtonClicked(PickerFragment<?> fragment) {
//here I am getting the selected facebook user
List<GraphUser> FriendListToPlay = friendPickerFragment.getSelection();
for (GraphUser User: FriendListToPlay) {
Log.i("info",User.getId()+' '+User.getName());
/* create button for every facebook user chosen
Button myButton = new Button(PickerActivity.this);
myButton.setText(User.getName() + " waiting for game");
LinearLayout ll = (LinearLayout)findViewById(R.id.linear_view);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
*/
}
finishActivity();
}
});
SelectionFragment:
public class SelectionFragment extends Fragment {
public static String OwnId = "";
public static GraphUser OwnUser = null;
private static final String TAG = "SelectionFragment";
private static final int REAUTH_ACTIVITY_CODE = 100;
private ProfilePictureView profilePictureView;
private TextView userNameView;
private ListView listView;
private List<BaseListElement> listElements;
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(final Session session, final SessionState state, final Exception exception) {
onSessionStateChange(session, state, exception);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.selection,
container, false);
// Find the user's profile picture custom view
profilePictureView = (ProfilePictureView) view.findViewById(R.id.selection_profile_pic);
profilePictureView.setCropped(true);
// Find the user's name view
userNameView = (TextView) view.findViewById(R.id.selection_user_name);
// Find the list view
listView = (ListView) view.findViewById(R.id.selection_list);
// Set up the list view items, based on a list of
// BaseListElement items
listElements = new ArrayList<BaseListElement>();
// Add an item for the friend picker
listElements.add(new PeopleListElement(0));
// Set the list view adapter
listView.setAdapter(new ActionListAdapter(getActivity(),
R.id.selection_list, listElements));
// Check for an open session
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// Get the user's data
makeMeRequest(session);
}
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REAUTH_ACTIVITY_CODE) {
uiHelper.onActivityResult(requestCode, resultCode, data);
} else if (resultCode == Activity.RESULT_OK) {
// Do nothing for now
}
}
private void makeMeRequest(final Session session) {
// Make an API call to get user data and define a
// new callback to handle the response.
Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// If the response is successful
if (session == Session.getActiveSession()) {
if (user != null) {
// Set the id for the ProfilePictureView
// view that in turn displays the profile picture.
profilePictureView.setProfileId(user.getId());
// Set the Textview's text to the user's name.
userNameView.setText(user.getName());
OwnId = user.getId();
OwnUser = user;
//ServiceAsyncTask task = new ServiceAsyncTask();
//task.run();
}
}
if (response.getError() != null) {
// Handle errors, will do so later.
}
}
});
request.executeAsync();
}
private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
if (session != null && session.isOpened()) {
// Get the user's data.
makeMeRequest(session);
}
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
uiHelper.onSaveInstanceState(bundle);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
private class PeopleListElement extends BaseListElement {
public PeopleListElement(int requestCode) {
super(getActivity().getResources().getDrawable(R.drawable.action_people),
getActivity().getResources().getString(R.string.action_people),
getActivity().getResources().getString(R.string.action_people_default),
requestCode);
}
#Override
protected View.OnClickListener getOnClickListener() {
return new View.OnClickListener() {
#Override
public void onClick(View view) {
startPickerActivity(PickerActivity.FRIEND_PICKER, getRequestCode());
}
};
}
#Override
protected void populateOGAction(OpenGraphAction action) {
// TODO Auto-generated method stub
}
}
private class ActionListAdapter extends ArrayAdapter<BaseListElement> {
private List<BaseListElement> listElements;
public ActionListAdapter(Context context, int resourceId, List<BaseListElement> listElements) {
super(context, resourceId, listElements);
this.listElements = listElements;
for (int i = 0; i < listElements.size(); i++) {
listElements.get(i).setAdapter(this);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater =
(LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.listitem, null);
}
BaseListElement listElement = listElements.get(position);
if (listElement != null) {
view.setOnClickListener(listElement.getOnClickListener());
ImageView icon = (ImageView) view.findViewById(R.id.icon);
TextView text1 = (TextView) view.findViewById(R.id.text1);
TextView text2 = (TextView) view.findViewById(R.id.text2);
if (icon != null) {
icon.setImageDrawable(listElement.getIcon());
}
if (text1 != null) {
text1.setText(listElement.getText1());
}
if (text2 != null) {
text2.setText(listElement.getText2());
}
}
return view;
}
}
private void startPickerActivity(Uri data, int requestCode) {
Intent intent = new Intent();
intent.setData(data);
intent.setClass(getActivity(), PickerActivity.class);
startActivityForResult(intent, requestCode);
}
public void createButton() {
}
}

Ok, this is the best I could do without fully knowing the code.
As far as I can tell, then ActionListAdapter is responsible for creating the list of friends. If I am right, then what you need to do is.
Alter res/layout/listitem, adding a Button view with an id, for examples sake let it be btn_friend
// Somewhere in res/layout/listitem
<Button
android:id="#+id/btn_friend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
Alter ActionListAdapter to set the text an listen for clicks
private class ActionListAdapter extends ArrayAdapter<BaseListElement> {
private List<BaseListElement> listElements;
public ActionListAdapter(Context context, int resourceId, List<BaseListElement> listElements) {
super(context, resourceId, listElements);
this.listElements = listElements;
for (int i = 0; i < listElements.size(); i++) {
listElements.get(i).setAdapter(this);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater =
(LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.listitem, null);
}
BaseListElement listElement = listElements.get(position);
if (listElement != null) {
view.setOnClickListener(listElement.getOnClickListener());
ImageView icon = (ImageView) view.findViewById(R.id.icon);
TextView text1 = (TextView) view.findViewById(R.id.text1);
TextView text2 = (TextView) view.findViewById(R.id.text2);
Button btn = (Button) view.findViewById(R.id.btn_friend);
if (icon != null) {
icon.setImageDrawable(listElement.getIcon());
}
if (text1 != null) {
text1.setText(listElement.getText1());
}
if (text2 != null) {
text2.setText(listElement.getText2());
}
if (btn != null) {
// I do not know exactly what text1 and text2 is
btn.setText(text1 + " waiting for game");
btn.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
Toast.makeText(getActivity(), text1+ " " + text2 + " clicked!", Toast.LENGTH_SHORT).show();
}
});
}
}
return view;
}
}
Hope I have not misunderstood how the code works.

Related

How to set up custom input dialog for saving data in Firebase when user clicks any textview widget in cardview?

In MainActivity I have NavigationDrawer. For each menu item, I have a fragment class with a corresponding layout. One of them is MyCardFragment.java. In this fragment, I am showing CardView through RecyclerView.
My CardView contains some TextViews and an ImageView. What I wanted is when a user clicks a widget it will open a custom input dialog (contains a TextView, an EditText, a positive button, and a negative button) for updating data in Firebase Real-time database. I created a dialog fragment class, but don't know how to implement it in my adapter class.
This is my main activity which holds RecyclerView and CardView:
MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth=FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
if (currentUser != null){
myRef = FirebaseDatabase.getInstance().getReference().child("user").child(currentUser.getUid());
}
mContext = MainActivity.this;
mDrawerLayout = findViewById(R.id.drawer_layout);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeAsUpIndicator(R.drawable.ic_action_name);
NavigationView navigationView = findViewById(R.id.nav_view);
//navigationView.inflateHeaderView(R.layout.nav_header);
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// set item as selected to persist highlight
menuItem.setChecked(true);
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
// Add code here to update the UI based on the item selected
// For example, swap UI fragments here
switch (menuItem.getItemId()) {
case R.id.nav_myCards:
menuItem.setChecked(true);
getSupportActionBar().setTitle("MY Cards");
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,new MyCardFragment())
.commit();
break;
return true;
}
});
mDrawerLayout.addDrawerListener(
new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// Respond when the drawer's position changes
}
#Override
public void onDrawerOpened(View drawerView) {
// Respond when the drawer is opened
}
#Override
public void onDrawerClosed(View drawerView) {
// Respond when the drawer is closed
}
#Override
public void onDrawerStateChanged(int newState) {
// Respond when the drawer motion state changes
}
}
);
navigationView.getMenu().getItem(0).setChecked(true);
//Highlighted
//onNavigationItemSelected(navigationView.getMenu().getItem(0));
setupFirebaseAuth();
if (currentUser != null){
//updateNavHeader();
}
}
Custom Dialog Fragment:
DialogCompanyAddress.java:
public class DialogCompanyAddress extends DialogFragment {
public DialogCompanyAddress() {
// Required empty public constructor
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.fragment_dialog_company_address,null));
builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//save data to the firebase
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Do
}
});
return builder.create();
}
}
finally the adapter:
RecyclerviewAdapter.java:
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyHolder> {
// ... constructor and member variables
// Usually involves inflating a layout from XML and returning the holder
Context mContext;
List<Template> listdata;
public RecyclerviewAdapter(Context context,List<Template> listdata) {
this.mContext = context;
this.listdata = listdata;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
/*// Inflate the custom layout
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview,parent,false);
// Return a new holder instance
MyHolder myHolder = new MyHolder(view);
return myHolder;*/
View view = LayoutInflater.from(mContext).inflate(R.layout.cardview,parent,false);
return new MyHolder(view);
}
public void onBindViewHolder(MyHolder holder, int position) {
holder.pname.setText(listdata.get(position).getP_name());
holder.pdesignation.setText(listdata.get(position).getP_designation());
holder.pemail.setText(listdata.get(position).getP_email());
holder.pphone.setText(listdata.get(position).getP_phone());
holder.cname.setText(listdata.get(position).getC_name());
holder.caddress.setText(listdata.get(position).getC_address());
//holder.tempID.setText(listdata.get(position).getTempID());
Glide.with(mContext).load(listdata.get(position).getC_logo()).into(holder.logo_image);
}
#Override
public int getItemCount() {
//return listdata.size();
int arr = 0;
try{
if(listdata.size()==0) {
arr = 0;
} else {
arr=listdata.size();
}
} catch (Exception e){
e.printStackTrace();
}
return arr;
}
class MyHolder extends RecyclerView.ViewHolder{
// Your holder should contain a member variable
// for any view that will be set as you render a row
TextView pname,caddress,pemail,pdesignation,pphone,cname,tempID;
ImageView logo_image;
// We also create a constructor that accepts the entire item row
// and does the view lookups to find each subview
public MyHolder(final View itemView) {
// Stores the itemView in a public final member variable that can be used
// to access the context from any ViewHolder instance.
super(itemView);
pname = (TextView) itemView.findViewById(R.id.txt_personName);
caddress = (TextView) itemView.findViewById(R.id.txt_address);
pemail = (TextView) itemView.findViewById(R.id.txt_email);
pdesignation = (TextView) itemView.findViewById(R.id.txt_designation);
pphone = (TextView) itemView.findViewById(R.id.txt_phone);
cname = (TextView) itemView.findViewById(R.id.txt_companyName);
logo_image = itemView.findViewById(R.id.imageView);
tempID = itemView.findViewById(R.id.tempID);
caddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(mContext,"Clicked on Address",Toast.LENGTH_SHORT).show();
DialogCompanyAddress address = new DialogCompanyAddress();
//address.show(getSupportFragmentManager);--->This line give me error
}
});
}
}
use a interface in your adapter like below
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyHolder> {
public interface ClickListner {
void IconClick(Template template);
}
Context mContext;
List<Template> listdata;
private final ClickListner listner;
public RecyclerviewAdapter(Context context, List<Template> listdata, ClickListner listner) {
this.mContext = context;
this.listdata = listdata;
this.listner = listner;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.cardview, parent, false);
return new MyHolder(view);
}
public void onBindViewHolder(MyHolder holder, int position) {
holder.pname.setText(listdata.get(position).getP_name());
holder.pdesignation.setText(listdata.get(position).getP_designation());
holder.pemail.setText(listdata.get(position).getP_email());
holder.pphone.setText(listdata.get(position).getP_phone());
holder.cname.setText(listdata.get(position).getC_name());
holder.caddress.setText(listdata.get(position).getC_address());
//holder.tempID.setText(listdata.get(position).getTempID());
Glide.with(mContext).load(listdata.get(position).getC_logo()).into(holder.logo_image);
holder.bind(listdata.get(position), listner);
}
#Override
public int getItemCount() {
//return listdata.size();
int arr = 0;
try {
if (listdata.size() == 0) {
arr = 0;
} else {
arr = listdata.size();
}
} catch (Exception e) {
e.printStackTrace();
}
return arr;
}
class MyHolder extends RecyclerView.ViewHolder {
TextView pname, caddress, pemail, pdesignation, pphone, cname, tempID;
ImageView logo_image;
public MyHolder(final View itemView) {
super(itemView);
pname = (TextView) itemView.findViewById(R.id.txt_personName);
caddress = (TextView) itemView.findViewById(R.id.txt_address);
pemail = (TextView) itemView.findViewById(R.id.txt_email);
pdesignation = (TextView) itemView.findViewById(R.id.txt_designation);
pphone = (TextView) itemView.findViewById(R.id.txt_phone);
cname = (TextView) itemView.findViewById(R.id.txt_companyName);
logo_image = itemView.findViewById(R.id.imageView);
tempID = itemView.findViewById(R.id.tempID);
// caddress.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// //Toast.makeText(mContext,"Clicked on
Address",Toast.LENGTH_SHORT).show();
// DialogCompanyAddress address = new DialogCompanyAddress();
// //address.show(getSupportFragmentManager);--->This line give me
error
//
// }
// });
}
public void bind(final Template template, final ClickListner Listner) {
// DeleteIcon.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// delListner.onDeleteIconClick(card, position);
// }
// });
caddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Listner.IconClick(template);
}
});
}
}
and in your fragment you need to initialize the adapter. when initialize you can override the ClickListner interface.

Sending array list of object between activities with Parcelable

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);

Move from a fragment with listview adapter to new activity base on each item selected

I have done some series of research about how to make each item of the listview in fragment activity to move to another activity having getView() from swipeListadapter. The codes below contain the tab fragment containing the swipe listadapter for the list view and the setonitemclicklistener.
public class SwipeListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieList;
private String[] bgColors;
public SwipeListAdapter(Activity tab1, List<Movie> movieList) {
this.activity = tab1;
this.movieList = movieList;
bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public Object getItem(int location) {
return movieList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_rows, null);
TextView serial = (TextView) convertView.findViewById(R.id.serial);
TextView title = (TextView) convertView.findViewById(R.id.title);
serial.setText(String.valueOf(movieList.get(position).id));
title.setText(movieList.get(position).title);
String color = bgColors[position % bgColors.length];
serial.setBackgroundColor(Color.parseColor(color));
return convertView;
}
}
The code below is my fragment tab class
public class Tab1 extends Fragment implements ViewSwitcher.ViewFactory, SwipeRefreshLayout.OnRefreshListener {
private int index;
private int[] images = new int[] { R.drawable.gallery1, R.drawable.gallery2, R.drawable.gallery3, R.drawable.gallery4, R.drawable.gallery5, R.drawable.gallery6, R.drawable.gallery7, R.drawable.gallery8 };
ImageSwitcher switcher;
android.os.Handler Handler = new Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private SwipeListAdapter adapter;
private List<Movie> movieList;
private ListView listView;
// private static final String url = "http://api.androidhive.info/json/movies.json";
private String URL_TOP_250 = "http://192.177.53.152/locator/test/refractor.php?offset=";
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;
private static final String TAG = Tab1.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View vi = inflater.inflate(R.layout.tab_1,container,false);
listView = (ListView) vi.findViewById(R.id.list);
listView.setBackgroundColor(Color.WHITE);
swipeRefreshLayout = (SwipeRefreshLayout) vi.findViewById(R.id.swipe_refresh_layout);
movieList = new ArrayList<>();
adapter = new SwipeListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
//getView().setOnClickListener();
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovies();
}
}
);
return vi;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
switch(position) {
case 1:
intent = new Intent(getActivity().getApplicationContext(), New1.class);
startActivity(intent);
break;
case 2:
intent = new Intent(getActivity().getApplicationContext(), New2.class);
startActivity(intent);
break;
default:
intent = new Intent(getActivity().getApplicationContext(), New3.class);
startActivity(intent);
}
}
});
switcher = (ImageSwitcher) getActivity().findViewById(R.id.imageSwitcher1);
switcher.setFactory(this);
switcher.setImageResource(images[index]);
switcher.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
index++;
if (index >= images.length) {
index = 0;
}
switcher.setImageResource(images[index]);
}
});
switcher.setInAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
switcher.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out));
//auto change image
Handler.post(UpdateImage);
}
#Override
public void onRefresh() {
fetchMovies();
}
private void fetchMovies() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL_TOP_250 + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("postTitle");
Movie m = new Movie(rank, title);
movieList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
Runnable UpdateImage = new Runnable() {
public void run() {
// Increment index
index++;
if (index > (images.length - 1)) {
index = 0;
}
switcher.setImageResource(images[index]);
// Set the execution after 5 seconds
Handler.postDelayed(this, (3 * 1000));
}
};
#Override
public View makeView() {
ImageView myView = new ImageView(getActivity());
myView.setScaleType(ImageView.ScaleType.FIT_CENTER);
myView.setLayoutParams(new ImageSwitcher.LayoutParams(Gallery.LayoutParams.
FILL_PARENT, Gallery.LayoutParams.FILL_PARENT));
return myView;
}
}
In a nutshell, whenever I click any of the item listview, the app crashes and system logcat is not giving any clue to that. I want to be able to click an item on the listview in d fragment and to be directed to a new activity. Any help will be appreciated. Thanks.

How to refresh list view whenever data is updated in back end by other users

I have a list view containing few fields coming from back end. One feed is 'number of likes'.
When I click on any list row it opens one activity for that row, there like button in that activity. When user presses like it get appended on server.
Now the problem is it should show incremented value in the list view when user go back to list view activity. How to do that?
NOTE: Like counter is incremented if I close the app and start it again.
I tried to call on Create method again from on Resume method but it produces duplicate copy of rows every time list view activity is remusmed.
Here is my list activity code.
public class MainActivity extends Activity {
// Session Manager Class
SessionManager session;
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "MY_URL";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
{
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setThumbnailUrl(obj.getString("image"));
movie.setTitle(obj.getString("title"));
movie.setDate(obj.getString("date"));
movie.setVideo(obj.getString("video"));
movie.setLikes(obj.getInt("likes"));
movie.setId(obj.getInt("id"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//creating unique ID
final String deviceId = Settings.Secure.getString(this.getContentResolver(),
Settings.Secure.ANDROID_ID);
Toast.makeText(this, deviceId, Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show();
/**
* Call this function whenever you want to check user login
* This will redirect user to LoginActivity is he is not
* logged in
* */
session.checkLogin();
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
// ImageView thumbNail = (ImageView)view.findViewById(R.id.thumbnail);
String title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String likes = ((TextView)view.findViewById(R.id.likes)).getText().toString();
String date = ((TextView)view.findViewById(R.id.date)).getText().toString();
String video = ((TextView) view.findViewById(R.id.video)).getText().toString();
String idd = ((TextView) view.findViewById(R.id.idd)).getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(), MovieDetailActivity.class);
// in.putExtra("THUMB", thumbNail.toString());
in.putExtra("TITLE", title);
in.putExtra("LIKES", likes);
in.putExtra("DATE", date);
in.putExtra("VIDEO", video);
in.putExtra("IDD", idd);
in.putExtra("UNIQUEID",deviceId);
//in.putExtra(TAG_URL,"url");
// in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
}
);
// Creating volley request obj
enter code here
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setThumbnailUrl(obj.getString("image"));
movie.setTitle(obj.getString("title"));
movie.setDate(obj.getString("date"));
movie.setVideo(obj.getString("video"));
movie.setLikes(obj.getInt("likes"));
movie.setId(obj.getInt("id"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView likes = (TextView) convertView.findViewById(R.id.likes);
TextView date = (TextView) convertView.findViewById(R.id.date);
TextView video = (TextView) convertView.findViewById(R.id.video);
TextView id = (TextView) convertView.findViewById(R.id.idd);
//TextView year = (TextView) convertView.findViewById(R.id.releaseYear);
// getting movie data for the row
Movie m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
// rating
date.setText(m.getDate());
video.setText(m.getVideo());
likes.setText(String.valueOf(m.getLikes()));
id.setText(String.valueOf(m.getId()));
return convertView;
// Listview on item click listener
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
Requested implementation using a SortedList and RecyclerView:
Here is the example I used to build mine.
This is my slightly more complex code that includes sorting via a SearchView in the toolbar. You can use the example in the above link if you want the example without the sorting. The control logic is in my Presenter class that manages this adapter and the Fragment:
public class AdapterInstitutionList extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
// lists to control all items and items visible after sorting
private SortedList<MInstitutionInfo> visibleList;
private ArrayList<MInstitutionInfo> allItems;
// my fragment and the presenter
private FInstitutionSelection fInstitutionSelection;
private PInstitutionList presenter;
public AdapterInstitutionList(PInstitutionList pInstitutionSelection, FInstitutionSelection fInstitutionSelection) {
// get ref to fragment, presenter, and create new callback for sortedlist
this.fInstitutionSelection = fInstitutionSelection;
presenter = pInstitutionSelection;
visibleList = new SortedList<>(MInstitutionInfo.class, new InstitutionListCallback());
allItems = new ArrayList<>();
}
// inflate your list item view here
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.listitem_institution, parent, false);
return new InstitutionViewHolder(view);
}
// on binding, you populate your list item with the values, onclickhandle, etc
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
InstitutionViewHolder institutionViewHolder = (InstitutionViewHolder) viewHolder;
final MInstitutionInfo institutionInfo = visibleList.get(position);
institutionViewHolder.setInstitutionInfo(institutionInfo);
institutionViewHolder.populateTextView();
institutionViewHolder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
presenter.onInstitutionSelected(institutionInfo);
}
});
}
#Override
public int getItemCount() {
return visibleList.size();
}
// my utility function for the presenter/fragment
public MInstitutionInfo get(int position) {
return visibleList.get(position);
}
public int add(MInstitutionInfo item) {
return visibleList.add(item);
}
public int indexOf(MInstitutionInfo item) {
return visibleList.indexOf(item);
}
public void updateItemAt(int index, MInstitutionInfo item) {
visibleList.updateItemAt(index, item);
}
public void addAll(List<MInstitutionInfo> items) {
visibleList.beginBatchedUpdates();
try {
for (MInstitutionInfo item : items) {
visibleList.add(item);
allItems.add(item);
}
} finally {
visibleList.endBatchedUpdates();
}
}
public void addAll(MInstitutionInfo[] items) {
addAll(Arrays.asList(items));
}
public boolean remove(MInstitutionInfo item) {
return visibleList.remove(item);
}
public MInstitutionInfo removeItemAt(int index) {
return visibleList.removeItemAt(index);
}
public void clearVisibleList() {
visibleList.beginBatchedUpdates();
try {
// remove items at end to remove unnecessary array shifting
while (visibleList.size() > 0) {
visibleList.removeItemAt(visibleList.size() - 1);
}
} finally {
visibleList.endBatchedUpdates();
}
}
public void clearAllItemsList() {
allItems.clear();
}
public void filterList(String queryText) {
clearVisibleList();
visibleList.beginBatchedUpdates();
try {
String constraint = queryText.toLowerCase();
for (MInstitutionInfo institutionInfo : allItems) {
if (institutionInfo.getName() != null && institutionInfo.getName().toLowerCase().contains(constraint)) {
visibleList.add(institutionInfo);
}
}
} finally {
visibleList.endBatchedUpdates();
}
}
public void clearFilter() {
if (visibleList.size() == allItems.size()) {
return;
}
clearVisibleList();
visibleList.beginBatchedUpdates();
try {
for (MInstitutionInfo institutionInfo : allItems) {
visibleList.add(institutionInfo);
}
} finally {
visibleList.endBatchedUpdates();
}
}
// the callback for the SortedList
// this manages the way in which items are added/removed/changed/etc
// mine is pretty simple
private class InstitutionListCallback extends SortedList.Callback<MInstitutionInfo> {
#Override
public int compare(MInstitutionInfo o1, MInstitutionInfo o2) {
return o1.getName().compareTo(o2.getName());
}
#Override
public void onInserted(int position, int count) {
notifyItemRangeInserted(position, count);
}
#Override
public void onRemoved(int position, int count) {
notifyItemRangeRemoved(position, count);
}
#Override
public void onMoved(int fromPosition, int toPosition) {
notifyItemMoved(fromPosition, toPosition);
}
#Override
public void onChanged(int position, int count) {
notifyItemRangeChanged(position, count);
}
#Override
public boolean areContentsTheSame(MInstitutionInfo oldItem, MInstitutionInfo newItem) {
return oldItem.getName().equals(newItem.getName());
}
#Override
public boolean areItemsTheSame(MInstitutionInfo item1, MInstitutionInfo item2) {
return item1.getName().equals(item2.getName());
}
}
// this is the view holder that is used for the list items
private class InstitutionViewHolder extends RecyclerView.ViewHolder {
public View parent;
public TextView tvName;
public MInstitutionInfo institutionInfo;
public InstitutionViewHolder(View itemView) {
super(itemView);
parent = itemView;
tvName = (TextView) itemView.findViewById(R.id.tv_institution_listitem_name);
}
public MInstitutionInfo getInstitutionInfo() {
return institutionInfo;
}
public void setInstitutionInfo(MInstitutionInfo institutionInfo) {
this.institutionInfo = institutionInfo;
}
public void populateTextView() {
if (tvName != null && institutionInfo != null && institutionInfo.getName() != null) {
tvName.setText(institutionInfo.getName());
}
}
}
You simply instantiate this adapter and assign it to your RecyclerView
myRecyclerView.setAdapter(myAdapter);
When you call any of the batched updates, the list will automatically update itself in the UI. So when you get your initial data, just call addAll(yourData) and the RecyclerView will auto populate the list. When you get updated data, you just call addAll(yourNewData) and the RecyclerView will automatically add new items and remove the new non-existent items leaving you with a fully updated list. You will need to be sure to implement the SorteList.Callback methods compare(...), areContentsTheSame(...), areItemsTheSame(...) properly to ensure that this behaves as you want it to when adding/removing items.
Please let me know if you need any more help. Frankly, this implementation type for updated and sorted data is extremely smooth.

android eclipse qr results

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;
}
}

Categories