I'm developing an Android Application and I'm using Android ListView. I'm getting datas from the web service and fill them into the Arraylist. It's size is 37. Then i try to fill the listview with Arraylist but it always get the same element(last one). Below you can see the code part:
private void ctv_listele(String res){
ArrayList<CTV> ctvList = new ArrayList<CTV>();
try {
JSONObject jsonObject = new JSONObject(res);
JSONArray jsonArray = jsonObject.getJSONArray("tarife");
int max = jsonArray.length();
for(int i = 0; i < max; i++) {
JSONObject tmp = jsonArray.getJSONObject(i);
ctv.setYear(tmp.getString("Year"));
ctv.setYearlyCost(tmp.getString("YearlyCost"));
ctv.setMonthlyCost(tmp.getString("MonthlyCost"));
ctv.setGroup(tmp.getString("Group"));
ctv.setDegree(tmp.getString("Degree"));
Log.e("Added",tmp.getString("YearlyCost"));
ctvList.add(ctv);
}
Log.e("End",String.valueOf(ctvList.size()));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ListView productList = (ListView) findViewById(R.id.listView_ctv);
MyCustomAdapter adapter = new MyCustomAdapter(this, R.layout.ctv_row, ctvList);
productList.setAdapter(adapter);
}
public class MyCustomAdapter extends ArrayAdapter<CTV>{
private Activity context;
private ArrayList<CTV> liste;
private LayoutInflater layoutInflater;
private AdapterSatir adaSatir;
public MyCustomAdapter(Activity context, int ctvRow, ArrayList<CTV> objects) {
super(context, R.layout.ctv_row, objects);
this.context=context;
this.liste=objects;
Log.e("liste",String.valueOf(liste.size()));
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view_satir=convertView;
if(view_satir==null) {
adaSatir=new AdapterSatir();
layoutInflater=context.getLayoutInflater();
view_satir=layoutInflater.inflate(R.layout.cevretemizliktarifeleri_row, null,true);
adaSatir.textView1=(TextView) view_satir.findViewById(R.id.textView_ctvlist1);
adaSatir.textView2=(TextView) view_satir.findViewById(R.id.textView_ctvlist2);
adaSatir.textView3=(TextView) view_satir.findViewById(R.id.textView_ctvlist3);
adaSatir.textView4=(TextView) view_satir.findViewById(R.id.textView_ctvlist4);
view_satir.setTag(adaSatir);
} else {
adaSatir = (AdapterSatir) view_satir.getTag();
}
adaSatir.textView1.setText(liste.get(position).getDegree());
adaSatir.textView2.setText(liste.get(position).getGroup());
adaSatir.textView3.setText(liste.get(position).getMonthlyCost());
adaSatir.textView4.setText(liste.get(position).getYearlyCost());
return view_satir;
}
private class AdapterSatir
{
public TextView textView1;
public TextView textView2;
public TextView textView3;
public TextView textView4;
}
}
for(int i = 0; i < max; i++) {
JSONObject tmp = jsonArray.getJSONObject(i);
ctv.setYear(tmp.getString("Year"));
ctv.setYearlyCost(tmp.getString("YearlyCost"));
ctv.setMonthlyCost(tmp.getString("MonthlyCost"));
ctv.setGroup(tmp.getString("Group"));
ctv.setDegree(tmp.getString("Degree"));
Log.e("Added",tmp.getString("YearlyCost"));
ctvList.add(ctv);
}
you forget to init your cvt object at every iteration. So you add always the same reference to the list.
for(int i = 0; i < max; i++) {
JSONObject tmp = jsonArray.getJSONObject(i);
CTV cvt = new CVT();
ctv.setYear(tmp.getString("Year"));
ctv.setYearlyCost(tmp.getString("YearlyCost"));
ctv.setMonthlyCost(tmp.getString("MonthlyCost"));
ctv.setGroup(tmp.getString("Group"));
ctv.setDegree(tmp.getString("Degree"));
Log.e("Added",tmp.getString("YearlyCost"));
ctvList.add(ctv);
}
First Add new data to ctvList
then call adapter.notifyDataSetChanged();
Then new data will reflect in the List view please check this
Related
This question already has answers here:
ListView not "refreshing" after item is deleted from it
(6 answers)
Closed 5 years ago.
I Have a list view where i have loaded it with json array data. I have minus button to delete row from list. Here the problem is I am able to delete the item but list view is not getting refreshed. The list view gets refreshed once the application is closed or when I go back and navigate to that activity again.
Below is the custom adapter class code:
public class AddPassengerAdapater extends BaseAdapter implements ListAdapter {
private final JSONArray jsonArray;
ArrayList<String> data;
Context context;
JSONObject json_data;
LayoutInflater inflater;
public AddPassengerAdapater(Context context, JSONArray jsonArray,ArrayList<String> data) {
this.context = context;
this.jsonArray = jsonArray;
this.data = data;
String details = SessionManager.getPreferences(context,"splitfare_consumer");
data = new ArrayList<String>();
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(details);
for (int i=0; i < jsonarray.length() ; i++){
json_data = jsonarray.getJSONObject(i);
data.add(String.valueOf(json_data));
}
} catch (JSONException e) {
e.printStackTrace();
}
inflater = LayoutInflater.from(this.context);
}
#Override public int getCount() {
if(null==jsonArray)
return 0;
else
return jsonArray.length();
}
#Override public JSONObject getItem(int position) {
if(null==jsonArray) return null;
else
return jsonArray.optJSONObject(position);
}
#Override public long getItemId(int position) {
JSONObject jsonObject = getItem(position);
return jsonObject.optLong("id");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.addpassenger_row_layout, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
}
else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
json_data = getItem(position);
try {
String n = json_data.getString("name");
mViewHolder.name.setText(n);
String nu = json_data.getString("number");
mViewHolder.number.setText(nu);
} catch (JSONException e) {
e.printStackTrace();
}
mViewHolder.deletelist.setOnClickListener(new View.OnClickListener() {
JSONArray delete_jsonarray;
JSONObject jsonObject;
#Override
public void onClick(View v) {
String phonenumber = mViewHolder.number.getText().toString();
String jsonsetpreference_data = SessionManager.getPreferences(context,"splitfare_consumer");
Log.d("jsonsetpreference_data:::::::","" +jsonsetpreference_data);
try {
delete_jsonarray= new JSONArray(jsonsetpreference_data);
for (int i =0; i<= delete_jsonarray.length()-1 ; i++){
jsonObject = delete_jsonarray.getJSONObject(i);
String array_phonenumber = jsonObject.getString("number");
if (phonenumber.equals(array_phonenumber)){
delete_jsonarray.remove(i);
}
}
SessionManager.setPreferences(context,"splitfare_consumer",delete_jsonarray.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return convertView;
}
private class MyViewHolder {
TextView name, number;
ImageView deletelist;
public MyViewHolder(View item) {
name = (TextView) item.findViewById(R.id.consumername);
number = (TextView) item.findViewById(R.id.consumer_number);
deletelist = (ImageView) item.findViewById(R.id.dltconsumer);
}
}
}
Listview activity code:
public class AddPassengerList extends AppCompatActivity {
#BindView(R.id.listview)
ListView listview;
#BindView(R.id.btn_addmore)
CustomFontButton btn_addmore;
#BindView(R.id.donebtn)
CustomFontButton donebtn;
public static final String TAG = "AddPassengerList";
Activity activity=this;
Context context = this;
JSONArray js;
AddPassengerAdapater adapter;
LayoutInflater inflater;
String name ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_passenger_list);
ButterKnife.bind(this);
/*Status bar color*/
Window window = activity.getWindow();
// clear FLAG_TRANSLUCENT_STATUS flag:
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// finally change the color
window.setStatusBarColor(ContextCompat.getColor(context,R.color.colorAccent));
String data = SessionManager.getPreferences(context,"splitfare_consumer");
Log.d(TAG,""+data);
ArrayList<String> details= new ArrayList<String>();
try {
js = new JSONArray(data);
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new AddPassengerAdapater(context,js,details);
listview.setAdapter(adapter);
btn_addmore.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
btn_addmore.setBackgroundResource(R.drawable.addmorepassengerpressed);
break;
case MotionEvent.ACTION_UP:
btn_addmore.setBackgroundResource(R.drawable.addmorepassenger);
Intent i = new Intent(AddPassengerList.this,AddPassenger.class);
startActivity(i);
break;
}
return false;
}
});
}
}
Recall your adapter again after delete item...
mViewHolder.deletelist.setOnClickListener(new View.OnClickListener() {
JSONArray delete_jsonarray;
JSONObject jsonObject;
#Override
public void onClick(View v) {
String phonenumber = mViewHolder.number.getText().toString();
String jsonsetpreference_data = SessionManager.getPreferences(context,"splitfare_consumer");
Log.d("jsonsetpreference_data:::::::","" +jsonsetpreference_data);
try {
delete_jsonarray= new JSONArray(jsonsetpreference_data);
for (int i =0; i<= delete_jsonarray.length()-1 ; i++){
jsonObject = delete_jsonarray.getJSONObject(i);
String array_phonenumber = jsonObject.getString("number");
if (phonenumber.equals(array_phonenumber)){
delete_jsonarray.remove(i);
}
}
SessionManager.setPreferences(context,"splitfare_consumer",delete_jsonarray.toString());
} catch (JSONException e) {
e.printStackTrace();
}
notifyDataSetChanged();
}
});
I've a listview which shows values from web service. Its fine when it loads the listview. But when I click on any item to open a new fragment (which shows details of the item) and get back to the same listview, its items doubles everytime. For example, if I have (in original) 5 items in total. Then when I get back from the fragment, the total count will be 10, then 15 and so on. It means the app is adding all items again and again. I searched for the solution and did what were the general solution like adapter.notifyDataSetChanged() but its still gets duplicated. If anyone can show me the problem, I would be grateful.
public class CustomListAdapter extends ArrayAdapter<Model> {
private Context mContext;
int resource;
private ArrayList<Model> mListData = new ArrayList<Model>();
public CustomListAdapter(Context mContext, int resource, ArrayList<Model> mListData) {
super(mContext, resource, mListData);
this.resource = resource;
this.mContext = mContext;
this.mListData = mListData;
}
public void setListData(ArrayList<Model> mListData) {
this.mListData = mListData;
notifyDataSetChanged();
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View v = convertView;
final ViewHolder holder;
if (v == null) {
holder = new ViewHolder();
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
v = inflater.inflate(resource, parent, false);
holder.custname = (TextView) v.findViewById(R.id.cust_name);
holder.date = (TextView) v.findViewById(R.id.date);
holder.staffname = (TextView) v.findViewById(R.id.staff_name);
holder.time = (TextView) v.findViewById(R.id.time);
holder.service = (TextView) v.findViewById(R.id.service);
holder.refid = (TextView) v.findViewById(R.id.refid);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
final Model item = mListData.get(position);
holder.custname.setText(item.getCustname());
holder.date.setText(item.getDate());
holder.staffname.setText(item.getStaffname());
holder.time.setText(item.getTime());
holder.service.setText(item.getService());
holder.refid.setText(item.getRefid());
return v;
}
class ViewHolder {
TextView custname, date, staffname, time, service, refid;
}
}
public class ListFrag extends Fragment{
private SwipeMenuListView listView;
private CustomListAdapter adapter;
private CShowProgress cShowProgress;
private SQLiteHandler db;
private String uid, bookingId;
private ArrayList<Model> arrayList = new ArrayList<>();
private static final String BOOKED_LIST = "http://192.168.220.13/android/showbookinglist";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.listfrag, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
listView = (SwipeMenuListView)view.findViewById(R.id.list);
db = new SQLiteHandler(getActivity());
cShowProgress = CShowProgress.getInstance();
fetchDetails();
adapter = new CustomListAdapter(getActivity(), R.layout.listitem, arrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String a = arrayList.get(i).getCustname();
String b = arrayList.get(i).getStaffname();
String c = arrayList.get(i).getService();
String d = arrayList.get(i).getDate();
String e = arrayList.get(i).getTime();
String f = arrayList.get(i).getRefid();
String g = arrayList.get(i).getEmail();
String h = arrayList.get(i).getServprice();
String j = arrayList.get(i).getSpeclprice();
String k = arrayList.get(i).getStatus();
db.addDetails(a, b, c, d, e, f, g, h, j, k);
DetailsView details = new DetailsView();
((Bookings)getActivity()).replaceFragment(details);
}
});
}
private void fetchDetails() {
cShowProgress.showProgress(getActivity());
StringRequest stringRequest = new StringRequest(Request.Method.POST, BOOKED_LIST,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
cShowProgress.hideProgress();
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
Model model = new Model();
model.setCustname(obj.getString("customername"));
model.setDate(obj.getString("staffdate"));
model.setStaffname(obj.getString("staffname")+"(Staff)");
model.setTime(obj.getString("stafftime"));
model.setService(obj.getString("servicename"));
model.setRefid(obj.getString("booking_referenceid"));
model.setEmail(obj.getString("customeremail"));
model.setServprice(obj.getString("serviceprice"));
model.setSpeclprice(obj.getString("specialprice"));
model.setStatus(obj.getString("status"));
model.setBookid(obj.getString("bookingid"));
arrayList.add(model);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("spaid", "145");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
}
try to change it as.. B'coz you are adding the elements in previously created list.. So you have to clear it.
private void fetchDetails() {
if(arrayList!=null )arrayList.clear(); // this line
cShowProgress.showProgress(getActivity());
The thing is that when you get back to the fragment it is recreated and onViewCreated is called again. From there you call again fetchDetails() and then your are adding the whole List for a second time to the adapter. So you can clear the list before fetchDetails() or just if you have to fetch them again.
change your try - catch block of onResponse method by below.
try {
JSONArray jsonArray = new JSONArray(response);
arrayList = new ArrayList<>();
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject obj = jsonArray.getJSONObject(i);
Model model = new Model();
model.setCustname(obj.getString("customername"));
model.setDate(obj.getString("staffdate"));
model.setStaffname(obj.getString("staffname")+"(Staff)");
model.setTime(obj.getString("stafftime"));
model.setService(obj.getString("servicename"));
model.setRefid(obj.getString("booking_referenceid"));
model.setEmail(obj.getString("customeremail"));
model.setServprice(obj.getString("serviceprice"));
model.setSpeclprice(obj.getString("specialprice"));
model.setStatus(obj.getString("status"));
model.setBookid(obj.getString("bookingid"));
arrayList.add(model);
}
adapter.notifyDataSetChanged();
This is happening because you are not clearing the arrayList. Due to this every time that you construct the array and the adapter, you are adding the elements into an array that already has elements.
That why you have 5, then 10, then 15 and so on..
Clear the array before adding new elements
arrayList.clear();
Or program another strategy like:
Not populate the array every time you return to the fragment.
Check if he element existe before add it into the array.
i am trying to display json data in listview but listview is empty logcat shows no error and app also don't get crashed i am unable to find the error here is the method that adds json data to the adapter
public void setTextToTextView(JSONArray jsonArray) {
contactAdapter = new ContactAdapter(this,R.layout.row_layout);
listView.setAdapter(contactAdapter);
try {
int count = 0;
String stop;
while(count < jsonArray.length())
{
JSONObject JO = jsonArray.getJSONObject(count);
stop = JO.getString("stop");
Contacts contacts = new Contacts(stop);
contactAdapter.add(contacts);
count++;
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
here is the Adapter class
public class ContactAdapter extends ArrayAdapter{
List list = new ArrayList();
public ContactAdapter(Context context, int resources){
super(context,resources);
}
public void add(Contacts 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;
ContactHolder contactHolder;
if(row == null)
{
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
contactHolder = new ContactHolder();
contactHolder.tx_stop = (TextView)row.findViewById(R.id.tx_stop);
row.setTag(contactHolder);
}
else
{
contactHolder = (ContactHolder)row.getTag();
}
Contacts contacts = (Contacts)this.getItem(position);
contactHolder.tx_stop.setText(contacts.getStop());
return row;
}
static class ContactHolder
{
TextView tx_stop;
}
}
Call
contactAdapter.notifyDataSetChanged();
after your while loop.
You can create ArrayList<Contacts> contactsArray = new ArrayList<Contacts>(); then push all objects in it after that to set your adapter with passed array. Your method should look like:
public void setTextToTextView(JSONArray jsonArray) {
ArrayList<Contacts> contactsArray = new ArrayList<Contacts>();
try {
int count = 0;
String stop;
while(count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
stop = JO.getString("stop");
Contacts contacts = new Contacts(stop);
contactsArray.add(contacts);
count++;
}
contactAdapter = new ContactAdapter(this,R.layout.row_layout, contactsArray);
listView.setAdapter(contactAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
In your adapter do the following:
ArrayList<Contacts> list = new ArrayList<Contacts>();
public ContactAdapter(Context context, int resources, ArrayList<Contacts> list){
super(context,resources);
this.list = list;
}
That's all. Hope to help!
I am working on application in which i am getting list of my history using pubnub which contains message and time token. The Original Json string is given below:
[[{"message":"hdjcjcjjckckckckvkckckck","timetoken":14151866297757284},{"message":"ufjfjfjcjfjchfjdhwjroritkgjcj","timetoken":14151869212145693},{"message":"qMobile","timetoken":14152601234812083}],14151866297757284,14152601234812083]
After using following method i have get the following Json String in JSONObject c.
{"message":"hdjcjcjjckckckckvkckckck","timetoken":14151866297757284}
pubnub.history(channel, true, 100, new Callback() {
#Override
public void successCallback(String channel,
Object message) {
notifyUser("HISTORY : " + message);
Log.i("Received msg : ", message.toString()); //<==== receiving Messages here
try {
JSONArray jsonObj = new JSONArray(message.toString());
JSONArray jArray = new JSONArray(jsonObj.get(0).toString());
for (int i = 0; i < jArray.length(); i++) {
JSONObject c = jArray.getJSONObject(i);
String messageString=c.getString("message");
String timeString=c.getString("timetoken");
String abc = timeString;
}
}
Now i just want to display my each Json Object in ListView like this
message:dsfdsvsfvdfvfdvdvgd
timetoken:14132423414141
message:dsfwfwefwedcsfsw
timetoken:21431353153252
message:dthfjtyhnfgvb
timetoken:68624526246
Thanks in advance.
Declare one ArrayList of hashmap like below:
ArrayList<HashMap<String,String>> data= new ArrayList<HashMap<String,String>>();
HashMap<String,String> jsonData;
private EfficientAdapter adapter;
//In your onCreate() method, just initialize your adapter.
adapter = new EfficientAdapter(this);
Now, inside this for loop:
for (int i = 0; i < jArray.length(); i++) {
jsonData=new HashMap<String,String>();
JSONObject c = jArray.getJSONObject(i);
String messageString=c.getString("message");
String timeString=c.getString("timetoken");
String abc = timeString;
jsonData.put("message",messageString);
jsonData.put("timeStamp",timeString);
data.add(jsonData);
}
YOURLISTVIEW.setAdapter(adapter);
//List Adapter code:
private class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context context;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.YOUR LAYOUT FILE TO SHOW MESSAGE AND TIME, null);
//Just create one xml in layout folder and give that layout file name like R.layout.list_item.
holder = new ViewHolder();
holder.txtMessage = (TextView) convertView.findViewById(R.id.txtMessage);
holder.txtTimestamp = (TextView) convertView.findViewById(R.id.txtTimestamp);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtMessage.setText(data.get(position).get("message"));
holder.txtTimestamp.setText(data.get(position).get("timeStamp"));
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//your list click event here
}
});
return convertView;
}
class ViewHolder {
TextView txtMessage;
TextView txtTimestamp;
}
}
A better option is to use GSON, it will save your time in the future with json parsing.
Download gson and add it to your project http://search.maven.org/#artifactdetails%7Ccom.google.code.gson%7Cgson%7C2.3%7Cjar
Paste your json - http://www.jsonschema2pojo.org/, and make a java class representation.
Use your json String (or Reader), your created class (in point 2.) and get a object that has all the values that the json has -
Gson gson = new Gson();
yourObject = gson.fromJson(yourJsonString, yourObject.class);
And then use this object inside your adapter. For example - message = yourObject.get(position).getMessage();
I am trying to add rows in a list view when a button is clicked , but my application is getting crashed everytime .
Here is my code :
public class MTCRichGraphicsActivity extends Activity {
int ELEMENT_COUNT = 3;
int position=0;
Button bAddView;
String[] elements = new String[ELEMENT_COUNT];
int r =0 ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bAddView = (Button) findViewById(R.id.bNewEvent);
final ListView list = (ListView) findViewById(R.id.list3d);
bAddView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.bNewEvent :
for (int i = 0; i< ELEMENT_COUNT; i++) {
elements[i] = String.valueOf(i);
}
final MyAdapter adapter = new MyAdapter(MTCRichGraphicsActivity.this,elements);
adapter.notifyDataSetChanged();
//list.setScrollY(currentPosition);
//list.setTranslationY(currentPosition);
list.setDivider( null );
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
ELEMENT_COUNT = ELEMENT_COUNT + 3;
}
}
});
}
}
Here I want to add 3 rows everytime a button(i.e. bNewEvent) is clicked , so I am incrementing ELEMENT_COUNT by 3 everytime. It works fine for first time , but when I press button second time it crashes.
Here is my adapter class :
public class MyAdapter extends BaseAdapter {
private final LayoutInflater mInflater;
private final String[] mItems;
TextView t;
ViewHolder holder;
public MyAdapter(Activity c,String[] objects) {
mInflater = c.getLayoutInflater();
mItems = objects;
}
public int getCount() {
return mItems.length;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView t;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listitem2, parent,false);
}
holder = new ViewHolder();
holder.t1 = (TextView) convertView.findViewById(R.id.tv1);
holder.t2 = (TextView) convertView.findViewById(R.id.tv2);
holder.t3 = (TextView) convertView.findViewById(R.id.tv3);
holder.t4 = (TextView) convertView.findViewById(R.id.tv4);
holder.t1.setText("Title"+position);
position = position + 3;
//((ImageView)convertView).setTextAlignment(1);
return convertView;
}
#Override
public Object getItem(int position) {
return mItems[position];
}
#Override
public long getItemId(int position) {
return position;
}
}
you can't use an array like this..
String[] elements = new String[ELEMENT_COUNT];
causes the array to have the same number of elements as the initial value of ELEMENT_COUNT, you can't then just increment ELEMENT_COUNT by 3 and try
for (int i = 0; i< ELEMENT_COUNT; i++) {
elements[i] = String.valueOf(i);
}
as the array only contains as many elements are initially defined. You need to change 'elements' to an ArrayList.
ArrayList<string> elements;
U define
int ELEMENT_COUNT = 3;
String[] elements = new String[ELEMENT_COUNT];
But u can't Resize Array
for (int i = 0; i< ELEMENT_COUNT; i++) {
elements[i] = String.valueOf(i);
}
this So u got Exception
Change Array To List
Like
List<String> element =new ArrayList<String>();
for (int i = 0; i< ELEMENT_COUNT; i++) {
element.add("String.valueOf(i)")
}
and Change Adapter also Like This