getting data from Textviews in listview - java

i am trying to get data from Textviews in a listview after has been modified by the user.
So then the user click on the row the "descrec" Textview will changed to "completed"
listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
TextView text2 = (TextView) view.findViewById(R.id.descrec);
if(text2.getText().toString().equals("Selected"))
{
text2.setText(Outstanding.outDesc[(int)id]);
}
else
{
text2.setText("Selected");
}
Log.i("you selected row number",String.valueOf(id));
}
});
once user finish selecting rows and hit the "submit" button i should print all the rows with "selected" String in "descrec" Textview but it's printing nothing.
public void submit (View view)
{
for (int i = 0; i < listView.getCount(); i++)
{
v = listView.getAdapter().getView(i, null, null);
TV = (TextView) v.findViewById(R.id.descrec);
if (TV.getText().toString().equals("Selected"))
{
//just to make sure descrec text has beeen changed somewhere
Log.i("descrec", (String) TV.getText());
}
//to check the Textview anyway
Log.i("descrec value", (String) TV.getText());
}
}
and the result of printing the whole rows' "descrec" giving the original values of the Textview before the user changed it to "Selected".
Here is the results after selecting rows and hitting submit button.
here is the full code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_outstanding);
new MyAsync().execute();
}
class MyAsync extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
Log.i("preexcute","first");
listView = (ListView)findViewById(R.id.listviewout);
Contactadapter2 = new contactadapter2(Outstanding.this , R.layout.rowrecord_layout);
listView.setAdapter(Contactadapter2);
BackgroundWorker Backgroundworker = new BackgroundWorker(Outstanding.this);
Backgroundworker.execute(type,Homescreen.userID);
}
#Override
protected Void doInBackground(Void... arg0) {
return null;
}
#Override
protected void onPostExecute(final Void unused) {
Log.i("postexcute","second");
for (int i = 0; i < outrecieptID.length; i++) {
Log.i("test", valueOf(i) + "out of" + valueOf(outrecieptID.length));
Contacts2 contacts2 = new Contacts2(Outstanding.outrecieptID[i], Outstanding.outAmount[i], Outstanding.outDesc[i]);
Contactadapter2.add(contacts2);
}
for(int i=0 ; i < listView.getCount() ; i++) {
v[i] = listView.getAdapter().getView(i, null, null);
}
listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
TextView text2 = (TextView) view.findViewById(R.id.descrec);
TV = (TextView) v[(int)id].findViewById(R.id.descrec);
if(text2.getText().toString().equals("Selected"))
{
text2.setText(Outstanding.outDesc[(int)id]);
}else
{
text2.setText("Selected");
TV.setText("Selected");
}
Log.i("you selected row number",String.valueOf(id));
}
});
}
}
public void submit (View view)
{
for (int i = 0; i < listView.getCount(); i++) {
// v = listView.getAdapter().getView(i, null, null);
TV = (TextView) v[i].findViewById(R.id.descrec);
if (TV.getText().toString().equals("Selected"))
{
//just to make sure descrec text has beeen changed somewhere
Log.i("descrec", (String) TV.getText());
}
//to see the Textview anyway
Log.i("descrec value", (String) TV.getText());
}
}
Here is the contactadapter code :
public class contactadapter2 extends ArrayAdapter {
List list= new ArrayList();
public contactadapter2(Context context, int resource) {
super(context, resource);
}
public void add(Contacts2 object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row=convertView;
ContentHolder contentHolder;
if(row==null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.rowrecord_layout,parent,false);
contentHolder = new ContentHolder();
contentHolder.recieptidout=(TextView) row.findViewById(R.id.recieptidrec);
contentHolder.amountout= (TextView) row.findViewById(R.id.amountrec);
contentHolder.descout= (TextView) row.findViewById(R.id.descrec);
row.setTag(contentHolder);
}
else
{
contentHolder = (ContentHolder)row.getTag();
}
Contacts2 contacts2 = (Contacts2) this.getItem(position);
contentHolder.recieptidout.setText(contacts2.getrecieptidrec());
contentHolder.amountout.setText(contacts2.getamountrec());
contentHolder.descout.setText(contacts2.getdescrec());
return row;
}
static class ContentHolder
{
TextView recieptidout,amountout,descout;
}

You should update the model with the "Selected" Text . Otherwise it wont work . Because when you call v = listView.getAdapter().getView(i, null, null) It will bind the data from your arraylist . So it will change your text that you set in the itemclick listener.
try to change some thing like this,
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView text2 = (TextView) view.findViewById(R.id.descrec);
if(text2.getText().toString().equals("Selected"))
{
text2.setText(Outstanding.outDesc[(int)id]);
}
else
{
text2.setText("Selected");
}
Contacts2 contacts2 = parent.getAdapter().getItem(position);
contacts2.setdescrec(text2.getText().toString());
Log.i("you selected row number",String.valueOf(id));
}
});

Related

How avoid refresh checkbox while expand list in android

I'm making NLevel expandable list using listview. I've added checkbox only last level data in list view. I have stuck in below scenario.
If I check checkbox then when I expand listview means checkbox gets automatically unchecked.I don't want it to be like that. If I checked checkbox it should stay checked until I uncheck manually.
Please anyone help me!! It's been two days I stuck here.
Here goes my code:
MainActivity.java
public class MainActivity extends Activity {
List<NLevelItem> list;
ListView listView;
Context context;
Button checkButton;
ArrayList<String>tempList;
CheckBox selected = null; //Make only one selection at a time
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
list = new ArrayList<NLevelItem>();
context = this;
checkButton = (Button)findViewById(R.id.buttons);
tempList = new ArrayList<String>();
//here we create 5 grandparent (top level) NLevelItems
//then foreach grandparent create a random number of parent (second level) NLevelItems
//then foreach parent create a random number of children (third level) NLevelItems
//we pass in an anonymous instance of NLevelView to the NLevelItem, this NLevelView is
//what supplies the NLevelAdapter with a View for this NLevelItem
Random rng = new Random();
final LayoutInflater inflater = LayoutInflater.from(this);
for (int i = 0; i < 5; i++) {
final NLevelItem grandParent = new NLevelItem(new SomeObject("GrandParent "+i),null, new NLevelView() {
#Override
public View getView(NLevelItem item) {
View view = inflater.inflate(R.layout.list_item, null);
TextView tv = (TextView) view.findViewById(R.id.textView);
//tv.setBackgroundColor(Color.GREEN);
String name = (String) ((SomeObject) item.getWrappedObject()).getName();
tv.setText(name);
return view;
}
});
list.add(grandParent);
int numChildren = rng.nextInt(4) + 1;
for (int j = 0; j < numChildren; j++) {
NLevelItem parent = new NLevelItem(new SomeObject("Parent "+j),grandParent, new NLevelView() {
#Override
public View getView(NLevelItem item) {
View view = inflater.inflate(R.layout.list_item, null);
TextView tv = (TextView) view.findViewById(R.id.textView);
//tv.setBackgroundColor(Color.YELLOW);
String name = (String) ((SomeObject) item.getWrappedObject()).getName();
tv.setText(name);
return view;
}
});
list.add(parent);
int children = rng.nextInt(3)+1;
for(int x=0; x<children;x++){
final NLevelItem childs = new NLevelItem(new SomeObject("Parent1 "+x),parent, new NLevelView() {
#Override
public View getView(NLevelItem item) {
View view = inflater.inflate(R.layout.list_item, null);
TextView tv = (TextView) view.findViewById(R.id.textView);
//tv.setBackgroundColor(Color.BLUE);
String name = (String) ((SomeObject) item.getWrappedObject()).getName();
tv.setText(name);
return view;
}
});
list.add(childs);
int grandChildren = rng.nextInt(5)+1;
for( int k = 0; k < grandChildren; k++) {
NLevelItem child = new NLevelItem(new SomeObject("child "+k),childs, new NLevelView() {
#Override
public View getView(NLevelItem item) {
View view = inflater.inflate(R.layout.check_list, null);
TextView tv = (TextView) view.findViewById(R.id.checktextView);
final String name = (String) ((SomeObject) item.getWrappedObject()).getName();
final CheckBox checkBox = (CheckBox)view.findViewById(R.id.check);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selected != null){ //Edit
selected.setChecked(false);
}
selected = checkBox; //Edit
if(checkBox.isChecked()){
tempList.add((String) ((SomeObject)childs.getWrappedObject()).getName()+"+"+name);
}
else {
tempList.remove((String) ((SomeObject)childs.getWrappedObject()).getName()+"+"+name);
}
}
});
//tv.setBackgroundColor(Color.GRAY);
tv.setText(name);
return view;
}
});
list.add(child);
}
}
}
}
NLevelAdapter adapter = new NLevelAdapter(list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
((NLevelAdapter)listView.getAdapter()).toggle(arg2);
((NLevelAdapter)listView.getAdapter()).getFilter().filter();
}
});
checkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i=0;i<tempList.size();i++){
Toast.makeText(context,tempList.get(i),Toast.LENGTH_LONG).show();
}
}
});
}
class SomeObject {
public String name;
public SomeObject(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}
NLevelAdapter.java
public class NLevelAdapter extends BaseAdapter {
List<NLevelItem> list;
List<NLevelListItem> filtered;
public void setFiltered(ArrayList<NLevelListItem> filtered) {
this.filtered = filtered;
}
public NLevelAdapter(List<NLevelItem> list) {
this.list = list;
this.filtered = filterItems();
}
#Override
public int getCount() {
return filtered.size();
}
#Override
public NLevelListItem getItem(int arg0) {
return filtered.get(arg0);
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
return getItem(arg0).getView();
}
public NLevelFilter getFilter() {
return new NLevelFilter();
}
class NLevelFilter {
public void filter() {
new AsyncFilter().execute();
}
class AsyncFilter extends AsyncTask<Void, Void, ArrayList<NLevelListItem> > {
#Override
protected ArrayList<NLevelListItem> doInBackground(Void...arg0) {
return (ArrayList<NLevelListItem>)filterItems();
}
#Override
protected void onPostExecute(ArrayList<NLevelListItem> result) {
setFiltered(result);
NLevelAdapter.this.notifyDataSetChanged();
}
}
}
public List<NLevelListItem> filterItems() {
List<NLevelListItem> tempfiltered = new ArrayList<NLevelListItem>();
OUTER: for (NLevelListItem item : list) {
//add expanded items and top level items
//if parent is null then its a top level item
if(item.getParent() == null) {
tempfiltered.add(item);
} else {
//go through each ancestor to make sure they are all expanded
NLevelListItem parent = item;
while ((parent = parent.getParent())!= null) {
if (!parent.isExpanded()) {
//one parent was not expanded
//skip the rest and continue the OUTER for loop
continue OUTER;
}
}
tempfiltered.add(item);
}
}
return tempfiltered;
}
public void toggle(int arg2) {
filtered.get(arg2).toggle();
}
}
Thanks in advance!!
i think you need to store the checkbox state in a boolean (is checked), and reflect that on the view, when getView() is called.
1- Add boolean checked to NLevelItem :
private boolean checked = false;
//add setter: setChecked(boolean)
//add getter isChecked()
2- Use that boolean in getView() (last one where checkbox is added)
#Override
public View getView(final NLevelItem item) {
// .......
final CheckBox checkBox = (CheckBox)view.findViewById(R.id.check);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//store checkbox state, note that NLevelItem item might need to be defined with 'final'
item.setChecked(checkBox.isChecked());
if(checkBox.isChecked()){
tempList.add((String) ((SomeObject)childs.getWrappedObject()).getName()+"+"+name);
}
else {
tempList.remove((String) ((SomeObject)childs.getWrappedObject()).getName()+"+"+name);
}
}//onClick()
}//setOnClickListener()
//update checkbox state from the corresponding NLevelItem
checkBox.setChecked(item.isChecked());
//.......
}//getView()
-EDIT:
to select 1 item, you need to iterate all items, set checked = false, but 1
i am not sure if you have to do it on:
List<NLevelItem> list;
or
List<NLevelListItem> filtered;
in the adapter class
private void selectOnly(int position){
for(int a=0;a<list.size();a++){
if(a == position){
list.get(a).setChecked(true);
continue;
}
list.get(a).setChecked(false);
}//for loop
notifyDataSetChanged(); // to update views (checkbox state)
}
Usage: selectOnly(15);
Use ViewHolder class to set and get Tag like this:
public class ListAdapter extends BaseAdapter {
private Context con;
private List<String> dataLt;
private static LayoutInflater inflater = null;
public ListAdapter(Context context, List<String> dataList){
con = context;
dataLt = dataList;
inflater = (LayoutInflater)con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return dataLt.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.list_item_search, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.textView = (TextView) vi.findViewById(R.id.textView);
/************ Set holder with LayoutInflater ************/
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
return vi;
}
public static class ViewHolder{
TextView textView;
}
}
Hope this may help.

OnItemClicklistener on list adapter that populate its items from database

I have a list view that implement swipelistadapter and app controller. The list view display correctly from the database, the only thing I need is to get position of each item and assign intent activity on each. These are my codes
public class SwipeListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieList;
private String[] bgColors;
public SwipeListAdapter(Activity tab1, List<Movie> movieList) {
this.activity = tab1;
this.movieList = movieList;
bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public Object getItem(int location) {
return movieList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_rows, null);
TextView serial = (TextView) convertView.findViewById(R.id.serial);
TextView title = (TextView) convertView.findViewById(R.id.title);
serial.setText(String.valueOf(movieList.get(position).id));
title.setText(movieList.get(position).title);
String color = bgColors[position % bgColors.length];
serial.setBackgroundColor(Color.parseColor(color));
return convertView;
}
}
Below Class is the main activity
public class Tab1 extends Fragment implements ViewSwitcher.ViewFactory, SwipeRefreshLayout.OnRefreshListener {
private int index;
private int[] images = new int[] { R.drawable.gallery1, R.drawable.gallery2, R.drawable.gallery3, R.drawable.gallery4, R.drawable.gallery5, R.drawable.gallery6, R.drawable.gallery7, R.drawable.gallery8 };
ImageSwitcher switcher;
android.os.Handler Handler = new Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private SwipeListAdapter adapter;
private List<Movie> movieList;
private ListView listView;
// private static final String url = "http://api.androidhive.info/json/movies.json";
private String URL_TOP_250 = "http://192.158.33.172/locator/test/refractor.php?offset=";
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;
private static final String TAG = Tab1.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_1,container,false);
listView = (ListView) v.findViewById(R.id.list);
// Adding request to request queue
//Editted AppController.getInstance().addToRequestQueue(movieReq);
swipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_refresh_layout);
movieList = new ArrayList<>();
adapter = new SwipeListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovies();
}
}
);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//String selectedFromList = (listView.getItemAtPosition(position).getString());
// String text = movieList[position];
Intent i = new Intent(getActivity(), Tab2.class);
// i.putExtra("TEXT", text);
startActivity(i);
}
});
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
switcher = (ImageSwitcher) getActivity().findViewById(R.id.imageSwitcher1);
switcher.setFactory(this);
switcher.setImageResource(images[index]);
switcher.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
index++;
if (index >= images.length) {
index = 0;
}
switcher.setImageResource(images[index]);
}
});
switcher.setInAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
switcher.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out));
//auto change image
Handler.post(UpdateImage);
}
#Override
public void onRefresh() {
fetchMovies();
}
private void fetchMovies() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL_TOP_250 + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("postTitle");
Movie m = new Movie(rank, title);
movieList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
Runnable UpdateImage = new Runnable() {
public void run() {
// Increment index
index++;
if (index > (images.length - 1)) {
index = 0;
}
switcher.setImageResource(images[index]);
// Set the execution after 5 seconds
Handler.postDelayed(this, (3 * 1000));
}
};
#Override
public View makeView() {
ImageView myView = new ImageView(getActivity());
myView.setScaleType(ImageView.ScaleType.FIT_CENTER);
myView.setLayoutParams(new ImageSwitcher.LayoutParams(Gallery.LayoutParams.
FILL_PARENT, Gallery.LayoutParams.FILL_PARENT));
return myView;
}
}
Any help will be appreciated. Thanks.
Code for getting a single item:
String singleItem = getItem(position);
this is quite straight forward. here is a modification to your onItemClickListener:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String text = movieList.get(position);
Intent i = new Intent(getActivity(), Tab2.class);
i.putExtra("TEXT", text);
startActivity(i);
}
});
just note that movieList object should be the same object you pass to your adapter

changes intended on one row but effects are showing in next row

hi friends i am not able to understand how to set text in the same row of the list view where i am having two button with text view at the center but when i am trying to increment or decrement the effect is showing on the next row but not the row on which i want the changes to be applied
CartAdapter.java
public class Cart_Adapter extends BaseAdapter {
Context cartcontext;
List<MobiData> cartlist;
LayoutInflater inflater;
cartlist cartdata;
public ArrayList<Integer> quantity = new ArrayList<Integer>();
CustomButtonListener customButtonListener;
public Cart_Adapter(Context cartcontext, List<MobiData> cartlist) {
this.cartcontext = cartcontext;
this.cartlist = cartlist;
}
#Override
public int getCount() {
return cartlist.size();
}
#Override
public Object getItem(int position) {
return cartlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) cartcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
cartdata = new cartlist();
convertView = inflater.inflate(R.layout.cart_row, parent, false);
cartdata.decrement = (TextView) convertView.findViewById(R.id.decrement);
cartdata.single = (TextView) convertView.findViewById(R.id.single);
cartdata.single.setTag(position);
cartdata.increment = (TextView) convertView.findViewById(R.id.increment);
cartdata.increment.setTag(position);
cartdata.cancel = (TextView) convertView.findViewById(R.id.cancel);
cartdata.vcmedname = (TextView) convertView.findViewById(R.id.vcmedname);
cartdata.vcmedprice = (TextView) convertView.findViewById(R.id.vcmedprice);
Typeface carttext = Typeface.createFromAsset(cartcontext.getAssets(), "fonts/fontawesome.ttf");
cartdata.decrement.setTypeface(carttext);
cartdata.increment.setTypeface(carttext);
cartdata.cancel.setTypeface(carttext);
convertView.setTag(cartdata);
} else {
cartdata = (cartlist) convertView.getTag();
}
MobiData newcart = cartlist.get(position);
cartdata.vcmedname.setText(newcart.getVcmedname());
cartdata.vcmedprice.setText(newcart.getVcmedprice());
cartdata.single.setText(newcart.getVcqty());
final String cartids = newcart.getVcmedid();
cartdata.cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cartlist.remove(position);
notifyDataSetChanged();
}
});
cartdata.increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v) {
if (customButtonListener !=null){
int plus = Integer.parseInt(cartdata.single.getText().toString());
plus++;
int plus = Integer.parseInt(cartdata.single.getText().toString());
plus++;
cartdata.single.setText(String.valueOf(plus));
SharedPreferences viewpref = cartcontext.getSharedPreferences("datapref", Context.MODE_PRIVATE);
String cartuid = viewpref.getString("uid", "");
String carttempid = viewpref.getString("tempid", "");
String incremnturl = "http://sampletemplates.net/mobichemist/json/cart_process.php?mid=" + cartids + "&userid=" + cartuid + "&tempid=" + carttempid;
Log.d("Incremnturl", incremnturl);
JsonArrayRequest incrementarray = new JsonArrayRequest(Request.Method.GET, incremnturl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject incrobj = response.getJSONObject(i);
int plus = Integer.parseInt(cartdata.single.getText().toString());
plus++;
cartdata.single.setText(String.valueOf(plus));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Incrementurl", String.valueOf(error));
}
});
incrementarray.setRetryPolicy(new DefaultRetryPolicy(50000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(incrementarray);
}
});
cartdata.decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i = Integer.parseInt(cartdata.single.getText().toString());
i--;
if (i <= 0) {
Toast.makeText(Single_Cart_Page.this, "Minimum Quantity is 1", Toast.LENGTH_SHORT).show();
} else {
cartdata.single.setText(String.valueOf(i));
}
}
});
return convertView;
}
static class cartlist {
TextView decrement, single, increment, cancel, vcmedname, vcmedprice;
}
try this and add your other code.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.cart_row, parent, false);
holder = new ViewHolder();
holder.decrement = (TextView) convertView.findViewById(R.id.decrement);
holder.single = (TextView) convertView.findViewById(R.id.single);
holder.increment = (TextView) convertView.findViewById(R.id.increment);
holder.cancel = (TextView) convertView.findViewById(R.id.cancel);
holder.vcmedname = (TextView) convertView.findViewById(R.id.vcmedname);
holder.vcmedprice = (TextView) convertView.findViewById(R.id.vcmedprice);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
Typeface carttext = Typeface.createFromAsset(cartcontext.getAssets(), "fonts/fontawesome.ttf");
holder.decrement.setTypeface(carttext);
holder.increment.setTypeface(carttext);
holder.cancel.setTypeface(carttext);
MobiData newcart = cartlist.get(position);
holder.vcmedname.setText(newcart.getVcmedname());
holder.vcmedprice.setText(newcart.getVcmedprice());
holder.single.setText(newcart.getVcqty());
final String cartids = newcart.getVcmedid();
holder.cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cartlist.remove(position);
notifyDataSetChanged();
}
});
return convertView;
}
static class ViewHolder {
private TextView decrement;
private TextView single;
private TextView increment;
private TextView vcmedname;
private TextView vcmedprice;
}
Use ArrayAdaper instead of Base Adapter with ViewHolder. Don't set setTag(position) manually for all views.
Find ViewHolder example here https://dzone.com/articles/optimizing-your-listview .It will solve your indexing problem. ViewHolder class sets all views position. Also find more description on Hold View Objects in a View Holder

EditText works correctly in ListView but CheckBoxes do not

So I have a custom list adapter, and I've learned that attaching listeners to particular items in that list is incredibly confusing. I understand that ListView recycles views, and that you must reference each item using a holder and a reference for that item. My EditTexts work when I scroll, but my CheckBoxes take the value of recycled views. Here is my code. Everything displays correctly, so it's not an XML issue.
public void changeMate(View view) {
View parent = (View)view.getParent();
CheckBox box = (CheckBox)view;
CheckBox mate;
if (view.getId()==R.id.trueBox) mate = (CheckBox) parent.findViewById(R.id.falseBox);
else mate = (CheckBox) parent.findViewById(R.id.trueBox);
mate.setChecked(!box.isChecked());
TextView label = (TextView)parent.findViewById(R.id.atomName);
// MainActivity.atoms[(int)label.getText().charAt(0)-'A'].immutableTruth=box.getId()==R.id.trueBox;
MainActivity.atoms[(int)label.getText().charAt(0)-'A'].immutableTruth=((CheckBox)findViewById(R.id.trueBox)).isChecked();
MainActivity.atoms[(int)label.getText().charAt(0)-'A'].valueSet=true;
c.put((int)label.getText().charAt(0)-'A',MainActivity.atoms[(int)label.getText().charAt(0)-'A'].immutableTruth);
}
public void kill(View view) {
try {
finish();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
public void handleChanges(View view) {
}
static class AtomViewer extends ArrayAdapter<Atom> {
private ArrayList<Atom> objects;
public AtomViewer(Context context, int resource, ArrayList objects) {
super(context, resource, objects);
this.objects = objects;
}
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
// assign the view we are converting to a local variable
View v = convertView;
final ViewHolder holder;
// first check to see if the view is null. if so, we have to inflate it.
// to inflate it basically means to render, or show, the view.
if (v == null) {
holder=new ViewHolder();
LayoutInflater inflater = (LayoutInflater) `enter code here` getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.atom_view, null);
holder.editText1= (EditText) convertView.findViewById(R.id.definition);
convertView.setTag(holder);
} else holder= (ViewHolder) convertView.getTag();
v=convertView;
holder.ref=position;
CheckBox tb = (CheckBox) v.findViewById(R.id.trueBox);
CheckBox fb = (CheckBox) v.findViewById(R.id.falseBox);
holder.tb=tb;
holder.fb=fb;
TextView name = (TextView) v.findViewById(R.id.atomName);
Atom i = objects.get(position);
holder.editText1.setText(e.valueAt(position));
holder.editText1.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
e.setValueAt(holder.ref, s);
}
});
{
if (!i.valueSet)
{
holder.fb.setChecked(!i.truth);
holder.tb.setChecked(i.truth);
}
boolean truth = c.get(position);
if (truth&&i.valueSet) {
holder.fb.setChecked(false);
holder.tb.setChecked(true);
}
else if(!truth)
{
holder.fb.setChecked(true);
holder.tb.setChecked(false);
}
CharSequence t = String.valueOf(i.getname());
name.setText(t);
if (i.dictionaryValue != null) ``holder.editText1.setText(i.dictionaryValue);
}
`return v;
}
}
public static Atom[] atoms;
public ArrayList<Atom> mParts = new ArrayList<Atom>();
public AtomViewer mAdapter;
public ListView listView;
public static SparseArray<Editable> e = new SparseArray<>(26);
public static SparseBooleanArray c = new SparseBooleanArray(26);
#Override
protected void onCreate(Bundle stuff) {
super.onCreate(null);
setContentView(R.layout.activity_info);
Intent i = getIntent();
getWindow().getDecorView().setSaveEnabled(false);
Bundle b=i.getExtras();
atoms=MainActivity.atoms;
String arg = b.getString("Argument");
String conc = b.getString("Conclusion");
TextView tv = (TextView) findViewById(R.id.argText);
tv.setText(arg);
tv = (TextView) findViewById(R.id.concText);
tv.setText(conc);
tv=(TextView)findViewById(R.id.valid);
tv.setText(b.getString("Validity"));
tv=(TextView)findViewById(R.id.sound);
tv.setText(b.getString("Soundness"));
//int index = 0;
for (Atom a:atoms
) {
if(a!=null) {
if(a.valueSet) c.put(a.ID,a.immutableTruth); else c.put(a.ID,a.truth);
mParts.add(a);
}
}
ArrayAdapter<Atom> arrayAdapter = new `enter code here`AtomViewer(this,R.layout.atom_view,mParts);
listView= (ListView) findViewById(R.id.list);
listView.setAdapter(arrayAdapter);
listView.getCheckedItemPositions();
}
private static class ViewHolder {
EditText editText1;
CheckBox tb,fb;
int ref;
}
}
Edit your code, move
holder.ref=position;
CheckBox tb = (CheckBox) v.findViewById(R.id.trueBox);
CheckBox fb = (CheckBox) v.findViewById(R.id.falseBox);
holder.tb=tb;
holder.fb=fb;
TextView name = (TextView) v.findViewById(R.id.atomName);
inside if (v == null)

Saving text and checkbox state in custom list

I am making a custom list and I want to save the text of some TextFile which is in R.id.quantity.
I also want to save the state of a checkbox. I tried to manage checked state of a checkbox in a list.
The List contains other view controls. I have put them in a Viewholder class. I am initializing qtyTxtV with some initial array value, once an event occurs in this code the value of the array changes but the list contents gets erased. Please help out.
Now this code is giving me a null pointer exception:
class MyAdapter1 extends BaseAdapter {
Context context;
ArrayList<Integer> price = new ArrayList<Integer>();
ArrayList<String> names = new ArrayList<String>();
public static HashMap<Integer, String> myList = new HashMap<Integer, String>();
static class ViewHolder {
public TextView tvQuantityName, tvPrice, tvDishName;
public ImageView imv1, imv2, imv3, imv4, imv5;
public EditText edtQty;
public CheckBox chkAdd;
}
public MyAdapter1(VegDetail vegDetail, ArrayList<String> names2,
ArrayList<Integer> price2) {
this.context = vegDetail;
this.names = names2;
this.price = price2;
}
#Override
public int getCount() {
return names.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#SuppressWarnings("null")
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
// View row = inflater.inflate(R.layout.rowlayout, parent, false);
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(context);
row = inflater.inflate(R.layout.rowlayout, parent, false);
holder.edtQty = (EditText) row.findViewById(R.id.quantity);
holder.imv1 = (ImageView) row.findViewById(R.id.star1);
holder.imv2 = (ImageView) row.findViewById(R.id.star2);
holder.imv3 = (ImageView) row.findViewById(R.id.star3);
holder.imv4 = (ImageView) row.findViewById(R.id.star4);
holder.imv5 = (ImageView) row.findViewById(R.id.star5);
holder.tvDishName = (TextView) row.findViewById(R.id.item_name);
holder.tvPrice = (TextView) row.findViewById(R.id.price1);
holder.tvQuantityName = (TextView) row.findViewById(R.id.qtyTxtV);
holder.chkAdd = (CheckBox) row.findViewById(R.id.chkAdd);
EditText edtQty = (EditText) row.findViewById(R.id.quantity);
edtQty.setText(VegDetail.qtyArray[position].toString());
CheckBox chkAdd = (CheckBox) row.findViewById(R.id.chkAdd);
chkAdd.setSelected(VegDetail.chkArray[position]);
holder.edtQty.addTextChangedListener(new TextWatcher() {
public void onTextChanged(final CharSequence s,
final int start, final int before, final int count) {
}
public void afterTextChanged(final Editable s) {
int newValue;
final String boxContents = s.toString();
if (!boxContents.isEmpty()) {
try {
newValue = Integer.parseInt(boxContents);
VegDetail.qtyArray[position] = newValue;
} catch (final Exception exc) {
VegDetail.qtyArray[position] = 0;
} finally {
}
} else {
VegDetail.qtyArray[position] = 0;
}
}
public void beforeTextChanged(final CharSequence s,
final int start, final int count, final int after) {
}
});
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
CheckBox chkAdd=(CheckBox)row.findViewById(R.id.chkAdd);
chkAdd.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
//VegDetail is another class where I gonna use checked list's states
VegDetail.chkArray[position] = isChecked;
}
});
final TextView tv1 = (TextView) row.findViewById(R.id.item_name);
TextView tv2 = (TextView) row.findViewById(R.id.price1);
final TextView tvQty = (TextView) row.findViewById(R.id.quantity);
tv1.setText(names.get(position));
tv1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,
"itme name is=>" + tv1.getText().toString(),
Toast.LENGTH_LONG).show();
}
});
tv2.setText("Rs:" + price.get(position));
return row;
}
}
The NPE must be at line :
holder.edtQty = (EditText) row.findViewById(R.id.quantity);
since holder is NULL as you have just defined above...ViewHolder holder = null

Categories