Display images on listView without scrolling? - android

I used GridView to display images of types of batteries. When user clicks any image, the features of that particular battery will get print on next page. The images and features are fetching from the server. The problem is the first battery image is displaying when I opened the GridView, but the other battery images are displaying in that GridView only after I scroll the screen two to three times. But I want to display all the images once I opened the GridView.
private void getDatasFromIntent() {
alHM = new ArrayList<>();
Intent intent = getIntent();
String typeResp = intent.getStringExtra("IMG_S");
try {
JSONObject jsonObject = new JSONObject(typeResp);
JSONArray jsonArray = jsonObject.getJSONArray("process");
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> hm = new HashMap<>();
JSONObject bat_json = jsonArray.getJSONObject(i);
String battery_featues_id = bat_json.getString("battery_featues_id");
String battery = bat_json.getString("battery_type");
String battery_image = bat_json.getString("battery_image");
battery_image = battery_image.replace("\\", "");
hm.put("battery_featues_id", battery_featues_id);
hm.put("battery_type", battery);
hm.put("battery_image", battery_image);
alHM.add(hm);
}
// prepared arraylist and passed it to the Adapter class
mAdapter = new GridviewAdapter(this, alHM);
// Set custom adapter to gridview
GridView gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
Toast.makeText(SampleBatteryList.this, "a: " + mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public class GridviewAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> list;
private final SampleBatteryList activity;
public GridviewAdapter(SampleBatteryList sampleBatteryList,
ArrayList<HashMap<String, String>> alHM) {
this.activity = sampleBatteryList;
this.list = alHM;
Log.d("VOLLY", "ADP :" + alHM);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public class ViewHolder {
public ImageView imgViewFlag;
public TextView txtViewTitle;
public Button button;
ViewHolder view;
}
#Override
public View getView(int i, View contentView, ViewGroup viewGroup) {
Log.d("VOLLY", "INT : " + i);
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if (contentView == null) {
view = new ViewHolder();
contentView = inflator.inflate(R.layout.grid_content_sub, null);
view.txtViewTitle = (TextView)
contentView.findViewById(R.id.tv_battery_type);
view.imgViewFlag = (ImageView)
contentView.findViewById(R.id.img_battery);
view.button = (Button)
contentView.findViewById(R.id.btn_card_type);
contentView.setTag(view);
} else {
view = (ViewHolder) contentView.getTag();
view.txtViewTitle.setText(list.get(i).get("battery_type"));
view.imgViewFlag.setImageResource(R.drawable.branded_logo);
view.imgViewFlag.setImageDrawable(null);
Picasso.with(SampleBatteryList.this)
.load(Links._img + list.get(i).get("battery_image"))
.fit().centerCrop()
.into(view.imgViewFlag);
final int ii = i;
final Button btn = view.button;
view.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setText(list.get(ii).get("battery_type"));
btn.setSingleLine(true);
YoYo.with(Techniques.TakingOff).duration(2000).playOn(btn);
showDialog();
Log.d("VOLLY", "id :" +list.get(ii).get("battery_featues_id"));
callVollyForFeature(list.get(ii).get("battery_featues_id"));
}
});
}
return contentView;
}
}

here you are using view holder class but after initialization part and assign value part are in if and else so value not showing.
#Override
public View getView(int i, View contentView, ViewGroup viewGroup) {
Log.d("VOLLY", "INT : " + i);
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if (contentView == null) {
view = new ViewHolder();
contentView = inflator.inflate(R.layout.grid_content_sub, null);
view.txtViewTitle = (TextView)
contentView.findViewById(R.id.tv_battery_type);
view.imgViewFlag = (ImageView)
contentView.findViewById(R.id.img_battery);
view.button = (Button)
contentView.findViewById(R.id.btn_card_type);
contentView.setTag(view);
} else {
view = (ViewHolder) contentView.getTag();
view.txtViewTitle.setText(list.get(i).get("battery_type"));
view.imgViewFlag.setImageResource(R.drawable.branded_logo);
view.imgViewFlag.setImageDrawable(null);
Picasso.with(SampleBatteryList.this)
.load(Links._img + list.get(i).get("battery_image"))
.fit().centerCrop()
.into(view.imgViewFlag);
final int ii = i;
final Button btn = view.button;
view.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setText(list.get(ii).get("battery_type"));
btn.setSingleLine(true);
YoYo.with(Techniques.TakingOff).duration(2000).playOn(btn);
showDialog();
Log.d("VOLLY", "id :" +list.get(ii).get("battery_featues_id"));
callVollyForFeature(list.get(ii).get("battery_featues_id"));
}
});
}
return contentView;
}
change to
#Override
public View getView(int i, View contentView, ViewGroup viewGroup) {
Log.d("VOLLY", "INT : " + i);
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if (contentView == null) {
view = new ViewHolder();
contentView = inflator.inflate(R.layout.grid_content_sub, null);
view.txtViewTitle = (TextView)
contentView.findViewById(R.id.tv_battery_type);
view.imgViewFlag = (ImageView)
contentView.findViewById(R.id.img_battery);
view.button = (Button)
contentView.findViewById(R.id.btn_card_type);
contentView.setTag(view);
}else{
view = (ViewHolder) contentView.getTag();
}
view.txtViewTitle.setText(list.get(i).get("battery_type"));
view.imgViewFlag.setImageResource(R.drawable.branded_logo);
view.imgViewFlag.setImageDrawable(null);
Picasso.with(SampleBatteryList.this)
.load(Links._img + list.get(i).get("battery_image"))
.fit().centerCrop()
.into(view.imgViewFlag);
final int ii = i;
final Button btn = view.button;
view.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setText(list.get(ii).get("battery_type"));
btn.setSingleLine(true);
YoYo.with(Techniques.TakingOff).duration(2000).playOn(btn);
showDialog();
Log.d("VOLLY", "id :" +list.get(ii).get("battery_featues_id"));
callVollyForFeature(list.get(ii).get("battery_featues_id"));
}
});
return contentView;
}

Related

mproduct.remove(position) or notifyDataSetChange() does not work inside getView method

I have checked most of the places but i could not get the precise answer for this question.
problem in function : getView
What is the problem : When if condition gets true,
mproduct.remove((position));
notifyDataSetChanged();
both statement suppose to work.
// here mproduct is object of ArrayList;
If i write Log.e(); It displays promt message.
Thanks in advance.
{
public class DataAdapterCheckOut extends BaseAdapter {
Context context;
ArrayList<CheckOutProduct> mproduct;
public DataAdapterCheckOut(Context context, ArrayList<CheckOutProduct>
product){
// super(context, R.layout.activity_list_product, product);
this.context=context;
this.mproduct=product;
}
public class Holder{
TextView nameFV, mrpFV, our_priceFV, weightFv, unitFV, countFV;
ImageView pic;
int countTemp=1,mrp=0,ourPrice=0;
String name;
Button btnAdd, btnSubstract, btnAddCart;
}
#Override
public int getCount() {
return mproduct.size();
}
#Override
public Object getItem(int position) {
return mproduct.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final CheckOutProduct checkOutProduct = mproduct.get(position);
// Check if an existing view is being reused, otherwise inflate the view
SharedPreferences prefs = context.getSharedPreferences("MNA",
Context.MODE_PRIVATE);
String personalEmail = prefs.getString("personalEmail", null);
String mobTemp = prefs.getString("MNAF", null);
final Holder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new Holder();
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.activity_list_product,
parent, false);
viewHolder.nameFV = (TextView)
convertView.findViewById(R.id.txtNameViewer);
//viewHolder.idFV = (TextView)
convertView.findViewById(R.id.txtIdViewer);
viewHolder.mrpFV = (TextView)
convertView.findViewById(R.id.txtMrpViewer);
viewHolder.our_priceFV = (TextView)
convertView.findViewById(R.id.txtOurPriceViewer);
viewHolder.weightFv = (TextView)
convertView.findViewById(R.id.txtWeightViewer);
viewHolder.unitFV = (TextView)
convertView.findViewById(R.id.txtUnitViewer);
viewHolder.countFV = (TextView)
convertView.findViewById(R.id.txtViewProductCount);
viewHolder.pic = (ImageView)
convertView.findViewById(R.id.imgView);
viewHolder.btnAdd = (Button)
convertView.findViewById(R.id.buttonAdd);
viewHolder.btnSubstract = (Button)
convertView.findViewById(R.id.buttonSubstract);
viewHolder.btnAddCart = (Button)
convertView.findViewById(R.id.buttonAddCart);
convertView.setTag(viewHolder);
} else {
viewHolder = (Holder) convertView.getTag();
}
viewHolder.nameFV.setText(checkOutProduct.get_name());
viewHolder.name = checkOutProduct.get_name();
viewHolder.mrpFV.setText("MRP : " +
checkOutProduct.getMrp());
viewHolder.mrp = checkOutProduct.getMrp();
viewHolder.our_priceFV.setText("Our Price : " +
checkOutProduct.getOurPrice());
viewHolder.ourPrice = checkOutProduct.getOurPrice();
viewHolder.weightFv.setText(checkOutProduct.getWeight());
viewHolder.unitFV.setText(" " + checkOutProduct.getUnit());
viewHolder.pic.setImageBitmap(convertToBitmap(checkOutProduct.getImage()));
viewHolder.countFV.setText("" +
checkOutProduct.get_quantity());
viewHolder.countTemp = checkOutProduct.get_quantity();
viewHolder.btnAdd.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.countTemp++;
viewHolder.countFV.setText("" +
viewHolder.countTemp);
}
});
viewHolder.btnSubstract.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.countTemp--;
if (viewHolder.countTemp >= 1)
viewHolder.countFV.setText("" +
viewHolder.countTemp);
else {
Toast.makeText(context, "Sorry Item Count at
least 1", Toast.LENGTH_LONG).show();
viewHolder.countTemp = 1;
}
}
});
viewHolder.btnAddCart.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("B", "Added into Cart");
SharedPreferences prefs =
context.getSharedPreferences("MNA", Context.MODE_PRIVATE);
String personalEmail =
prefs.getString("personalEmail", null);
CheckOutDBHelper checkOutDBHelper1 = new
CheckOutDBHelper(context);
checkOutDBHelper1.addCheckOutInformation(new
CheckOutProduct(personalEmail, checkOutProduct.get_name(),
checkOutProduct.getID(), checkOutProduct.getMrp(),
checkOutProduct.getOurPrice(), checkOutProduct.getWeight(),
checkOutProduct.getUnit(), checkOutProduct.getImage(),
viewHolder.countTemp));
}
});
UserDBHelper userDBHelper = new UserDBHelper(context);
if(personalEmail!=null&&!personalEmail.equals(checkOutProduct.get_gmail()))
{
mproduct.remove(position);
notifyDataSetChanged();
}
if (mobTemp!=null&&!userDBHelper.getEmailId(mobTemp).equals(checkOutProduct.get_gmail())){
mproduct.remove((`enter code here`position));
notifyDataSetChanged();
enter code here
}
return convertView;
}
//get bitmap image from byte array
private Bitmap convertToBitmap(byte[] b){
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
}
}

Get checked items id from custom listview and pass them to new activity android

I'm developing an android app which has a custom listview with a checkbox. I want to pass all the checked items from one activity to another. how should I pass them? and where should I manage the checkbox (to get all the checked items) in the custom adapter or the activity?
Note: I retrieve all the data from my server using json response.
Here's my Model :
public class Groups {
public String name;
public boolean selected= false;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public Groups() {
}
}
My Adapter:
public class AdapterMainActivity extends BaseAdapter{
Activity activity;
private LayoutInflater inflater;
List<Groups> groupsList;
public AdapterMainActivity(Activity activity, List<Groups> groupses) {
this.activity = activity;
this.groupsList = groupses;
}
#Override
public int getCount() {
return groupsList.size();
}
#Override
public Object getItem(int position) {
return groupsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_list, null);
TextView name = (TextView) convertView.findViewById(R.id.textViewName);
final CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
final Groups groups = groupsList.get(position);
name.setText(groupsList.get(position).getName());
checkBox.setChecked(groups.selected);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
groups.selected = isChecked;
MainActivity.getInstance().updateArrayList(groupsList);
}
});
}
return convertView;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
ListView listViewGroups;
Button buttonSentToActivity;
List<Groups> groupsList;
List<Groups> resultGroupList;
ArrayList<Boolean> areChecked;
List<String> finalArray;
private AdapterMainActivity adapterMainActivity;
static MainActivity yourActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourActivity = this;
groupsList= new ArrayList<Groups>();
resultGroupList= new ArrayList<Groups>();
ReadGroup(37);
adapterMainActivity = new AdapterMainActivity(this, groupsList);
listViewGroups = (ListView) findViewById(R.id.listViewGroups);
listViewGroups.setAdapter(adapterMainActivity);
buttonSentToActivity = (Button) findViewById(R.id.buttonSendTo2Activity);
buttonSentToActivity.setOnClickListener(buttonSentToActivityListener);
Log.e("Group list size ", String.valueOf(groupsList.size()));
finalArray = new ArrayList<>();
for (int i = 0; i < resultGroupList.size(); i++) {
if (resultGroupList.get(i).selected) {
finalArray.add(resultGroupList.get(i).getName());
Log.e("final array size", String.valueOf(finalArray.size()));
}
}
}
public void ReadGroup(long cid) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray readArray = jsonObject.getJSONArray("groups");
for (int i = 0; i < readArray.length(); i++) {
Log.e("i is: ", String.valueOf(i));
JSONObject jssonRow = readArray.getJSONObject(i);
String groupName = jssonRow.getString("name");
Groups groups = new Groups();
groups.setName(groupName);
Log.e("NAME is: ", groupName);
groupsList.add(groups);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapterMainActivity.notifyDataSetChanged();
}
};
Log.e("Client id is: ", String.valueOf(cid));
ReadGroupRequesr readGroupRequest = new ReadGroupRequesr(cid, responseListener);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(readGroupRequest);
Log.e("out of the loop", "");
}
public static MainActivity getInstance() {
return yourActivity;
}
public void updateArrayList(List<Groups> arrayList) {
this.resultGroupList = arrayList;
}
View.OnClickListener buttonSentToActivityListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
//Bundle b= new Bundle();
//b.putStringArrayList("arrayList", (ArrayList<String>) finalArray);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putStringArrayListExtra("arrayList", (ArrayList<String>) finalArray);
//intent.putExtras(b);
Log.e("final array size", String.valueOf(finalArray.size()));
startActivity(intent);
}
};
}
At the very first, manage your checkboxes :
In your activity class add a boolean array or arraylist having size same as your list array size and initialize it with all value as false initially :
String[] titlesArray;
ArrayList<Boolean> arrChecked;
// initialize arrChecked boolean array and add checkbox value as false initially for each item of listview
arrChecked = new ArrayList<Boolean>();
for (int i = 0; i < titles.size(); i++) {
arrChecked.add(false);
}
Now replace your adapter class with this :
class VivzAdapter extends ArrayAdapter<String> implements OnCheckedChangeListener {
Context context;
int[] images;
String[] titlesArray, descrptionArray;
List<Integer> positions = new ArrayList<Integer>();
ArrayList<Boolean> arrChecked;
VivzAdapter(Context context, String[] titles, int[] images, String[] description, ArrayList<Boolean> arrChecked) {
super(context, R.layout.single_row, R.id.textView1, titles);
this.context = context;
this.images = images;
this.titlesArray = titles;
this.descrptionArray = description;
this.arrChecked = arrChecked;
}
class MyViewHolder {
ImageView myImage;
TextView myTitle;
TextView myDescription;
CheckBox box;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.imageView1);
myTitle = (TextView) v.findViewById(R.id.textView1);
myDescription = (TextView) v.findViewById(R.id.textView2);
box = (CheckBox) v.findViewById(R.id.checkBox1);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder holder = null;
if (row == null) {
// 1.Âștime
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//row contem RelativeLayout(root) em single_row.xml
row = inflater.inflate(R.layout.single_row, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
//Log.d("VIVZ", "Creating a new Row");
} else {
//reciclamos aqui, qeremos usar antigo objecto holder
holder = (MyViewHolder) row.getTag();
//Log.d("VIVZ", "Recycling stuff");
}
holder.myImage.setImageResource(images[position]);
holder.myTitle.setText(titlesArray[position]);
holder.myDescription.setText(descrptionArray[position]);
//set position as id
holder.box.setId(position);
//set onClickListener of checkbox rather than onCheckedChangeListener
holder.box.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
if (arrChecked.get(id)) {
//if checked, make it unchecked
arrChecked.set(id, false);
} else {
//if unchecked, make it checked
arrChecked.set(id, true);
}
}
});
//set the value of each checkbox from arrChecked boolean array
holder.box.setChecked(arrChecked.get(position));
return row;
}
}
After that, implement click listener of send button say btnSend button (I am considering that you are sending your data from one activity to another activity on click of send button) :
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<String> arrTempList = new ArrayList();
for(int i=0; i<titles.size(); i++){
if(arrChecked.get(i) == true){
arrTempList.add(titles[i]);
}
}
// here you can send your arrTempList which is having checked items only
}
});
Here's the solution for this Question:
My adapter:
public class ChooseContactsAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
public ArrayList<Contacts> contactsList;
public CheckBox checkBoxAdapter;
public ChooseContactsAdapter(Activity activity, ArrayList<Contacts> group) {
this.activity = activity;
this.contactsList = group;
}
#Override
public int getCount() {
return contactsList.size();
}
#Override
public Object getItem(int position) {
return contactsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_choose_contacts_sms,
null);
final TextView fNAme = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactFName);
TextView LName = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactLName);
checkBoxAdapter = (CheckBox) convertView.findViewById(R.id.checkBoxSelectContact);
checkBoxAdapter.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
Contacts contacts = (Contacts) cb.getTag();
contacts.setSelected(cb.isChecked());
Toast.makeText(activity.getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
}
});
final Contacts contacts = contactsList.get(position);
fNAme.setText(contacts.getContactFName());
LName.setText(contacts.getContactLName());
checkBoxAdapter.setChecked(contacts.isSelected());
checkBoxAdapter.setTag(contacts);
}
return convertView;
}
}
In my activity I have button to go from 1 activity to the 2 activity:
private View.OnClickListener buttonSubmitGroupListener =new View.OnClickListener() {
#Override
public void onClick(View view) {
List <Integer> contactsIDArray= new ArrayList<Integer>();
List<Contacts> arrayOfContacts= chooseContactsAdapter.contactsList;
for(int i=0; i< arrayOfContacts.size(); i++){
Contacts contacts= arrayOfContacts.get(i);
if(contacts.isSelected()==true){
contactsIDArray.add(contacts.getContactID());
}
}
for (int i = 0; i < contactsIDArray.size(); i++) {
Log.e("Id Array size ", String.valueOf(contactsIDArray.size()));
Log.e("Selected id ", String.valueOf(contactsIDArray.get(i)));
}
intent = new Intent(getApplicationContext(), SendSMSActivity.class);
Bundle b = new Bundle();
b.putIntegerArrayList("checkedContacts", (ArrayList<Integer>) contactsIDArray);
intent.putExtras(b);
startActivity(intent);
}
};
Second Activity add this code:
Bundle b = getIntent().getExtras();
List<Integer> result = new ArrayList<Integer>();
result = b.getIntegerArrayList("checkedContacts");

List view showing on another fragment

I'm using a view pager with a sliding panel inside, so when my panel is expanded it creates a request of users and instantiates viewholders to show them in the list view, the problem is that they get instantiated on wherever they want, how I can tell in what fragment it should be instantiated.
Here is my code:
#Override
public void onPanelAnchored(View panel) {
final View cView = panel;
EndpointInterface Service = ServiceAuthGenerator.createService(EndpointInterface.class);
currentID = sharedpreferences.getInt("CURRENTID", 0);
Call<List<Ride>> call = Service.getPassengers(currentRide);
call.enqueue(new Callback<List<Ride>>() {
#Override
public void onResponse(Response<List<Ride>> response, Retrofit retrofit) {
if (response.isSuccess() && !response.body().isEmpty()) {
dialogx.dismiss();
ArrayList<String> myUsersName = new ArrayList<>();
ArrayList<String> myUsersLastName = new ArrayList<>();
ArrayList<String> myUsersMapDirection = new ArrayList<>();
ArrayList<Integer> myUsersID = new ArrayList<>();
ArrayList<Boolean> myUsersRole = new ArrayList<>();
for (int i = 0; i < response.body().size(); i++) {
myUsersRole.add(response.body().get(i).getRole());
myUsersName.add(response.body().get(i).getUser().getFirst_name());
myUsersLastName.add(response.body().get(i).getUser().getLast_name());
myUsersMapDirection.add(getAdress(new LatLng(response.body().get(i).getOrigin_lat(), response.body().get(i).getOrigin_lng())));
myUsersID.add(response.body().get(i).getId());
currentName = myUsersName.get(i) + " " + myUsersLastName.get(i);
mMap.addMarker(new MarkerOptions().snippet(getAdress(new LatLng(response.body().get(Integer.valueOf(i)).getOrigin_lat(), response.body().get(Integer.valueOf(i)).getOrigin_lng()))).position(new LatLng(response.body().get(Integer.valueOf(i)).getOrigin_lat(), response.body().get(Integer.valueOf(i)).getOrigin_lng())).title(response.body().get(Integer.valueOf(i)).getUser().getFirst_name()).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
}
ListAdapter userAdapter = new CustomAdapterRequest(MainMenu.this, myUsersName, myUsersLastName, myUsersMapDirection, myUsersID, myUsersRole, currentRide);
ListView userListView = (ListView) cView.findViewById(R.id.listViewUserRequest);
userListView.setAdapter(userAdapter);
}
}
#Override
public void onFailure(Throwable t) {
Toast.makeText(getApplicationContext(), "no", Toast.LENGTH_SHORT).show();
}
});
}
Also, here is my adapter code:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
myViewHolder holder = null;
if (row == null) {
LayoutInflater customInflater = (LayoutInflater) contexto.getSystemService(contexto.LAYOUT_INFLATER_SERVICE);
row = customInflater.inflate(R.layout.custom_row_request, parent, false);
holder = new myViewHolder(row);
row.setTag(holder);
} else {
holder = (myViewHolder) row.getTag();
}
String singleNameItem = itemName.get(position);
String singleLastNameItem = itemLastName.get(position);
String singleDir = itemDirection.get(position);
Integer singleID = itemIDs.get(position);
Boolean singleRole = itemRoles.get(position);
holder.tv_name.setText(singleNameItem + " " + singleLastNameItem);
holder.tv_Direction.setText(singleDir);
holder.im_profilepic.setImageResource(R.mipmap.profile_photo3);
return row;
}
And my holder class.
class myViewHolder {
TextView tv_name;
TextView tv_Direction;
ImageView im_profilepic;
myViewHolder(View v) {
tv_name = (TextView) v.findViewById(R.id.nameText);
tv_Direction = (TextView) v.findViewById(R.id.originText);
im_profilepic = (ImageView) v.findViewById(R.id.ivImage);
}
}
This is the Fragment class
public class fragment1 extends Fragment {
public fragment1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
return (CardView) inflater.inflate(R.layout.layout1, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void setTextDestination(String origin, String Destination, Long Date, String estimatedTime, boolean singleRole) {
TextView tv_Destination = (TextView) getView().findViewById(R.id.TextDestination);
TextView tv_origin = (TextView) getView().findViewById(R.id.TextOrigin);
TextView tv_Date = (TextView) getView().findViewById(R.id.textDatePager);
TextView tv_EstimatedTiem = (TextView) getView().findViewById(R.id.estimatedTimeRoute);
ImageView iv_roleType = (ImageView) getView().findViewById(R.id.ImgView_roleTypeLayout1);
tv_Destination.setText(Destination);
tv_origin.setText(origin);
iv_roleType.setImageResource(singleRole ? R.mipmap.steerorange3 : R.mipmap.handorange3);
tv_EstimatedTiem.setText(estimatedTime);
java.util.Date date = new Date(Date * 1000L);
DateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
format.setTimeZone(TimeZone.getDefault());
String formatted = format.format(date);
tv_Date.setText(formatted);
}
}
I created a list of fragment1 which is mu fragment class and added it to a list, then depending on how many items on the list I have is the number of instances I get, my set text function works correctly but I don't know how to do that with the list view!
Thanks! :D
moved the method that added the list view to the fragment that was instantiated.

how to listen on click of a button in array adapter

I am adding one button per row to show off map in that row in array adapter . I want to get hold of value in that row when that button is clicked . How can I get those values on click of button .
my class:
public class MyListAdapter extends ArrayAdapter<String> {
private final Context context;
private final ArrayList<HashMap<String, ArrayList<String>>> pjclist;
private final ArrayList<PermJorneyCycleBean> pjcarraylist ;
String villagename;
int black = Color.WHITE;
float village = 20f;
float depot = 16f;
int red = Color.RED;
int count;
ArrayList<String> Deoptname;
public MyListAdapter(Context context,ArrayList<HashMap<String, ArrayList<String>>>pjcretrivelist, String [] villagename,ArrayList<PermJorneyCycleBean>itempjcarraylist) {
// public MyListAdapter(Context context,ArrayList<PermJorneyCycleBean> pjcretrivelist, String [] villagename) {
super(context, R.layout.scheduleplan,villagename);
this.context = context;
this.pjcarraylist=itempjcarraylist;
this.pjclist=pjcretrivelist;
count =pjcretrivelist.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout rowView1=null;
LinearLayout rowView=null;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (position<count){
rowView1= (LinearLayout) inflater.inflate(R.layout.scheduleplan, null, true);
rowView= (LinearLayout) rowView1.findViewById(R.id.plan);
HashMap<String, ArrayList<String>> depotlistnew = new HashMap<String, ArrayList<String>>();
depotlistnew = pjclist.get(position);
Iterator<Entry<String, ArrayList<String>>> itr = depotlistnew.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry pairs = (Map.Entry) itr.next();
villagename = pairs.getKey().toString();
createNewRow(rowView, villagename, black, village);
Deoptname = (ArrayList) pairs.getValue();
for (int i = 0; i < Deoptname.size(); i++) {
String depotname = new String();
depotname = Deoptname.get(i);
createNewRow(rowView, depotname, red, depot);
}
}
Button mapbutton = createbutton(rowView, "Locate on Map");
mapbutton.setTag(position);
mapbutton.setClickable(true);
mapbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), " This is to depot map"+villagename,Toast.LENGTH_LONG).show();
}
});
}
else if (position==count){
rowView1 = (LinearLayout) inflater.inflate(R.layout.schedulemap, null, true);
Button villagebutton = (Button)rowView1.findViewById(R.id.getBack);
villagebutton.setClickable(true);
villagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "This is for Map"+villagename,Toast.LENGTH_LONG).show();
}
});
}
else if (position==count+1)
{
rowView1 = (LinearLayout) inflater.inflate(R.layout.scheduleplanlast, null, true);
Button backbutton = (Button)rowView1.findViewById(R.id.getBackHome);
backbutton.setClickable(true);
backbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), " This is to test it",Toast.LENGTH_LONG).show();
}
});
}
return rowView1;
}
public void createNewRow(LinearLayout ll1, String value, Integer color,float size) {
TextView tv = new TextView(ll1.getContext());
tv.setTextColor(color);
tv.setTextSize(size);
tv.setText(value);
ll1.addView(tv);
}
public Button createbutton(LinearLayout ll1, String value) {
Button backbutton = new Button(ll1.getContext());
backbutton.setText(value);
backbutton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
ll1.addView(backbutton);
return backbutton;
}
public TextView createTextView(LinearLayout ll1, String value){
TextView lattextview = new TextView(ll1.getContext());
lattextview.setVisibility(0);
lattextview.setText(value);
lattextview.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
ll1.addView(lattextview);
return lattextview;
}
}
I am not able to get hold of position on click of those buttons .
For your reference i have the following code snippet for button click on Array Adapter
class MySimpleArrayAdapter extends ArrayAdapter<String> {
private Context context;
public MySimpleArrayAdapter(Context context) {
super(context, R.layout.buddy_list);
this.context = context;
}
public int getCount() {
return speedList.size();
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = vi.inflate(R.layout.speeddial_list, null);
}
TextView name = (TextView) rowView.findViewById(R.id.Name);
TextView buddyId = (TextView) rowView.findViewById(R.id.sipid);
Button btn = (Button)rowView.findViewById(R.id.speeddialbtn);
name.setText(speedList.get(position).getName());
buddyId.setText(speedList.get(position).getNumber());
btn.setText(Integer.toString(speedList.get(position).getSPDIndex()));
/*name.setText(names.get(position).toString());
buddyId.setText(buddyIds.get(position).toString());
btn.setText(numberButton.get(position).toString());*/
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (!speedList.get(0).getName().equals(" No SpeedDial Found")) {
registerForContextMenu(getListView());
getListView().showContextMenu();
} else {
unregisterForContextMenu(getListView());
}
selected_name_fromlist = speedList.get(position).getName();
selected_number_fromlist = speedList.get(position).getNumber();
System.out.println(" selected :" + selected_name_fromlist);
}
});
return rowView;
}
}
Here is a good Handling Button clicks in a ListView Row tutorial.

Android dynamic Multicolumn Listview

I have a multicolumn List view like the one shown in the image, i used custom adapters to populate this custom list.so the question is how to get data on click of submit button means when i click submit button i should get data like name, price and quantity of only checked checkbox....Thanx in advance.
In my Main xml i have a listview and in mainlist xml i have txtname, txtprice, edittext and checkbox and use efficient adapter.
i'm able to view data in list view, bt the problem is i m unable to save data on click of submit button... so plz help me out, with a sample code, bcz m new to android..
the following is my code..
public class Menu extends Activity {
ListView list;
Cursor cursorMenu;
Button btnPlaceOrder;
Button btnShowOrders;
String Descstr="";
String strtotal="";
List<String[]> lstSelectedItems = null;
DBAdapter db = new DBAdapter(this);
private String[] strName;
private String[] strPrice;
private String[] strDescription;
private class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
try {
return strName.length;
} catch (Exception e) {
//Toast.makeText(Menu.this, "No Data !", Toast.LENGTH_LONG).show();
return 0;
}
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.menulist, null);
holder = new ViewHolder();
holder.text = (TextView) convertView
.findViewById(R.id.txtItemName);
holder.text2 = (TextView) convertView
.findViewById(R.id.txtPrice);
holder.text3 = (TextView) convertView
.findViewById(R.id.txtDescription);
holder.etext3 = (EditText) convertView
.findViewById(R.id.txtQty);
holder.chk = (CheckBox) convertView
.findViewById(R.id.chkBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(strName[position]);
holder.text2.setText(strPrice[position]);
holder.text3.setText(strDescription[position]);
return convertView;
}
class ViewHolder {
TextView text;
TextView text2;
TextView text3;
EditText etext3;
CheckBox chk;
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
btnPlaceOrder = (Button) findViewById(R.id.btnPlaceOrder);
btnPlaceOrder.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
/*db.open();
cursorMenu = db.menu_getAllTitles();
int rowcount = cursorMenu.getCount();
System.out.println("---- +++++ " + rowcount);
System.out.println("---- column +++++ " + cursorMenu.getColumnCount());
int index = 0;
if (rowcount > 0) {
strName = new String[rowcount];
strPrice = new String[rowcount];
strDescription = new String[rowcount];
if (cursorMenu.moveToFirst()) {
do {
strName[index] = cursorMenu.getString(1);
strDescription[index] = cursorMenu.getString(2);
strPrice[index] = cursorMenu.getString(3);
Log.v(TAG, "Name-- " + strName[index] + "Price-- "
+ strPrice[index]);
index++;
} while (cursorMenu.moveToNext());
}
cursorMenu.close();
} else {
Toast.makeText(this, "No Data found", Toast.LENGTH_LONG).show();
}*/
list = (ListView) findViewById(R.id.lstMenu);
list.setAdapter(new EfficientAdapter(this));
System.out.println("--List Child count-----"+list.getChildCount());
System.out.println("--List count-----"+list.getCount());
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getBaseContext(),
"You clciked " + strName[arg2] + "\t" + strPrice[arg2],
Toast.LENGTH_LONG).show();
}
});
}
}
http://www.vogella.de/articles/AndroidListView/article.html go through this example you can get every thing regards listview.

Categories

Resources