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;
}
}
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
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);
Basically I have in my Parse database two columns "rank" and "rankCount" which are both numbers.
Rank represents the total rank of the item in that row and rankCount represents the number of people who ranked it.
What I'm trying to do is create a method which will sum the average between those two, make an Int out of the number(in case its a Double/Float) and display the corresponding number with stars in a RatingBar between 1-5 stars, inside a specified Fragment with a ListView in it.
Note: I don't want to make changes in the parse database because I'm using it for the iphone version of this app witch is already complete, but I'm having a more difficult time with android.
specific Fragment class:
public class RecommendedTab extends Fragment {
ListView recommendedListView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View tab_recommended = inflater.inflate(R.layout.tab_recommended, container, false);
recommendedListView = (ListView)tab_recommended.findViewById(R.id.recommendedList);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Place");
new RemoteDataTask(){
protected void onPostExecute(List<Places> places) {
recommendedListView.setAdapter(new PlacesAdapter(getActivity(), places, null));
}
}.execute(query);
return tab_recommended;
}
}
Adapter class:
public class PlacesAdapter extends BaseAdapter{
private List<Places> places=null;
private List<Places> filteredPlaces=null;
LayoutInflater inflater;
ImageLoader imageLoader;
private Context context;
private Location loc;
public PlacesAdapter(Context context, List<Places> places, Location loc){
this.context = context;
this.places = places;
inflater = LayoutInflater.from(context);
imageLoader = new ImageLoader(context);
resetPlaces();
}
public void resetPlaces(){
filteredPlaces = places;
}
public void filter(String s){
//validation
filteredPlaces = new ArrayList<Places>();//
for(int i=0;i<places.size();i++){
if(places.get(i).getName().toLowerCase().contains(s.toLowerCase())){
filteredPlaces.add(places.get(i));
}
}
}
public class ViewHolder {
RatingBar ratingBar;
TextView name;
TextView type;
TextView adress;
TextView phone;
TextView hours;
TextView details;
ImageView image;
}
#Override
public int getCount() {
return filteredPlaces.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public Object getItem(int position) {
return filteredPlaces.get(position);
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.row_layout, null);
holder.name = (TextView)view.findViewById(R.id.placeName);
holder.type = (TextView) view.findViewById(R.id.placeType);
holder.image = (ImageView) view.findViewById(R.id.placeImage);
holder.ratingBar = (RatingBar)view.findViewById(R.id.placeRate);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.ratingBar.setOnRatingBarChangeListener(onRatingChangedListener(holder, position));
holder.ratingBar.setTag(position);
holder.ratingBar.setRating(places.get(position).getRatingStar());
holder.name.setText(places.get(position).getName());
holder.type.setText(places.get(position).getType());
imageLoader.DisplayImage(places.get(position).getImage(),
holder.image);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, PlaceDetails.class);
intent.putExtra("name", (places.get(position).getName()));
intent.putExtra("phone", (places.get(position).getPhone()));
intent.putExtra("hours", (places.get(position).getHours()));
intent.putExtra("rank", (places.get(position).getRatingStar()));
intent.putExtra("details", (places.get(position).getDetails()));
intent.putExtra("image", (places.get(position).getImage()));
context.startActivity(intent);
}
});
return view;
}
private RatingBar.OnRatingBarChangeListener onRatingChangedListener(final ViewHolder holder, final int position) {
return new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
places.get(position).setRatingStar(v);
}
};
}
}
class for the query:
public class RemoteDataTask extends AsyncTask<ParseQuery<ParseObject>, Void, List<Places>> {
#Override
protected List<Places> doInBackground(ParseQuery<ParseObject>... query) {
List<Places> places = new ArrayList<Places>();
try {
List<ParseObject> ob = query[0].find();
for (ParseObject place : ob) {
ParseFile image = (ParseFile) place.get("image");
Places p = new Places();
p.setName((String) place.get("name"));
p.setType((String) place.get("type"));
p.setHours((String) place.get("hours"));
p.setPhone((String)place.get("phone"));
p.setDetails((String) place.get("details"));
p.setImage(image.getUrl());
places.add(p);
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return places;
}
}
I have many other classes in my project but im quite sure they are irrelevant for my question.
PS: what is the android equevilant for Swift's "NSUserDefaults"?
i need to check if an item already been rated and disable the RatingBar.
There are several ways to do it, for example you can:
Add an instance variable int rank to class Place with needed setter & getter.
Using Math.round set to each Place rank rounded value of rank/rankCount, both you can get with relevant ParseObject.getDouble
And then when creating view for Place, just use it's predefined rank variable as a counter for needed stars.
Note:
it's better to use: ParseObject.getString
instead of (String) place.get("name") getting an Object and then casting to String as you did. It's also mentioned in it's Parse Documentation:
In most cases it is more convenient to use a helper function such as ParseObject.getString(String) or ParseObject.getInt(String).
Leave a comment if you need further assistance
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.
I am getting an error for #Override, and it is saying i must override or implement a supertype.
This is my code, and the bit that is giving me the error is protected void onNewIntent(Intent intent).
Thanks
public class CartListActivity extends ListActivity {
public class ProductListAdapter extends BaseAdapter {
#Override
protected void onNewIntent(Intent intent) {
String query = "";
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
//use the query to search your data
query = intent.getStringExtra(SearchManager.QUERY);
}
int catId = intent.getIntExtra(MainActivity.SELECTED_CATEGORY, 0);
if (catId != 0)
categoryId = catId;
loader = new ListViewLoader(adapter, categoryId);
if (query.length() > 0) {
loader.execute(String.format(MainActivity.WEBSERVER_GETLIST + "q=%s", categoryId, query));
}
else {
loader.execute(String.format(MainActivity.WEBSERVER_GETLIST, categoryId));
}
}
private final Context context;
private List<Product> itemList;
public List<Product> getItemList() {
return itemList;
}
public void setItemList(List<Product> itemList) {
this.itemList = itemList;
}
public Context getContext() {
return context;
}
public ProductListAdapter(Context c) {
context = c;
}
#Override
public int getCount() {
if(itemList == null) return 0;
else return itemList.size();
}
#Override
public Object getItem(int position) {
if (itemList == null) return null;
else return itemList.get(position);
}
#Override
public long getItemId(int position) {
if (itemList == null) return 0;
else return itemList.get(position).hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View cell = convertView;
if (cell == null) {
// get layout from mobile xml
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
cell = inflater.inflate(R.layout.adapter_product_list, parent, false);
}
Product p = itemList.get(position);
//set value into textview according to position
TextView textView = (TextView) cell.findViewById(R.id.product_title);
textView.setText(p.getProductName());
// add £ symbol
textView = (TextView) cell.findViewById(R.id.product_info);
textView.setText("Price: " + "£"+ p.getPrice());
//set value into imageview according to position
ImageView imgView = (ImageView) cell.findViewById(R.id.product_image);
// clear the image
imgView.setImageDrawable(null);
//and load from the network
p.loadImage(imgView, 54, 54);
return cell;
}
}
public static final Integer[] productIcons = {
0, // index 0 is empty
R.drawable.books,
R.drawable.films,
R.drawable.music,
R.drawable.games,
};
private int categoryId;
private ProductListAdapter adapter;
private ListViewLoader loader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get the category from the intent
Intent intent = getIntent();
categoryId = intent.getIntExtra(MainActivity.SELECTED_CATEGORY, 0);
adapter = new ProductListAdapter(this);
setListAdapter(adapter);
// Show the Up button in the action bar.
setupActionBar();
loader = new ListViewLoader(adapter, categoryId);
loader.execute(String.format(MainActivity.WEBSERVER_GETLIST, categoryId));
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.product_list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.show_cart:
//create the intent for the cart activity
Intent intent = new Intent(getApplicationContext(), CartActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
//create an intent
Intent intent = new Intent(this, ProductActivity.class);
Product p = (Product)adapter.getItem(position);
//specify the extra parameters we want to pass
intent.putExtra(MainActivity.SELECTED_CATEGORY, p.getCategoryId());
intent.putExtra(MainActivity.SELECTED_PRODUCTID, p.getProductId());
intent.putExtra(MainActivity.SELECTED_PRODUCTNAME, p.getProductName());
intent.putExtra(MainActivity.SELECTED_PRODUCTPRICE, p.getPrice());
intent.putExtra(MainActivity.SELECTED_SUITABLEFORKIDS, p.getSuitableForKids());
startActivity(intent);
}
}
onNewIntent is a method of Activity and can only be overridden in a class which extends Activity. You're extending it in your ProductListAdapter extending Adapter.
Please, move the code to your upper class CartListActivity in which you have declared ProductListAdapter class
public class CartListActivity extends ListActivity
{
#Override
protected void onNewIntent(Intent intent)
{
String query = "";
if (Intent.ACTION_SEARCH.equals(intent.getAction()))
{
//use the query to search your data
query = intent.getStringExtra(SearchManager.QUERY);
}
int catId = intent.getIntExtra(MainActivity.SELECTED_CATEGORY, 0);
if (catId != 0)
categoryId = catId;
loader = new ListViewLoader(adapter, categoryId);
if (query.length() > 0)
{
loader.execute(String.format(MainActivity.WEBSERVER_GETLIST + "q=%s", categoryId, query));
}
else
{
loader.execute(String.format(MainActivity.WEBSERVER_GETLIST, categoryId));
}
}
//ALL OTHER FUNCTION OF CartListActivity
public class ProductListAdapter extends BaseAdapter
{
#Override
public int getCount()
{
if(itemList == null)
return 0;
else
return itemList.size();
}
#Override
public Object getItem(int position)
{
if (itemList == null)
return null;
else
return itemList.get(position);
}
#Override
public long getItemId(int position)
{
if (itemList == null)
return 0;
else
return itemList.get(position).hashCode();
}
}
}
Method onNewIntent can only be overridden in an Activity. You're extending it in your Adapter. Can you move the method to the Activity class and try it?
The #Override annotation tells the compiler that you intend to override a method from a subclass (or interface). If you don't (e.g. because you changed the signature and no longer override), it will generate a warning. Did you change something about the signature of the method or copied/moved it from somewhere else?
Your project is configured to use JRE source level 1.4 (or lower). To solve this problem in Eclipse
Go to the Properties of the Java project in Eclipse
Go to the Java Compiler menu
Check that the Compiler Compliance Level is set to 1.5 or higher
Just want to let you know that the #Override annotation is not required to override a method.