I'm currently developing a delivery boy application for a grocery store. So in one screen, i need to display all the details - Customer name, address, landmark and date along with the grocery list. I'm using a list view to show all the items that need to be delivered. I want to show the customer details in the same screen. But i guess, because of the listview, the details keep getting repeated.
This is the xml file i'm using -
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="7dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/cust_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textColor="#color/bb_darkBackgroundColor"
android:textSize="18sp"
android:visibility="visible" />
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/landmark"
android:layout_marginTop="13dp"
android:text="Delivery Date"
android:textColor="#color/bb_darkBackgroundColor"
android:textSize="18sp"
android:visibility="visible" />
<TextView
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/relativeLayout"
android:layout_marginTop="37dp"
android:layout_toLeftOf="#+id/tv_quantity"
android:layout_toStartOf="#+id/tv_quantity"
android:text="Address"
android:textColor="#color/bb_darkBackgroundColor"
android:textSize="18sp"
android:visibility="visible" />
<TextView
android:id="#+id/landmark"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/relativeLayout"
android:layout_alignStart="#+id/relativeLayout"
android:layout_alignTop="#+id/relativeLayout"
android:layout_marginTop="72dp"
android:text="TextView"
android:textColor="#color/bb_darkBackgroundColor"
android:textSize="18sp"
android:visibility="visible" />
</RelativeLayout>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="200dp"
android:dividerHeight="1dp"
android:layout_above="#+id/r1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="13dp"
android:layout_marginStart="13dp"></ListView>
<RelativeLayout
android:id="#+id/r1"
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<Button
android:id="#+id/btn_order_collected"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:background="#drawable/blue_button_background"
android:text="Order Collected "
android:textAllCaps="false"
android:textColor="#android:color/white"
android:textSize="18sp"
android:layout_marginTop="31dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="24dp"
android:layout_marginStart="24dp" />
<Button
android:id="#+id/btn_go_to_map"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/btn_order_deliver"
android:layout_alignStart="#+id/btn_order_deliver"
android:layout_below="#+id/btn_order_deliver"
android:layout_marginTop="28dp"
android:background="#drawable/white_button_background"
android:text="Go To Map"
android:textAllCaps="false"
android:textColor="#color/theme_color"
android:textSize="18sp" />
<Button
android:id="#+id/call_customer"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/btn_go_to_map"
android:layout_alignBottom="#+id/btn_go_to_map"
android:layout_alignLeft="#+id/btn_order_collected"
android:layout_alignStart="#+id/btn_order_collected"
android:background="#drawable/white_button_background"
android:text="Call Customer"
android:textAllCaps="false"
android:textColor="#color/theme_color"
android:textSize="18sp" />
<Button
android:id="#+id/btn_order_deliver"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/btn_order_collected"
android:layout_marginEnd="38dp"
android:layout_marginRight="38dp"
android:background="#drawable/blue_button_background"
android:text="Delivered"
android:textColor="#color/colorWhite"
android:textSize="18sp" />
</RelativeLayout>
</RelativeLayout>
This is my order_product.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="300dp"
android:orientation="vertical"
android:padding="10dp">
<RelativeLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="21dp"
android:layout_marginStart="21dp"><![CDATA[
android:id="#+id/relativeLayout"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true">
<TextView
android:id="#+id/tv_quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/tv_no_of_item"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/tv_no_of_item"
android:text="Qty: 180 ml"
android:textColor="#android:color/black"
android:textSize="16sp" />
<TextView
android:id="#+id/tv_product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:text="Product Name"
android:textColor="#android:color/black"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_no_of_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_product_name"
android:layout_marginTop="10dp"
android:text="No. of bottle: 5"
android:textColor="#android:color/black"
android:textSize="16sp" />
</RelativeLayout>
</RelativeLayout>
This is my java file:-
public class ItemTwoFragment extends Fragment implements
AsyncResponseCurrentOrder {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private Button btn_order_collected, btn_go_to_map, btn_call_customer,
btn_order_deliver;
private OnFragmentInteractionListener mListener;
private ListView listView;
currentOrder cOrder;
public ItemTwoFragment(){}
public static ItemTwoFragment newInstance(String param1, String param2) {
ItemTwoFragment fragment = new ItemTwoFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.current_orders, container, false);
btn_order_collected = (Button)
view.findViewById(R.id.btn_order_collected);
btn_go_to_map = (Button) view.findViewById(R.id.btn_go_to_map);
btn_call_customer = (Button) view.findViewById(R.id.call_customer);
listView = (ListView) view.findViewById(R.id.listview);
btn_order_deliver = (Button) view.findViewById(R.id.btn_order_deliver);
btn_order_deliver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedpreferences =
getActivity().getSharedPreferences("MY" , Context.MODE_PRIVATE);
String driver_token =
sharedpreferences.getString("driver_token", "");
String order_no = sharedpreferences.getString("current_order_no"
, "");
new orderDeliver(getActivity(), driver_token ,
order_no).execute();
}
});
btn_order_collected.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sharedpreferences =
getActivity().getSharedPreferences("MY" , Context.MODE_PRIVATE);
String driver_token =
sharedpreferences.getString("driver_token", "");
String order_no = sharedpreferences.getString("current_order_no"
, "");
new orderPickup(getActivity(), driver_token ,
order_no).execute();
// Toast.makeText(getContext(),"Order
Collected",Toast.LENGTH_SHORT).show();
}
});
/* btn_go_to_map.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MainActivity.tabLayout.setScrollPosition(1, 0f, true);
MainActivity.viewPager.setCurrentItem(1);
}
});*/
btn_call_customer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sharedpreferences =
getActivity().getSharedPreferences("Customer" , Context.MODE_PRIVATE);
String customer_phone =
sharedpreferences.getString("customer_phone", "");
Preferences preferences= new Preferences(getContext());
String uri = "tel:" + customer_phone;
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse(uri));
startActivity(callIntent);
}
});
return view;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser){
SharedPreferences sharedpreferences =
getActivity().getSharedPreferences("MY" , Context.MODE_PRIVATE);
String driver_token = sharedpreferences.getString("driver_token",
"");
String order_no = sharedpreferences.getString("current_order_no" ,
"");
cOrder = new currentOrder(getActivity() ,driver_token , order_no);
cOrder.delegate= this;
cOrder.execute();
}
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
/* throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");*/
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void processFinish1(List<Order> cOrder) {
OrderListAdapter orderListAdapter = new OrderListAdapter(getContext(),
cOrder);
listView.setAdapter(orderListAdapter);
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private class orderPickup extends AsyncTask<String, Void, String> {
Context activity ;
String device_token , order_no;
String status = "";
public orderPickup(Context activity, String device_token, String
order_no) {
this.activity = activity;
this.device_token = device_token;
this.order_no = order_no;
}
#Override
protected String doInBackground(String... params) {
try {
String result= WebService.orderPickup(device_token , order_no,
activity);
JSONObject jsonObject = new JSONObject(result);
status = jsonObject.optString("msg");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return status;
}
#Override
protected void onPostExecute(String status) {
super.onPostExecute(status);
// MainActivity.tabLayout.setScrollPosition(1, 0f, true);
// MainActivity.viewPager.setCurrentItem(1);
Toast.makeText(activity , status , Toast.LENGTH_LONG).show();
}
}
//order deliver update
private class orderDeliver extends AsyncTask<String, Void, String> {
Context activity ;
String device_token , order_no;
String status = "";
public orderDeliver(Context activity, String device_token, String
order_no) {
this.activity = activity;
this.device_token = device_token;
this.order_no = order_no;
}
#Override
protected String doInBackground(String... params) {
try {
String result= WebService.orderDeliver(device_token , order_no,
activity);
JSONObject jsonObject = new JSONObject(result);
status = jsonObject.optString("msg");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return status;
}
#Override
protected void onPostExecute(String status) {
super.onPostExecute(status);
// MainActivity.tabLayout.setScrollPosition(1, 0f, true);
// MainActivity.viewPager.setCurrentItem(1);
Toast.makeText(activity , status , Toast.LENGTH_LONG).show();
}
}
}
class currentOrder extends AsyncTask<String, Void, List<Order>> {
public AsyncResponseCurrentOrder delegate = null;
Activity activity ;
String device_token, order_no;
ProgressDialog progressDialog;
public currentOrder(Activity activity, String device_token, String
order_no) {
this.activity = activity;
this.device_token = device_token;
this.order_no=order_no;
}
#Override
protected void onPreExecute() {
progressDialog= ProgressDialog.show(activity, "Loading. . .","Please Wait. . .", true);
super.onPreExecute();
}
#Override
protected List<Order> doInBackground(String... params) {
List<Order> orderList = new ArrayList<>();
try {
String result= WebService.orderDetails(device_token,order_no, activity);
JSONObject jsonObject = new JSONObject(result);
Log.d("Json Array", "doInBackground: "+jsonObject);
String status = jsonObject.optString("error");
if(status.equals("0")){
JSONArray jsonarray = jsonObject.getJSONArray("data");
for(int i=0;i<jsonarray.length(); i++){
//jObj.getString("address"), jObj.getString("landmark"),jObj.getString("date"),
JSONObject jObj = jsonarray.getJSONObject(i);
Order order = new Order(jObj.getString("customer_name"),jObj.getString("delivery_address1"),jObj.getString("delivery_date"), jObj.getString("delivery_landmark"), jObj.getString("product_name"), jObj.getString("variant_name") ,jObj.getInt("qty"));
SharedPreferences sharedpreferences = activity.getSharedPreferences("Customer" , Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
// editor.putString("customer_name",jObj.getString("customer_name"));
// editor.putString("date",jObj.getString("date"));
//editor.putString("landmark",jObj.getString("landmark"));
//editor.putString("address",jObj.getString("address"));
editor.putString("delivery_latitude",jObj.getString("delivery_latitude"));
editor.putString("delivery_longitude",jObj.getString("delivery_longitude"));
editor.putString("delivery_address1",jObj.getString("delivery_address1"));
editor.putString("delivery_address2",jObj.getString("delivery_address2"));
editor.putString("customer_name",jObj.getString("customer_name"));
editor.putString("customer_phone",jObj.getString("customer_phone"));
editor.commit();
orderList.add(order);
}
}
else {
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return orderList;
}
protected void onPostExecute(List<Order> orderList) {
delegate.processFinish1(orderList);
progressDialog.dismiss();
}
}
And this is my adapter:-
public class OrderListAdapter extends BaseAdapter {
Context context;
List<Order> orderList = null;
LayoutInflater layoutInflater;
boolean tickOrder = false, cancelOrder = false;
public OrderListAdapter(Context context, List<Order> orderList) {
this.context = context;
this.orderList = orderList;
layoutInflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return orderList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return orderList.get(position);
}
#Override
public long getItemId(int i) {
return i;
}
static class ViewHolder {
TextView tvProductName,tvNoOfItem,tvQuantity, tv_cust_name, tv_address,
tv_landmark, tv_date;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View view = convertView;
if (view == null) {
view = layoutInflater.inflate(R.layout.order_product, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.tv_cust_name= (TextView)view.findViewById(R.id.cust_name);
viewHolder.tv_address = (TextView) view.findViewById(R.id.address);
viewHolder.tv_landmark= (TextView)view.findViewById(R.id.landmark);
viewHolder.tv_date= (TextView)view.findViewById(R.id.date);
viewHolder.tvProductName = (TextView) view.findViewById(R.id.tv_product_name);
viewHolder.tvNoOfItem = (TextView) view.findViewById(R.id.tv_no_of_item);
viewHolder.tvQuantity = (TextView) view.findViewById(R.id.tv_quantity);
//viewHolder.cancelOrder = (ImageButton) view.findViewById(R.id.btn_cross);
//viewHolder.tickOrder = (ImageButton) view.findViewById(R.id.btn_tick);
view.setTag(viewHolder);
}
Order order = (Order) getItem(position);
final ViewHolder holder = (ViewHolder) view.getTag();
holder.tv_cust_name.setText(order.getCustomer_name());
holder.tv_address.setText(order.getAddress());
holder.tv_landmark.setText(order.getLandmark());
holder.tv_date.setText(order.getDate());
holder.tvProductName.setText(order.getProductName());
holder.tvNoOfItem.setText("Qty: " + order.getQuantity());
holder.tvQuantity.setText("Size: " + order.getVariantName());
/* holder.cancelOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!cancelOrder){
holder.cancelOrder.setBackgroundResource(R.drawable.cancel_order);
holder.tickOrder.setBackgroundResource(R.drawable.tick_inactive);
cancelOrder = true;
tickOrder = false;
}else {
holder.cancelOrder.setBackgroundResource(R.drawable.cross_inactive);
cancelOrder = false;
tickOrder = true;
}
}
});*/
/* holder.tickOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!tickOrder){
holder.tickOrder.setBackgroundResource(R.drawable.order_active);
holder.cancelOrder.setBackgroundResource(R.drawable.cross_inactive);
tickOrder = true;
cancelOrder = false;
}else {
holder.tickOrder.setBackgroundResource(R.drawable.tick_inactive);
tickOrder = false;
cancelOrder = true;
}
}
});*/
return view;
}
}
Thanks in advance!
Related
So, I have a three items in a recyclerview and I want to check if one of the field is unique or not in my case it's name. all the fields are shown correctly on the screen but whenever I call checkValidation it always returns false even when two names are not the same. I have a list and whenever I call from the activity it shows some different values as not how it is on the screen. If there is anything you didn't get kindly please comment.
dear community I really need help here..
Let me know what part you really didn't get.. :/
MainActivity.java
public MainActivity extends AppCompatActivity implements someinterface
..
..
#OnClick(R.id.activity_detailed_proceed)
void goToOrderPage() {
if (checkValidation()) {
startActivity(new Intent(MainActivity.this, Destination.class));
} else {
SameNameAlertDialogFragment sameNameAlertDialogFragment = new SameNameAlertDialogFragment();
sameNameAlertDialogFragment.show(getSupportFragmentManager(), "ERROR DIALOG");
}
}
..
..
boolean checkValidation() {
//
ArrayList<PersonFriends> personList = personAdapter.getPersonList();
ArrayList<String> namesList = new ArrayList<>();
for (int i = 0; i < personList.size(); i++) {
namesList.add(personList.get(i).getName());
System.out.println(personList.get(i).getName());
}
boolean corrent = true;
Set<String> set = new HashSet<String>(namesList);
if (set.size() < namesList.size()) {
//duplicates found
Log.d(TAG, "False was called here");
return false;
}
return true;
}
PersonAdapter personAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_selected_therapy);
ButterKnife.bind(this);
ArrayList<PersonFriends> personList = new ArrayList<>();
personAdapter = new PersonAdapter(this, this);
personRecyclerview.setAdapter(personAdapter);
personRecyclerview.setNestedScrollingEnabled(false);
personRecyclerview.setLayoutManager(new LinearLayoutManager(this));
}
some interface setup to get the name and duration
#Override
public void onPersonDetailClicked(int position, View view) {
if (view.getId() == R.id.person_name) {
adapterPosition = position;
EnterPersonDialogFragment enterPersonDialogFragment = new EnterPersonDialogFragment();
enterPersonDialogFragment.show(getSupportFragmentManager(), "PERSONS SELECTED");
}
if (view.getId() == R.id.delete_person) {
personAdapter.removeItem(position);
// personAdapter.setPersonList(personList);
// personAdapter.notifyItemRemoved(position);
}
if (view.getId() == R.id.person_duration) {
adapterPosition = position;
DurationDialogFragment durationDialogFragment = new DurationDialogFragment();
durationDialogFragment.show(getSupportFragmentManager(), "DURATION SELECTED");
}
}
#Override
public void enteredInName(String name) {
//change the list that is inside the adapter.
personAdapter.getPersonList().get(adapterPosition).setName(name);
personAdapter.notifyItemChanged(adapterPosition, PersonAdapter.PAYLOAD_NAME);
}
#Override
public void durationSelectedIs(String duration) {
personAdapter.getPersonList().get(adapterPosition).setduration(duration);
personAdapter.notifyItemChanged(adapterPosition, PersonAdapter.PAYLOAD_DURATION);
}
PersonAdapter.java
public class PersonAdapter extends RecyclerView.Adapter<PersonAdapter.PersonViewHolder> {
public static final String PAYLOAD_NAME = "PAYLOAD_NAME";
public static final String PAYLOAD_DURATION = "PAYLOAD_DURATION";
public static final String PAYLOAD_DATE = "PAYLOAD_DATE";
public static final String TAG = PersonAdapter.class.getSimpleName();
Context context;
ArrayList<PersonFriends> personList;
onPersonItemClicked onPersonItemClicked;
public PersonAdapter(Context context, onPersonItemClicked personItemClickListener) {
this.context = context;
onPersonItemClicked = personItemClickListener;
}
public void setPersonList(ArrayList<PersonFriends> personList) {
this.personList = personList;
notifyDataSetChanged();
}
public ArrayList<PersonFriends> getPersonList() {
return this.personList;
}
public void removeItem(int position) {
personList.remove(position);
notifyItemRemoved(position);
}
#NonNull
#Override
public PersonAdapter.PersonViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.item_persons_details, parent, false);
return new PersonViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PersonAdapter.PersonViewHolder holder, int position) {
PersonFriends Person = personList.get(position);
holder.personName.setText(Person.getName());
holder.personDate.setText(Person.getDate());
holder.personDuration.setText(Person.getduration());
if (position == 0) {
holder.deleteFab.hide();
}
}
#Override
public void onBindViewHolder(#NonNull PersonViewHolder holder, int position, #NonNull List<Object> payloads) {
if (!payloads.isEmpty()) {
final PersonFriends item = personList.get(position);
for (final Object payload : payloads) {
if (payload.equals(PAYLOAD_NAME)) {
// in this case only name will be updated
holder.personName.setText(item.getName());
} else if (payload.equals(PAYLOAD_DURATION)) {
// only age will be updated
holder.personDuration.setText(item.getduration());
} else if (payload.equals(PAYLOAD_DATE)) {
holder.personDate.setText(item.getDate());
}
}
} else {
// in this case regular onBindViewHolder will be called
super.onBindViewHolder(holder, position, payloads);
}
}
#Override
public int getItemCount() {
return personList.size();
}
public interface onPersonItemClicked {
void onPersonDetailClicked(int position, View view);
}
class PersonViewHolder extends RecyclerView.ViewHolder {
private final View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
onPersonItemClicked.onPersonDetailClicked(getAdapterPosition(), view);
}
};
#BindView(R.id.person_name)
TextView personName;
#BindView(R.id.person_date)
TextView personDate;
#BindView(R.id.person_duration)
TextView personDuration;
#BindView(R.id.delete_person)
FloatingActionButton deleteFab;
public PersonViewHolder(#NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
personName.setOnClickListener(onClickListener);
personDate.setOnClickListener(onClickListener);
personDuration.setOnClickListener(onClickListener);
deleteFab.setOnClickListener(onClickListener);
}
}
}
item_persons_details.xml
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center|top"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:orientation="vertical"
android:scrollbars="none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/person_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="24dp"
android:background="#drawable/bg_rounded_30"
android:padding="8dp"
android:paddingStart="16dp"
android:paddingEnd="16dp"
android:text="NAME">
</TextView>
<TextView
android:id="#+id/person_duration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:background="#drawable/bg_rounded_30"
android:drawableEnd="#drawable/ic_bottom_arrow"
android:drawablePadding="5dp"
android:padding="8dp"
android:text="DURATION">
</TextView>
<TextView
android:id="#+id/person_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:background="#drawable/bg_rounded_30"
android:drawableEnd="#drawable/ic_bottom_arrow"
android:drawablePadding="4dp"
android:padding="8dp"
android:text="MYDATE">
</TextView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/delete_person"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|center"
android:layout_margin="4dp"
android:backgroundTint="#color/colorBackground"
android:foregroundGravity="right"
android:outlineSpotShadowColor="#color/white"
android:src="#drawable/ic_bin"
android:tint="#color/colorBlack"
app:backgroundTint="#color/white"
app:fabCustomSize="30dp"
app:layout_constraintBottom_toBottomOf="#id/material_card_layout"
app:layout_constraintStart_toStartOf="#id/material_card_layout"
app:layout_constraintTop_toBottomOf="#id/material_card_layout"
app:maxImageSize="20dp" />
</LinearLayout>
</HorizontalScrollView>
I have chat app and i have fragment and show in it my friends , and currently i think to add online and offline feature next to user name in my friend fragment, I wrote the code and it working without problem , But i need to add icon online or offline next to The Full name of users, In layout i added the icons but i can't control these in code, I want if user online.. online icon set visibilty visible and offline icon set visibilty invisible and i want if user offline.. online icon set invisible and offline icon set visible.. this is my problem just!
Note: The icons is ImageView...
I wrote comment above my problems in fisrt class and in layout xml..
I have to class the first class(FriendsFragment):
public class FriendsFragment extends Fragment {
public static int setOnlineSta;
RecyclerView results_list;
DatabaseReference mUDB,mUDBSec;
FirebaseUser mCurrentUser;
FriendsAdapter friendsAdapter;
ArrayList<String> fullNameList,userStatusList, userIdList, profileImageList;
View mMainView;
public FriendsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMainView = inflater.inflate(R.layout.fragment_friends, container, false);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String current_uid = mCurrentUser.getUid();
mUDB =
FirebaseDatabase.getInstance()
.getReference().child("Friends").child(current_ui
d);
mUDB.keepSynced(true);
mUDBSec = FirebaseDatabase.getInstance().getReference();
mUDBSec.keepSynced(true);
results_list = (RecyclerView) mMainView.findViewById(R.id.users_list);
results_list.setHasFixedSize(true);
results_list.setLayoutManager(new LinearLayoutManager(getActivity()));
results_list.addItemDecoration(new DividerItemDecoration(getActivity(),
LinearLayoutManager.VERTICAL));
fullNameList = new ArrayList<>();
userStatusList = new ArrayList<>();
userIdList = new ArrayList<>();
profileImageList = new ArrayList<>();
setAdapter();
return mMainView;
}
private void setAdapter() {
mUDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
final String uid = snapshot.getKey();
DatabaseReference userRef = mUDBSec.child("Users").child(uid);
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String uidSec = uid;
userIdList.add(uidSec);
String full_name = dataSnapshot.child("name").getValue(String.class);
String user_status = dataSnapshot.child("status").getValue(String.class);
String profile_pic = dataSnapshot.child("image").getValue(String.class);
fullNameList.add(full_name);
userStatusList.add(user_status);
profileImageList.add(profile_pic);
if (dataSnapshot.hasChild("online"))
{
// My Problem Here
Boolean userOnline_Check = (Boolean)
dataSnapshot.child("online").getValue();
if (userOnline_Check == true)
{
}
if (userOnline_Check == false)
{
}
}
friendsAdapter = new FriendsAdapter(getActivity(), fullNameList,
userStatusList, userIdList, profileImageList);
results_list.setAdapter(friendsAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}}
Second Class(FriendsAdapter):
public class FriendsAdapter extends
RecyclerView.Adapter<FriendsAdapter.FriendViewHolder> {
Context context;
ArrayList<String> fullNameList,userStatusList, userIdList,profileImageList;
class FriendViewHolder extends RecyclerView.ViewHolder
{
ImageView profileImage;
ImageView active_emo, not_active_emo;
TextView full_name, user_status,user_id;
public FriendViewHolder(View itemView) {
super(itemView);
full_name = (TextView) itemView.findViewById(R.id.user_single_name);
user_status = (TextView) itemView.findViewById(R.id.username_friend);
user_id = (TextView) itemView.findViewById(R.id.user_single_id);
profileImage = (ImageView) itemView.findViewById(R.id.user_single_image);
active_emo = (ImageView) itemView.findViewById(R.id.active_state);
not_active_emo = (ImageView) itemView.findViewById(R.id.not_active_state);
}
}
public FriendsAdapter(Context context, ArrayList<String> fullNameList,
ArrayList<String> userStatusList, ArrayList<String> userIdList,
ArrayList<String> profileImageList) {
this.context = context;
this.fullNameList = fullNameList;
this.userStatusList = userStatusList;
this.userIdList = userIdList;
this.profileImageList = profileImageList;
}
#Override
public FriendsAdapter.FriendViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view =
LayoutInflater.from(context).inflate(R.layout.users_single_layout, parent,
false);
return new FriendsAdapter.FriendViewHolder(view);
}
#Override
public void onBindViewHolder(final FriendsAdapter.FriendViewHolder holder,
final int position) {
holder.full_name.setText(fullNameList.get(position));
holder.user_status.setText(userStatusList.get(position));
holder.user_id.setText(userIdList.get(position));
Glide.with(context).load(profileImageList.get(position)).into(holder.profile
Image);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence options[] = new CharSequence[]{"Open Profile", "Send message"};
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if(i == 0){
Intent profileIntent = new Intent(context, UserProfile.class);
profileIntent.putExtra("USER_ID",String.valueOf(userIdList.get(position)));
context.startActivity(profileIntent);
}
if(i == 1){
Intent chatIntent = new Intent(context, Search.class);
chatIntent.putExtra("USER_ID",String.valueOf(userIdList.get(position)));
context.startActivity(chatIntent);
}
}
});
builder.show();
}
});
}
#Override
public int getItemCount() {
return fullNameList.size();
}}
My Layout code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/user_single_image"
android:layout_width="65dp"
android:layout_height="65dp"
android:padding="2dp"
android:src="#drawable/profile_default" />
<LinearLayout
android:layout_width="233dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/user_single_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Full name"
android:textColor="#color/bluePrim"
android:textSize="20sp" />
<TextView
android:id="#+id/username_friend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="User Name" />
<TextView
android:id="#+id/user_single_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="User Id"
android:visibility="gone" />
</LinearLayout>
<-- the icons below !-->
<ImageView
android:id="#+id/active_state"
android:layout_width="20dp"
android:layout_height="20dp"
android:src="#drawable/active"
android:visibility="invisible" />
<ImageView
android:id="#+id/not_active_state"
android:layout_width="20dp"
android:layout_height="20dp"
android:src="#drawable/notactive"
android:visibility="invisible" />
</LinearLayout>
</LinearLayout>
Thank you..
I am developing an app which shows all the installed applications to user with checkboxes. I am succeed in doing so. But I am having problem in saving and retrieving the selected apps by the user. I have used ArrayList for storing selected apps, it works fine but when the app is shutdown all the items in arraylist gets remove. Then I have switched to Storage via SharedPreferences but i didn't work. Last option is to store and retrieve the applicationInfo objects via SQLite database but I dont know how to insert and retrieve an ApplicationInfo object to/from database.
Below is my code(Storage via ArrayList):
main_activity.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context="com.example.pc.fkidshell.Teen3Activity">
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:id="#+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginBottom="20dp"
android:text="Add Selected Apps"
android:width="170dp"
android:layout_alignParentBottom="true"
android:layout_gravity="center_horizontal" />
</LinearLayout>
row.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/app_icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="3dp"
android:scaleType="centerCrop" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:orientation="vertical"
android:paddingLeft="5dp" >
<TextView
android:id="#+id/app_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textStyle="bold" />
<TextView
android:id="#+id/app_paackage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
</LinearLayout>
<CheckBox
android:id="#+id/cb_app"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
main_activity.java:
public class Teen3Activity extends ListActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teen3);
Button btn1=(Button) findViewById(R.id.btn_add);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if(MyAddedapss.getAdded_apps().isEmpty())
{
Toast.makeText(getApplicationContext(), "Nothing to ADD!", Toast.LENGTH_LONG).show();
}
else
{
MyAddedapss.writeList(Teen3Activity.this,MyAddedapss.getAdded_apps());
Toast.makeText(getApplicationContext(), "Apps Added!", Toast.LENGTH_LONG).show();
}
}
});
packageManager = getPackageManager();
new LoadApplications().execute();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
ApplicationInfo app = applist.get(position);
try {
Intent intent = packageManager.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(Teen3Activity.this, e.getMessage(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(Teen3Activity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list)
{
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (null != packageManager.getLaunchIntentForPackage(info.packageName))
{
applist.add(info);
}
} catch (Exception e)
{
e.printStackTrace();
}
}
return applist;
}
private class LoadApplications extends AsyncTask<Void, Void, Void>
{
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params)
{
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(Teen3Activity.this, R.layout.row, applist);
return null;
}
#Override
protected void onCancelled()
{
super.onCancelled();
}
#Override
protected void onPostExecute(Void result)
{
setListAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(Teen3Activity.this, null, "Loading application info...");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
}
}
ApplicationAdapter.java:
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo>
{
private List<ApplicationInfo> appsList = null;
private Context context;
private PackageManager packageManager;
private ArrayList<Boolean> checkList = new ArrayList<Boolean>();
public ApplicationAdapter(Context context, int textViewResourceId, List<ApplicationInfo> appsList)
{
super(context, textViewResourceId, appsList);
this.context = context;
this.appsList = appsList;
packageManager = context.getPackageManager();
for (int i = 0; i < appsList.size(); i++) {
checkList.add(false);
}
}
#Override
public int getCount() {
return ((null != appsList) ? appsList.size() : 0);
}
#Override
public ApplicationInfo getItem(int position) {
return ((null != appsList) ? appsList.get(position) : null);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.row, null);
}
ApplicationInfo data = appsList.get(position);
if (null != data) {
TextView appName = (TextView) view.findViewById(R.id.app_name);
TextView packageName = (TextView) view.findViewById(R.id.app_paackage);
ImageView iconview = (ImageView) view.findViewById(R.id.app_icon);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.cb_app);
checkBox.setTag(Integer.valueOf(position)); // set the tag so we can identify the correct row in the listener
checkBox.setChecked(checkList.get(position));// set the status as we stored it
checkBox.setOnCheckedChangeListener(mListener); // set the listener
appName.setText(data.loadLabel(packageManager));
packageName.setText(data.packageName);
iconview.setImageDrawable(data.loadIcon(packageManager));
}
return view;
}
CompoundButton.OnCheckedChangeListener mListener = new CompoundButton.OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
checkList.set((Integer)buttonView.getTag(),isChecked); // get the tag so we know the row and store the status
if(isChecked)
{
int addapppos = (Integer) buttonView.getTag();
ApplicationInfo p=appsList.get(addapppos);
MyAddedapss.setAdded_apps(p);
buttonView.setEnabled(false);
}
}
};
}
MyAddedApps.java: (class for storing the selected Apps by user)
public class MyAddedapss extends Application
{
private static ArrayList<ApplicationInfo> added_apps=new ArrayList<ApplicationInfo>();
public static void setAdded_apps(ApplicationInfo element)
{
added_apps.add(element);
}
public static ArrayList<ApplicationInfo> getAdded_apps()
{
return added_apps;
}
public static boolean remove_app(ApplicationInfo element)
{
return added_apps.remove(element);
}
}
But I am having problem in saving and retrieving the selected apps by the user
Save their package names to a SQLite database, SharedPreferences, or some other form of file (e.g., JSON).
Last option is to store and retrieve the applicationInfo objects via SQLite database but I dont know how to insert and retrieve an ApplicationInfo object to/from database
You can't. You save their package names. Then, on a future run of your app, you load those package names and get the ApplicationInfo objects from Android via PackageManager for those package names.
I have ViewPager that containing 3 different Fragment. each Fragment containing A Different View and also ListView, I got a problem when I was trying to show the ListView in one of Fragment from ViewPager, it doesn't show anything. I've tried to debug my adapter and it seems my getView() method is not called. I try to call my Fragment not from ViewPager, the result is getView() is called from adapter and ListView is showing. Is there any problem to show ListView from ViewPager? I have tried this solution by calling my adapter from onViewCreated() but there's nothing change. so is there any wrong with my method? this is my code :
My Fragment Class for Managing ViewPager
public class Frag_Provider extends Fragment {
private String[] tabsTitles = {"TERDEKAT", "SEMUA", "PROVIDERKU"};
String url = "";
List<ModelProvider> list_provider;
DB_Esehat db_esehat = null;
SQLiteDatabase db = null;
ContentLoadingProgressBar progressbar;
TabLayout tabLayout;
ViewPager pager;
public Frag_Provider (){
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
((MainActivity) getActivity()).custom_toolbar("Provider", R.color.toolbar_provider, R.color.toolbar_provider_dark);
View result=inflater.inflate(R.layout.fragment_provider, container, false);
list_provider = new ArrayList<ModelProvider>();
progressbar = (ContentLoadingProgressBar)result.findViewById(R.id.progressbar);
db_esehat = new DB_Esehat(getActivity());
db = db_esehat.getWritableDatabase();
db.delete("LST_PROVIDER", null, null);
pager=(ViewPager)result.findViewById(R.id.pager);
tabLayout = (TabLayout)result.findViewById(R.id.sliding_tabs);
url = getResources().getString(R.string.url_host)+getResources().getString(R.string.url_provider);
new ProviderTask(url).execute();
pager.setAdapter(buildAdapter(tabsTitles));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(pager);
}
});
return(result);
}
public class ProviderTask extends AsyncTask<String, Void, String> {
String url = "";
public ProviderTask(String url) {
this.url = url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressbar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
String result = "";
try {
result = Connection.get(url);
} catch (Exception e) {
result = "";
}
return result;
}
#Override
protected void onPostExecute(String result) {
progressbar.setVisibility(View.GONE);
pager.setVisibility(View.VISIBLE);
tabLayout.setVisibility(View.VISIBLE);
super.onPostExecute(result);
if (result.equals("") || result.equals(null)) {
MethodSupport.AlertDialog(getActivity());
} else {
try {
JSONArray Data = new JSONArray(result);
for (int i = 0; i < Data.length(); i++) {
String LSKA_NOTE = "";
String RSALAMAT = "";
String RSTELEPON = "";
String RSNAMA = "";
String MAPPOS = "";
int RSTYPE = 0;
int RSID = 0;
int RS_NTT = 0;
JSONObject json = Data.getJSONObject(i);
if (json.has("LSKA_NOTE")) {
LSKA_NOTE = json.getString("LSKA_NOTE");
}
if (json.has("RSALAMAT")) {
RSALAMAT = json.getString("RSALAMAT");
}
if (json.has("RSTELEPON")) {
RSTELEPON = json.getString("RSTELEPON");
}
if (json.has("RSNAMA")) {
RSNAMA = json.getString("RSNAMA");
}
if (json.has("MAPPOS")) {
MAPPOS = json.getString("MAPPOS");
}
if (json.has("RSTYPE")) {
RSTYPE = json.getInt("RSTYPE");
}
if (json.has("RSID")) {
RSID = json.getInt("RSID");
}
if (json.has("RS_NTT")) {
RS_NTT = json.getInt("RS_NTT");
}
db_esehat.InsertRS(LSKA_NOTE, RSALAMAT, RSTELEPON, RSNAMA, MAPPOS, RSTYPE, RSID, RS_NTT);
}
} catch (Exception e) {
Log.d("TES", e.getMessage());
}
}
}
}
private PagerAdapter buildAdapter(String[] tabsTitles) {
return(new FragmentStatePagerAdapter(getActivity(), getChildFragmentManager(),tabsTitles));
}
}
This is FragmentStatePagerAdapter.java
public class FragmentStatePagerAdapter extends FragmentPagerAdapter {
Context ctxt=null;
private String[] tabsTitles;
public FragmentStatePagerAdapter(Context ctxt, FragmentManager mgr, String[] tabsTitles) {
super(mgr);
this.ctxt=ctxt;
this.tabsTitles = tabsTitles;
}
#Override
public int getCount() {
return tabsTitles.length;
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return Frag_Provider_Terdekat.newInstance(position);
case 1:
return Frag_Provider_Semua.newInstance(position);
case 2:
return Frag_Provider_Ku.newInstance(position);
}
return null;
}
// #Override public float getPageWidth(int position) { return(0.7f); }
#Override
public String getPageTitle(int position) {
return tabsTitles[position];
}
}
this is my Fragment_Provider.xml, Layout for managing my ViewPager
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"
android:indeterminate="false" />
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
app:tabMode="fixed"
android:fillViewport="true"
android:visibility="gone" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white"
android:layout_below="#id/sliding_tabs"
android:visibility="gone"/>
</RelativeLayout>
This is of my Fragment in ViewPagerthat containing ListView :
public class Frag_Provider_Terdekat extends Fragment {
private static final String KEY_POSITION="position";
private ListView list_provider;
List<ModelProviderTerdekat> list_ekamedicare;
DB_Esehat db_esehat;
SQLiteDatabase db;
ProviderTerdekatAdapter adapter;
static Frag_Provider_Terdekat newInstance(int position) {
Frag_Provider_Terdekat frag=new Frag_Provider_Terdekat();
Bundle args=new Bundle();
args.putInt(KEY_POSITION, position);
frag.setArguments(args);
return(frag);
}
static String getTitle(Context ctxt, int position) {
return("PROVIDER KU");
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View result=inflater.inflate(R.layout.fragment_child_providerterdekat, container, false);
list_provider = (ListView)result.findViewById(R.id.list_provider);
list_ekamedicare = new ArrayList<ModelProviderTerdekat>();
db_esehat = new DB_Esehat(getActivity());
list_ekamedicare = db_esehat.getProvider();
adapter = new ProviderTerdekatAdapter(getActivity().getApplicationContext(), R.layout.adapter_provider, list_ekamedicare);
list_provider.setAdapter(adapter);
return result;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
and this is Adapter for my ListView
public class ProviderTerdekatAdapter extends ArrayAdapter<ModelProviderTerdekat> {
List<ModelProviderTerdekat> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
static class ViewHolder {
ImageView imvprov_map;
ImageView imvprov_fav;
TextView textprov_nama_rs;
TextView textprov_alamat_rs;
TextView textprov_km_rs;
}
public ProviderTerdekatAdapter (Context context, int viewResourceId, List<ModelProviderTerdekat> data) {
super(context, R.layout.adapter_provider, data);
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = inflater.inflate(R.layout.adapter_provider, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.imvprov_map = (ImageView) view.findViewById(R.id.imvprov_map);
viewHolder.imvprov_fav = (ImageView) view.findViewById(R.id.imvprov_fav);
viewHolder.textprov_nama_rs = (TextView) view.findViewById(R.id.textprov_nama_rs);
viewHolder.textprov_alamat_rs = (TextView) view.findViewById(R.id.textprov_alamat_rs);
viewHolder.textprov_km_rs = (TextView) view.findViewById(R.id.textprov_km_rs);
view.setTag(viewHolder);
}
ViewHolder viewHolder = (ViewHolder) view.getTag();
viewHolder.textprov_nama_rs.setText(data.get(position).getRSNAMA());
viewHolder.textprov_alamat_rs.setText(data.get(position).getRSALAMAT());
return view;
}
}
I have no Idea why my GetView() not called in my Adapter, is it because I put in ViewPager? well I hope someone understand about it and help me to solver my problem. thank you very much.
Finally.. I found a solution for my problem, it's because I put ViewPager in RelativeLayout after I change into LinearLayout all view displayed as I wanted
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"
android:indeterminate="false" />
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
app:tabMode="fixed"
android:fillViewport="true"
android:visibility="gone" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white"
android:layout_below="#id/sliding_tabs"
android:visibility="gone"/>
</LinearLayout>
I need help with a project in Android where I'm working. I have an AsyncTask that external data collected through the internet with a custom adapter.
My view currently has a view that is generated by the adapter and outside of it, contains a button. I would like to press that button give me current information from view as for example the name of the element.
MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ebebeb"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#drawable/header" >
<TextView
android:layout_width="fill_parent"
android:layout_height="55dp"
android:gravity="center_vertical"
android:paddingLeft="35dp"
android:text="Menú"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFF" />
<TextView
android:id="#+id/openmenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:background="#drawable/ic_action_overflow"
android:clickable="true"
android:contentDescription="Desc"
android:visibility="visible" />
<TextView
android:id="#+id/love"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/ic_action_love"
android:clickable="true"
android:contentDescription="Desc"
android:visibility="visible" />
<TextView
android:id="#+id/refresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/love"
android:layout_alignBottom="#+id/love"
android:layout_marginRight="5dp"
android:layout_toLeftOf="#+id/love"
android:background="#drawable/ic_action_refresh"
android:clickable="true"
android:contentDescription="Desc"
android:visibility="visible" />
</RelativeLayout>
<com.unomasdelafamilia.sevilla.CardContainer
android:id="#+id/layoutview"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#ebebeb" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center" >
<Button
android:id="#+id/infobtn"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/lovebtn"
android:background="#drawable/love" />
</RelativeLayout>
</LinearLayout>
MainActivity.class
private class JSONParse extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
mCardContainer = (CardContainer) findViewById(R.id.layoutview);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Obteniendo datos ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONfromURL(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json != null){
pDialog.dismiss();
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
for (int i = 0; i < user.length(); i++) {
JSONObject c = user.getJSONObject(i);
String id = c.getString(TAG_ID);
String image = c.getString(imagen);
adapter.add(new CardModel(id, "Sevilla", image));
}
mCardContainer.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}else{
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "Compruebe su conexión e inténtelo de nuevo más tarde", Toast.LENGTH_SHORT).show();
//No hay datos
}
}
CardModel.class
public class CardModel {
private String title;
private String description;
//private Drawable cardImageDrawable;
private String image;
/* private Drawable cardLikeImageDrawable;
private Drawable cardDislikeImageDrawable;*/
private OnCardDimissedListener mOnCardDimissedListener = null;
private OnClickListener mOnClickListener = null;
public interface OnCardDimissedListener {
void onLike();
void onDislike();
}
public interface OnClickListener {
void OnClickListener();
}
/*public CardModel(String string, Drawable drawable) {
this(null, null, null);
}*/
public CardModel(String title, String description, String image) {
this.title = title;
this.description = description;
//this.cardImageDrawable = cardImage;
this.image = image;
}
public CardModel(String title, String description, Bitmap cardImage) {
this.title = title;
this.description = description;
//this.cardImageDrawable = new BitmapDrawable(null, cardImage);
}
public CardModel(HashMap<String, String> map) {
this.title = title;
this.description = description;
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public String getImage(){
return image;
}
public void setDescription(String description) {
this.description = description;
}
public void setImage(String image) {
this.image = image;
}
/*public Drawable getCardLikeImageDrawable() {
return cardLikeImageDrawable;
}
public void setCardLikeImageDrawable(Drawable cardLikeImageDrawable) {
this.cardLikeImageDrawable = cardLikeImageDrawable;
}
public Drawable getCardDislikeImageDrawable() {
return cardDislikeImageDrawable;
}
public void setCardDislikeImageDrawable(Drawable cardDislikeImageDrawable) {
this.cardDislikeImageDrawable = cardDislikeImageDrawable;
}
*/
/* public void setOnCardDimissedListener( OnCardDimissedListener listener ) {
this.mOnCardDimissedListener = listener;
}
public OnCardDimissedListener getOnCardDimissedListener() {
return this.mOnCardDimissedListener;
}
public void setOnClickListener( OnClickListener listener ) {
this.mOnClickListener = listener;
}
public OnClickListener getOnClickListener() {
return this.mOnClickListener;
}*/
}
SimpleCardStackAdapter.java
public final class SimpleCardStackAdapter extends CardStackAdapter {
public SimpleCardStackAdapter(Context mContext) {
super(mContext);
}
#Override
public View getCardView(int position, CardModel model, View convertView, ViewGroup parent) {
if(convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.std_card_inner, parent, false);
assert convertView != null;
}
int loader = R.drawable.ic_launcher;
ImageView image = (ImageView) convertView.findViewById(R.id.sp_image);
ImageLoader imgLoader = new ImageLoader(mContext);
//((ImageView) convertView.findViewById(R.id.sp_image)).setImageDrawable(model.getImage());
((TextView) convertView.findViewById(R.id.textView1)).setText(model.getTitle());
((TextView) convertView.findViewById(R.id.textView2)).setText(model.getDescription());
imgLoader.DisplayImage(model.getImage(), loader, image);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getContext(), "Pulsado", Toast.LENGTH_SHORT).show();
((ViewManager)v.getParent()).removeView(v);
}
});
return convertView;
}
}
In short, how I can get ítem information when the button is pressed. Thank you very much to all, Greetings
You should use the tag property of views in Android.
So, you can dynamically set the tag like
String item = "item";
Button button = findViewById(R.id.Button);
button.setTag(item);
where and whenever is appropriate in you code.
Then, you can retrieve the tag when clicked like
#Override
public void onClick(View button) {
String myString = (String) button.getTag();
}
Update
After understanding OPs requirement.
In your overridden getCardView handler, after you instantiate the ImageView like
ImageView image = (ImageView) convertView.findViewById(R.id.sp_image);
set its tag from the model object like
image.setTag(model.getTitle());
then, in your click handler, get the tag of the ImageView like
#Override
public void onClick(View button) {
ImageView image = (ImageView) getView().findViewById(R.id.sp_image);
String item = (String)image.getTag();
}