How to update listview when loading next new items android? - android

hi i have popup button. When I click pop up button, it displays radio button.For every radio button selection, I am fetching datas and updating in UI.
Problem is for first radio button it is updating UI. But for second radio button and so on, UI is not updating. How to solve this?
Code is as follows:
public class DataList extends Activity {
private Button popUpClick;
private Dialog sortFilterDialog;
private RadioGroup radioGroup;
private RadioButton ascToDesradioButton, desToAscradioButton,
highToLowradioButton, lowToHighradioButton, popularityradioButton;
private int popupselectionItem;
private ImageView closeButton;
private String sessionId;
private String sortName,sortOrder;
ArrayList<SortFilterProducts> personsList;
private ListView list;
private DataListAdapter gridAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.sortfilterclick);
personsList= new ArrayList<SortFilterProducts>();
popUpClick = (Button) findViewById(R.id.popupButton);
list=(ListView)findViewById(R.id.sortFilterList);
gridAdapter = new DataListAdapter(this, R.layout.sort_filter_listrow, personsList);
list.setAdapter(gridAdapter);
popUpClick.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sortFilterDialog = new Dialog(SortFilterPopupActivity.this);
sortFilterDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
sortFilterDialog.setContentView(R.layout.sortfilterrow);
radioGroup = (RadioGroup) sortFilterDialog
.findViewById(R.id.radioGroup);
ascToDesradioButton = (RadioButton) sortFilterDialog
.findViewById(R.id.asc_to_des);
desToAscradioButton = (RadioButton) sortFilterDialog
.findViewById(R.id.des_to_asc);
highToLowradioButton = (RadioButton) sortFilterDialog
.findViewById(R.id.high_to_low);
lowToHighradioButton = (RadioButton) sortFilterDialog
.findViewById(R.id.low_to_high);
popularityradioButton = (RadioButton) sortFilterDialog
.findViewById(R.id.popularity);
ascToDesradioButton
.setOnClickListener(radioButtonOnClickListener);
desToAscradioButton
.setOnClickListener(radioButtonOnClickListener);
highToLowradioButton
.setOnClickListener(radioButtonOnClickListener);
lowToHighradioButton
.setOnClickListener(radioButtonOnClickListener);
popularityradioButton
.setOnClickListener(radioButtonOnClickListener);
}
private final OnClickListener radioButtonOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
switch (popupselectionItem = v.getId()) {
case R.id.asc_to_des:
sortName="atoz";
sortOrder="SORT_ASC";
new SortFilterElement().execute();
//new AscToDesElements().execute();
break;
case R.id.des_to_asc:
sortName="atoz";
sortOrder="SORT_DESC";
new SortFilterElement().execute();
//new DescToAscElements().execute();
break;
case R.id.high_to_low:
sortName="lowtohigh";
sortOrder="SORT_ASC";
new SortFilterElement().execute();
//new PriceHightoLow().execute();
break;
case R.id.low_to_high:
sortName="lowtohigh";
sortOrder="SORT_DESC";
//new PriceLowtoHigh().execute();
new SortFilterElement().execute();
break;
case R.id.popularity:
sortName="popularity";
sortOrder="SORT_ASC";
//new Popularity().execute();
new SortFilterElement().execute();
break;
default:
}
sortFilterDialog.dismiss();
}
class SortFilterElement extends AsyncTask<String,String,String>{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog=new ProgressDialog(SortFilterPopupActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected String doInBackground(String... args) {
try {
SoapSerializationEnvelope env = new SoapSerializationEnvelope(
SoapSerializationEnvelope.VER11);
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
if (sessionId == null) {
JSONObject json = new JSONObject();
json.put("page", "1");
json.put("limit", "10");
json.put("sort_name", sortName);
json.put("sort_order", sortOrder);
String params = json.toString();
requests.addProperty("args", params);
env.setOutputSoapObject(requests);
androidHttpTransport.call("", env);
Object results = env.getResponse();
Log.e("Sort results", results.toString());
if (results.toString() != null) {
JSONObject jsono = new JSONObject(results
.toString());
JSONArray jarray = jsono
.getJSONArray("result");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
SortFilterProducts products = new SortFilterProducts();
String id = object.getString("id");
int productPrice = object.getInt("price");
String imageUrl = object
.getString("image_url");
int ratings=object.getInt("ratings");
products.setProductName(productName);
products.setImageUrl(imageUrl);
personsList.add(products);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.cancel();
gridAdapter.notifyDataSetChanged();
}
}
};
});
}
}
and My DataListAdapter:
public class DataListAdapter extends BaseAdapter {
LayoutInflater layoutInflater;
int Resource;
ViewHolder viewHolder;
Activity activity;
public ImageLoader loader;
private final ArrayList<SortFilterProducts> itemLists;
public DataListAdapter(Activity a, int resource,
ArrayList<SortFilterProducts> itemList) {
layoutInflater = (LayoutInflater) a
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
itemLists = itemList;
activity = a;
loader = new ImageLoader(a.getApplicationContext());
}
#Override
public int getCount() {
return itemLists.size();
}
#Override
public Object getItem(int position) {
return itemLists.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v= convertView;
try {
if(v==null){
viewHolder = new ViewHolder();
v = layoutInflater.inflate(Resource, null);
viewHolder.productName=(TextView)v.findViewById(R.id.productName);
viewHolder.productPrice=(TextView)v.findViewById(R.id.price);
v.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder) v.getTag();
}
final String productName=itemLists.get(position).getProductName();
final int productPrice=itemLists.get(position).getProductPrice();
viewHolder.productName.setText(productName);
viewHolder.productPrice.setText(Integer.toString(productPrice));
}
catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
static class ViewHolder {
public TextView productName,productPrice;
}
}

Invalidate the items of the ListView while expanding the ArrayList<SortFilterProducts> passed to adapter.
list.invalidateViews();
Good Luck. :)

As I mention in comments, you should call notifyDataSetChanged() method after adding new objects to your list.
First of all, add following method to your DataListAdapter
public void addItem(SortFilterProducts product) {
itemLists.add(product);
notifyDataSetChanged();
}
Then, remove the line personsList.add(products); on your onCreate() method and add the following line.
DataListAdapter adapter = (DataListAdapter)list.getAdapter();
adapter.addItem(products);
Your ListView automatically updated whenever new item is added.
Hope this may help.

Related

Custom ListView - Duplicate Entries

Main Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] answers = new String[]{"choice0","choice2","choice0","choice1","choice3","choice3"};
Question[] questions = new Question[6];
for(int i=0; i<6; i++){
questions[i] = new Question("Question"+(1+i),new String[]{"choice0","choice1","choice2","choice3"},answers[i]);
}
ListView listView = (ListView)findViewById(R.id.listQuestions);
QuestionAdapter questionAdapter = new QuestionAdapter(this, R.layout.list_item_row_qs, questions);
listView.setAdapter(questionAdapter);
}
}
Adapter
public class QuestionAdapter extends ArrayAdapter {
Context context;
Question[] questions;
View view;
public QuestionAdapter(Context context, int id, Question[] questions){
super(context, id, questions);
this.context = context;
this.questions = questions;
}
private class ViewHolder{
TextView chapName;
RadioButton rb0;
RadioButton rb1;
RadioButton rb2;
RadioButton rb3;
Button button;
RadioGroup rg;
TextView hiddenAnswer;
}
#Override
public View getView(int pos, View row, ViewGroup parent){
this.view = row;
ViewHolder viewHolder = null;
if(row == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(R.layout.list_item_row_qs, null);
viewHolder = new ViewHolder();
viewHolder.chapName=(TextView) row.findViewById(R.id.question);
viewHolder.rb0 = (RadioButton) row.findViewById(R.id.choice0);
viewHolder.rb1 = (RadioButton) row.findViewById(R.id.choice1);
viewHolder.rb2 = (RadioButton) row.findViewById(R.id.choice2);
viewHolder.rb3 = (RadioButton) row.findViewById(R.id.choice3);
viewHolder.button = (Button) row.findViewById(R.id.check);
viewHolder.hiddenAnswer = (TextView) row.findViewById(R.id.answer);
row.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder)row.getTag();
}
viewHolder.chapName.setText(questions[pos].getQuestionDescr());
viewHolder.rb0.setText(questions[pos].getChoice()[0]);
viewHolder.rb1.setText(questions[pos].getChoice()[1]);
viewHolder.rb2.setText(questions[pos].getChoice()[2]);
viewHolder.rb3.setText(questions[pos].getChoice()[3]);
viewHolder.hiddenAnswer.setText(questions[pos].getAnswer());
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View rowView = (ViewGroup) v.getParent();
RadioGroup group = (RadioGroup) rowView.findViewById(R.id.rg);
int selectedId = group.getCheckedRadioButtonId();
if (selectedId == -1) {
Toast.makeText(context, "Please choose the correct option", Toast.LENGTH_LONG).show();
} else {
RadioButton radioButton = (RadioButton) group.findViewById(selectedId);
String answer = String.valueOf(((TextView) rowView.findViewById(R.id.answer)).getText());
if (radioButton.getText().equals(answer)) {
Toast.makeText(context, "Correct Answer", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Wrong Answer", Toast.LENGTH_LONG).show();
}
}
}
});
return row;
}
}
Problem
First item in the list maps to 5th item. 2nd item to sixth item. I mean if I change radio button at the first item, Same radio button gets selected at the 5th list item also.
Any suggestions?
Is it because of recycling?
How do I resolve it?
I tried saving in Question object and retrieving it. I used pos to retrieve and set. But same problem still exist.
Adapter:
public class PersonAdapter extends BaseAdapter
{
private static final int MIN_RECORDS_NUMBER = 11;
private Context _con;
private List<Person> _data;
public PersonAdapter(Context context, List<Person> data)
{
_con = context;
_data = data;
}
#Override
public int getCount()
{
return _data.size();
}
#Override
public Person getItem(int position)
{
return _data.get(position);
}
#Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
Holder h = null;
if (convertView == null)
{
h = new Holder();
convertView = LayoutInflater.from(_con).inflate(R.layout.item_layout, parent, false);
h._backgroundItem = (LinearLayout) convertView.findViewById(R.id.item_layout);
h._fName = (TextView) convertView.findViewById(R.id.f_name);
h._lName = (TextView) convertView.findViewById(R.id.l_name);
h._age = (TextView) convertView.findViewById(R.id.age);
h._editBtn = (Button) convertView.findViewById(R.id.edit_btn);
convertView.setTag(h);
}
else
{
h = (Holder) convertView.getTag();
}
final Person p = getItem(position);
h._fName.setText(p._fName);
h._lName.setText(p._lName);
h._age.setText(String.valueOf(p._age));
h._backgroundItem.setActivated(p._selected);
h._editBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
((MainActivity)_con).onEditClick(p._url);
}
});
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Person p = getItem(position);
Intent i = new Intent(_con,SecondActivity.class);
i.putExtra("DATA", p._fName);
_con.startActivity(i);
}
});
return convertView;
}
public void setData(List<Person> data)
{
_data = data;
notifyDataSetChanged();
}
private static class Holder
{
public LinearLayout _backgroundItem;
public TextView _fName;
public TextView _lName;
public TextView _age;
public Button _editBtn;
}
public interface IDialog
{
public void onEditClick(String url);
}
}
Activity
public class MainActivity extends Activity implements IDialog
{
private ListView _listView;
private PersonAdapter _adapter;
private Button _sortBtn;
private List<Person> _data;
private int _sort;
private int _selectedItemIndex;
private Bitmap _bit;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_listView = (ListView) findViewById(R.id.list);
_sortBtn = (Button) findViewById(R.id.sort_list_btn);
_selectedItemIndex = -1;
_sort = 1;
_data = new ArrayList<Person>();
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","abc", "defg", 1));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","aaa", "defg", 12));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","ccc", "defg", 13));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","bb", "defg", 14));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","aa", "defg", 144));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","fff", "defg", 199));
// _adapter = new PersonAdapter(this, _data);
// _listView.setAdapter(_adapter);
RedirectToMainActivityTask task = new RedirectToMainActivityTask();
task.execute();
_listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
if(position<_data.size())
{
if(_selectedItemIndex>-1)
{
_data.get(_selectedItemIndex)._selected = false;
}
_selectedItemIndex = position;
_data.get(position)._selected = true;
_adapter.setData(_data);
}
}
});
_sortBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if(_selectedItemIndex>-1)
{
_listView.clearChoices();
String fName = _adapter.getItem(_selectedItemIndex)._fName;
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
int newSelectedItemIndex = getSelectedItemIndexByFName(fName);
_selectedItemIndex = newSelectedItemIndex;
_adapter.setData(_data);
if(newSelectedItemIndex>-1)
{
_listView.setItemChecked(newSelectedItemIndex, true);
}
_sort = -_sort;
}
else
{
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
_adapter.setData(_data);
_sort = -_sort;
}
}
});
}
private int getSelectedItemIndexByFName(String name)
{
for(int index=0;index<_data.size();index++)
{
if(_data.get(index)._fName.equals(name))
{
return index;
}
}
return -1;
}
public static class Person
{
public String _url;
public String _fName;
public String _lName;
public int _age;
public boolean _selected;
public Person(String url,String fName, String lName, int age)
{
_url = url;
_fName = fName;
_lName = lName;
_age = age;
}
public static Comparator<Person> getComperatorByFirstName(final int ascendingFlag)
{
return new Comparator<Person>()
{
#Override
public int compare(Person patient1, Person patient2)
{
return patient1._fName.compareTo(patient2._fName) * ascendingFlag;
}
};
}
}
public Bitmap getBitmapFromURL(String src) {
try
{
URL url = new URL(src);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setInstanceFollowRedirects(true);
Bitmap image = BitmapFactory.decodeStream(httpCon.getInputStream());
return image;
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public void onEditClick(final String url)
{
new Thread(new Runnable()
{
#Override
public void run()
{
_bit = getBitmapFromURL(url);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_image);
ImageView image = (ImageView) dialog.findViewById(R.id.image);
if(_bit!=null)
{
image.setImageBitmap(_bit);
}
dialog.setTitle("This is my custom dialog box");
dialog.setCancelable(true);
//there are a lot of settings, for dialog, check them all out!
dialog.show();
}
});
}
}).start();
}
private class RedirectToMainActivityTask extends AsyncTask<Void, Void, Void>
{
protected Void doInBackground(Void... params)
{
try
{
Thread.sleep( 2 * 1000 );
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
Intent intent = new Intent( getApplicationContext(), SecondActivity.class );
intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
startActivity( intent );
}
}
}
I am saving the state of the person view inside of person object

On Scrolling Of listview radio button is automatically changing its state and some are previously checked in android

it is list of student selected by me it is list of student already selected when i scroll list in my custom list view when i am running application then radio buttons at bottom are already checked when i am checking upper radio button .how can i set radio button so that its state never change on scrolling list .
Here is my code for studentlist.java
public class studentlist extends AppCompatActivity {
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "id";
private static final String TAG_ClassDet = "classdetails";
private static final String TAG_YEAR = "yearof";
private static final String TAG_BRANCH ="branchof";
private static final String TAG_SECTION ="sectionof";
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private ArrayList<HashMap<String, String>> studentattendence,studentstatus;
ListView listView;
ArrayAdapter<Model> adapter;
List<Model> list = new ArrayList<Model>();
public ArrayList<HashMap<String, String>> personList;
private static final String KEY_STUDENT = "student";
private RadioGroup radioGroup;
private RadioButton radiobtn;
public Button ok;
private RadioButton radioButton;
HashMap<String, String> contact,contactstatus;
private String convertjson;
private String statusofattendence;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.liststudent);
listView = (ListView) findViewById(R.id.my_list);
studentattendence=new ArrayList<HashMap<String, String>>();
studentstatus=new ArrayList<HashMap<String, String>>();
personList = new ArrayList<HashMap<String, String>>();
Intent getstud = getIntent();
personList = (ArrayList<HashMap<String, String>>) getstud.getSerializableExtra(KEY_STUDENT);
ok= (Button) findViewById(R.id.ok);
Toast.makeText(getApplicationContext(), pioGroup.ersonList.get(0).get("enrolment") + "" + personList.get(1).get("enrolment") + "" + personList.get(2).get("enrolment"), Toast.LENGTH_LONG).show();
adapter = new MyAdapter(this, getModel(personList));
listView.setAdapter(adapter);
radioGroup = (RadioGroup) findViewById(R.id.radio);
listView.childDrawableStateChanged(radioGroup);
////ok button click get status of each radio button and store in hashmap
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int child=listView.getChildCount();
ArrayList<String> radio=new ArrayList<>();
View[] vy = new View[1];
Log.d("child", String.valueOf(child));
for(int i=0;i<child;i++) {
// RadioGroup rd = (RadioGroup) listView.getChildAt(i);
View rgg=listView.getChildAt(i);
Log.d("radioview",String.valueOf(rgg));
radioGroup = (RadioGroup) rgg.findViewById(R.id.radio);
Log.d("radiogroup", String.valueOf(radioGroup));
int selectedId=radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton) rgg.findViewById(selectedId);
TextView tv= (TextView) rgg.findViewById(R.id.label);
Log.d("radiobutton and id", selectedId + "" + radioButton);
String status= radioButton.getText().toString();
Log.d("hello",status);
String enrol=tv.getText().toString();
contact = new HashMap<String, String>();
contact.put("enrollmentnum",enrol);
Log.d("enum",enrol);
studentattendence.add(contact);
contactstatus = new HashMap<String, String>();
contactstatus.put("status",status);
Log.d("ststuss",status);
studentstatus.add(contactstatus);
}
///here converting arraylist in to json string
convertjson = new Gson().toJson(studentattendence);
statusofattendence=new Gson().toJson(studentstatus);
Toast.makeText(getApplicationContext(),""+convertjson+""+statusofattendence,Toast.LENGTH_LONG).show();
NetAsync(v, convertjson,statusofattendence);
}
});
}
private List<Model> getModel(ArrayList<HashMap<String, String>> personList) {
for (int i = 0; i < personList.size(); i++) {
String enrolment = personList.get(i).get("enrolment");
list.add(new Model(enrolment));
}
return list;
}
////now we will send taked attendence to webservice
private class NetCheck extends AsyncTask<String,String,Boolean>
{
public final String convertjson,statusofattendence;
private ProgressDialog nDialog;
public NetCheck(String convertjson,String statusofattendence) {
this.convertjson=convertjson;
this.statusofattendence=statusofattendence;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
nDialog = new ProgressDialog(studentlist.this);
nDialog.setMessage("Loading..");
nDialog.setTitle("Checking Network");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected Boolean doInBackground(String... args) {
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
/*
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
// return false;
return true;
}
#Override
protected void onPostExecute(Boolean th) {
if (th == true) {
nDialog.dismiss();
new ProcessRegister().execute();
} else {
nDialog.dismiss();
}
}
}
private class ProcessRegister extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String forgotpassword;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(studentlist.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
TeacherFunctions userFunction = new TeacherFunctions();
Log.d("convertjson",convertjson);
Log.d("convertjson",statusofattendence);
JSONObject json = userFunction.addAttendence(convertjson,statusofattendence);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
/**
* Checks if the Password Change Process is sucesss
**/
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
String red = json.getString(KEY_ERROR);
if(Integer.parseInt(res) == 1){
pDialog.dismiss();
Toast.makeText(getApplicationContext(),"students Attendence Uploaded successfully"+json.getString("user"),Toast.LENGTH_LONG).show();
}
else if (Integer.parseInt(red) == 2)
{ pDialog.dismiss();
}
else {
pDialog.dismiss();
}
}}
catch (JSONException e) {
e.printStackTrace();
pDialog.dismiss();
Toast.makeText(getApplicationContext()," not Uploaded successfully"+e,Toast.LENGTH_LONG).show();
}
}}
public void NetAsync(View view, String convertjson,String statusofattendence){
new NetCheck(convertjson,statusofattendence).execute();
}
}
Code for model.java
public class Model {
private String name;
private boolean selected;
public Model(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
code for MyAdapter.java
public class MyAdapter extends ArrayAdapter<Model> {
private final List<Model> list;
private final Activity context;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
public MyAdapter(Activity context, List<Model> list) {
super(context, R.layout.row, list);
this.context = context;
this.list = list;
}
static class ViewHolder {
protected TextView text;
protected RadioButton radiobox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.row, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.label);
viewHolder.radiobox = (RadioButton) convertView.findViewById(R.id.radio1);
viewHolder.radiobox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.label, viewHolder.text);
convertView.setTag(R.id.radio1, viewHolder.radiobox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.radiobox.setTag(position); // This line is important.
viewHolder.text.setText(list.get(position).getName());
viewHolder.radiobox.setChecked(list.get(position).isSelected());
return convertView;
}
}
You are using setOnCheckedChangeListener() on viewHolder.radiobox. it is very bad code for that, because each time convertView getting null to view then setOnCheckedChangeListener() also called. And it set your modal data to next position. If you want to check it just put Log in onCheckedChange or try to put breakpoint in it.
just try this :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.row, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.label);
viewHolder.radiobox = (RadioButton) convertView.findViewById(R.id.radio1);
convertView.setTag(viewHolder);
convertView.setTag(R.id.label, viewHolder.text);
convertView.setTag(R.id.radio1, viewHolder.radiobox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.radiobox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if(viewHolder.radiobox.isChecked())
{
viewHolder.radiobox.setChecked(false);
}
else
{
viewHolder.radiobox.setChecked(true);
}
list.get(getPosition).setChecked( viewHolder.radiobox.isChecked()); // Set the value of checkbox to maintain its state.
}
});
viewHolder.text.setText(list.get(position).getName());
viewHolder.radiobox.setChecked(list.get(position).isChecked());
return convertView;
}
hope it will help you.
enter code here
getListView().setOnScrollListener(this);***
enter code here
public void onScroll(AbsListView view, int firstCell, int cellCount, int itemCount) {
RadioButton rb1 = (RadioButton) findViewById(R.id.option1);
rb1.setChecked(flase);
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
Actually everything was not working properly and then i had moved to listview with 4 button in place of radio button.

How to refresh fragment from out of activity or fragment but from baseAdapter class

I have some problem. when I click a delete(btnPlus.setOnClickListener in the interestAdepter class) button from listview baseAdapter, I want to refresh the fragment which contains the listview.
1.InterestAdapter class{edtied}
public class InterestAdapter extends BaseAdapter{
private ArrayList<InterestClass> m_List;
public InterestAdapter() {
m_List = new ArrayList<InterestClass>();
}
#Override
public int getCount() {
return m_List.size();
}
#Override
public Object getItem(int position) {
return m_List.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
final Context context = parent.getContext();
TextView textName = null;
TextView textDate = null;
TextView textConPrice = null;
TextView textNowPrice = null;
TextView textFog = null;
ImageButton btnPlus = null;
CustomHolder holder = null;
if ( convertView == null ) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_interest, parent, false);
textName = (TextView) convertView.findViewById(R.id.i_ProdNmae);
textDate = (TextView) convertView.findViewById(R.id.i_Date);
textConPrice = (TextView) convertView.findViewById(R.id.i_InterPrice);
textNowPrice = (TextView) convertView.findViewById(R.id.i_currentPrice);
textFog = (TextView) convertView.findViewById(R.id.i_Analysis);
btnPlus = (ImageButton) convertView.findViewById(R.id.i_addBtn);
holder = new CustomHolder();
holder.i_TextView = textName;
holder.i_TextView1 = textDate;
holder.i_TextView2 = textConPrice;
holder.i_TextView3 = textNowPrice;
holder.i_TextView4 = textFog;
holder.i_Btn = btnPlus;
convertView.setTag(holder);
}
else {
holder = (CustomHolder) convertView.getTag();
textName = holder.i_TextView;
textDate = holder.i_TextView1;
textConPrice = holder.i_TextView2;
textNowPrice = holder.i_TextView3;
textFog = holder.i_TextView4;
btnPlus = holder.i_Btn;
}
/*if(position == 0) {
textName.setText("종목");
textDate.setText("관심일");
textConPrice.setText("관심가");
textNowPrice.setText("현재가");
textFog.setText("수급");
btnPlus.setEnabled(false);
}else{
}*/
textName.setText(m_List.get(position).getName());
textDate.setText(m_List.get(position).getDate());
textConPrice.setText(m_List.get(position).getConPrice());
textNowPrice.setText(m_List.get(position).getNowPrice());
textFog.setText(m_List.get(position).getFog());
btnPlus.setEnabled(true);
textName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailActivity.class);
context.startActivity(intent);
}
});
btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Crypto enc = new Crypto();
SharedPreferences pref = context.getSharedPreferences("com.rabiaband.pref", 0);
String[] add_Params = new String[2];
try {
add_Params[0] = enc.AES_Encode(pref.getString("no", null), enc.global_deckey);
add_Params[1] = enc.AES_Encode(m_List.get(pos).getJmcode(), enc.global_deckey);
} catch (Exception e) {
Log.e("HomeCryptographError:", "" + e.getMessage());
}
AsyncCallAddDelFavorite delFavorite = new AsyncCallAddDelFavorite();
delFavorite.execute(add_Params);
}
});
private class AsyncCallAddDelFavorite extends AsyncTask<String, Void, Void> {
JSONObject del_Favorite_List;
/* public AsyncCallAddFavorite(HomeFragment home){
this.home=home;
}*/
#Override
protected void onPreExecute() {
/*Log.i(TAG, "onPreExecute");*/
}
#Override
protected Void doInBackground(String... params) {
dbConnection db_Cont=new dbConnection();
String id=params[0];
String jmcode=params[1];
Log.v("doinbackgroud",""+id+"ssssss"+jmcode);
del_Favorite_List=db_Cont.delFavorite(id, jmcode);
Log.v("doinbackgroud",del_Favorite_List.toString());
return null;
}
#Override
protected void onPostExecute(Void result) {
/*Log.i(TAG, "onPostExecute");*/
}
}
}
2.InterestFragment{edited}
public class InterestFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private ListView interest_ListView;
private InterestAdapter interest_Adapter;
String TAG="response";
RbPreference keep_Login;
public InterestFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment InterestFragment.
*/
// TODO: Rename and change types and number of parameters
public static InterestFragment newInstance(String param1, String param2) {
InterestFragment fragment = new InterestFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
keep_Login = new RbPreference(getContext());
Log.v("interFrag","oncreate");
// Inflate the layout for this fragment
/*if(keep_Login.get("name",null)!=null) {
return inflater.inflate(R.layout.fragment_interest, container, false);
}else{
return inflater.inflate(R.layout.need_login, container, false);
}*/
return inflater.inflate(R.layout.fragment_interest, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.v("ListFragment", "onActivityCreated().");
Log.v("ListsavedInstanceState", savedInstanceState == null ? "true" : "false");
if(keep_Login.get("no",null)!=null) {
String enc_Id="";
Crypto enc=new Crypto();
try{
enc_Id=enc.AES_Encode(keep_Login.get("no",null),enc.global_deckey);
}catch(Exception e){
}
interest_Adapter = new InterestAdapter();
interest_ListView = (ListView) getView().findViewById(R.id.i_ListView);
AsyncCallInterest task = new AsyncCallInterest();
task.execute(enc_Id);
}
}
private class AsyncCallInterest extends AsyncTask<String, Void, JSONArray> {
JSONArray interest_Array;
InterestFragment interest;
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
#Override
protected JSONArray doInBackground(String... params) {
String id=params[0];
dbConnection db_Cont=new dbConnection();
interest_Array=db_Cont.getFavorite(id);
Log.v("doinbackgroud", interest_Array.toString());
return interest_Array;
}
#Override
protected void onPostExecute(JSONArray result) {
try{
for (int i = 0 ; i < result.length() ; i ++){
InterestClass i_Class = new InterestClass();
String date=result.getJSONObject(i).getString("indate");
String time=date.substring(5,date.length());
i_Class.setJmcode(result.getJSONObject(i).getString("jmcode"));
i_Class.setName(result.getJSONObject(i).getString("jmname"));
i_Class.setDate(time);
i_Class.setConPrice(result.getJSONObject(i).getString("fprice"));
i_Class.setNowPrice(result.getJSONObject(i).getString("price"));
i_Class.setFog("40");
i_Class.setPlus(true);
interest_Adapter.add(i_Class);
}
interest_ListView.setAdapter(interest_Adapter);
}catch(Exception e){
Toast.makeText(getActivity(), "interest"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
}
Is there any way to refresh the fragment from the button in baseAdapter class? I searched a lot but I couldn't fine answer. Please help me, Thank you.
{edited}
I add AsyncCallAddDelFavorite class and AsyncCallInterest class. Thank you.
Update your adapter constructor. After deleting content, remove the item from the arraylist and notify dataset changed.
public class InterestAdapter extends BaseAdapter{
private ArrayList<InterestClass> m_List;
private Context mContext;
public InterestAdapter(Context context, ArrayList<InterestClass> list) {
m_List = list;
mContext = context;
}
#Override
public int getCount() {
return m_List.size();
}
#Override
public Object getItem(int position) {
return m_List.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final int pos = position;
final Context context = parent.getContext();
TextView textName = null;
TextView textDate = null;
TextView textConPrice = null;
TextView textNowPrice = null;
TextView textFog = null;
ImageButton btnPlus = null;
CustomHolder holder = null;
if ( convertView == null ) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_interest, parent, false);
textName = (TextView) convertView.findViewById(R.id.i_ProdNmae);
textDate = (TextView) convertView.findViewById(R.id.i_Date);
textConPrice = (TextView) convertView.findViewById(R.id.i_InterPrice);
textNowPrice = (TextView) convertView.findViewById(R.id.i_currentPrice);
textFog = (TextView) convertView.findViewById(R.id.i_Analysis);
btnPlus = (ImageButton) convertView.findViewById(R.id.i_addBtn);
holder = new CustomHolder();
holder.i_TextView = textName;
holder.i_TextView1 = textDate;
holder.i_TextView2 = textConPrice;
holder.i_TextView3 = textNowPrice;
holder.i_TextView4 = textFog;
holder.i_Btn = btnPlus;
convertView.setTag(holder);
}
else {
holder = (CustomHolder) convertView.getTag();
textName = holder.i_TextView;
textDate = holder.i_TextView1;
textConPrice = holder.i_TextView2;
textNowPrice = holder.i_TextView3;
textFog = holder.i_TextView4;
btnPlus = holder.i_Btn;
}
/*if(position == 0) {
textName.setText("종목");
textDate.setText("관심일");
textConPrice.setText("관심가");
textNowPrice.setText("현재가");
textFog.setText("수급");
btnPlus.setEnabled(false);
}else{
}*/
textName.setText(m_List.get(position).getName());
textDate.setText(m_List.get(position).getDate());
textConPrice.setText(m_List.get(position).getConPrice());
textNowPrice.setText(m_List.get(position).getNowPrice());
textFog.setText(m_List.get(position).getFog());
btnPlus.setEnabled(true);
textName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailActivity.class);
context.startActivity(intent);
}
});
btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Crypto enc = new Crypto();
SharedPreferences pref = context.getSharedPreferences("com.rabiaband.pref", 0);
String[] add_Params = new String[2];
try {
add_Params[0] = enc.AES_Encode(pref.getString("no", null), enc.global_deckey);
add_Params[1] = enc.AES_Encode(m_List.get(pos).getJmcode(), enc.global_deckey);
} catch (Exception e) {
Log.e("HomeCryptographError:", "" + e.getMessage());
}
AsyncCallAddDelFavorite delFavorite = new AsyncCallAddDelFavorite();
delFavorite.execute(add_Params);
**m_List.remove(position);
notifyDatasetChanged();**
}
});
private class AsyncCallAddDelFavorite extends AsyncTask<String, Void, Void> {
JSONObject del_Favorite_List;
/* public AsyncCallAddFavorite(HomeFragment home){
this.home=home;
}*/
#Override
protected void onPreExecute() {
/*Log.i(TAG, "onPreExecute");*/
}
#Override
protected Void doInBackground(String... params) {
dbConnection db_Cont=new dbConnection();
String id=params[0];
String jmcode=params[1];
Log.v("doinbackgroud",""+id+"ssssss"+jmcode);
del_Favorite_List=db_Cont.delFavorite(id, jmcode);
Log.v("doinbackgroud",del_Favorite_List.toString());
return null;
}
#Override
protected void onPostExecute(Void result) {
/*Log.i(TAG, "onPostExecute");*/
}
}
}
Update Adapter initialization in fragment. You are adding item to adapter directly. Use arraylist and after downloading data create adapter instance.
private ArrayList<InterestClass> interestList = new ArrayList<>();
and update your onPostExecute Method
#Override
protected void onPostExecute(JSONArray result) {
try{
for (int i = 0 ; i < result.length() ; i ++){
InterestClass i_Class = new InterestClass();
String date=result.getJSONObject(i).getString("indate");
String time=date.substring(5,date.length());
i_Class.setJmcode(result.getJSONObject(i).getString("jmcode"));
i_Class.setName(result.getJSONObject(i).getString("jmname"));
i_Class.setDate(time);
i_Class.setConPrice(result.getJSONObject(i).getString("fprice"));
i_Class.setNowPrice(result.getJSONObject(i).getString("price"));
i_Class.setFog("40");
i_Class.setPlus(true);
interestList.add(i_Class);
}
interest_Adapter = new InterestAdapter(getActivity,interestList);
interest_ListView.setAdapter(interest_Adapter);
}catch(Exception e){
Toast.makeText(getActivity(), "interest"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
If I understand you correctly you want to remove the item from your ListView too after your removing it from your Database, to achieve that you can call this
m_List.remove(position);
interest_Adapter..notifyDataSetChanged();
First line removes the item and Second one will insure that the Adapter gets updated after the item has been removed.
Hope this helps

How to set listview row clickable only one time in android?

Explanation:
I have a listview in my fragment. When I click one of the row of the listview it goes to another activity.In listview,I got the data from the adapter.
Inside the adapter view,I set the setOnClick().
Problem is when I click one of the row multiple time it is opening multiple activity.I want to restrict only one time click on the particular row over the listview item.
Here is my fragment where I get the listview and set the adapter-
public class HomeFragment extends Fragment{
public HomeFragment() {
}
public static String key_updated = "updated", key_description = "description", key_title = "title", key_link = "link", key_url = "url", key_name = "name", key_description_text = "description_text";
private static String url = "";
List<String> lst_key = null;
List<JSONObject> arr_completed = null;
List<String> lst_key2 = null;
List<JSONObject> lst_obj = null;
List<String> list_status = null;
ListView completed_listview;
int PagerLength = 0,exeption_flag=0;
View rootView;
private ViewPager pagerRecentMatches;
private ImageView imgOneSliderRecent;
private ImageView imgTwoSliderRecent;
private ImageView imgThreeSliderRecent;
private ImageView imgFourSliderRecent;
private ImageView imgFiveSliderRecent;
private ImageView imgSixSliderRecent;
private ImageView imgSevenSliderRecent;
private ImageView imgEightSliderRecent;
LinearLayout selector_dynamic;
LinearLayout Recent_header_layout;
FrameLayout adbar;
String access_token = "";
SharedPreferences sharedPreferences;
int current_pos=0,status_flag=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
findViews();
selector_dynamic = (LinearLayout) rootView.findViewById(R.id.selectors_dynamic);
adbar = (FrameLayout) rootView.findViewById(R.id.adbar);
new AddLoader(getContext()).LoadAds(adbar);
MainActivity activity = (MainActivity) getActivity();
access_token = activity.getMyData();
sharedPreferences = getContext().getSharedPreferences("HomePref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (access_token == null || access_token=="") {
url = "https://api.litzscore.com/rest/v2/recent_matches/?access_token=" + sharedPreferences.getString("access_token", null) + "&card_type=summary_card";
} else {
editor.putString("access_token", access_token);
editor.commit();
url = "https://api.litzscore.com/rest/v2/recent_matches/?access_token=" + access_token + "&card_type=summary_card";
}
completed_listview = (ListView) rootView.findViewById(R.id.completed_listview);
Recent_header_layout = (LinearLayout) rootView.findViewById(R.id.Recent_header_layout);
Recent_header_layout.setVisibility(View.GONE);
if(!Utils.isNetworkConnected(getContext())){
dialog_popup();
}
else{
new TabJson().execute();
}
pagerRecentMatches.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
return rootView;
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void dialog_popup() {
final Dialog dialog = new Dialog(getContext());
DisplayMetrics metrics = getResources()
.getDisplayMetrics();
int screenWidth = (int) (metrics.widthPixels * 0.90);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.internet_alert_box);
dialog.getWindow().setLayout(screenWidth, WindowManager.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(true);
Button btnNo = (Button) dialog.findViewById(R.id.btn_no);
Button btnYes = (Button) dialog.findViewById(R.id.btn_yes);
btnNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
getActivity().finish();
}
});
dialog.show();
btnYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!Utils.isNetworkConnected(getContext())){
dialog_popup();
}
else{
dialog.dismiss();
new TabJson().execute();
}
}
});
dialog.show();
}
public class TabJson extends AsyncTask<String, String, String> {
String jsonStr = "";
#Override
protected void onPreExecute() {
Utils.Pdialog(getContext());
}
#Override
protected String doInBackground(String... params) {
jsonStr = new CallAPI().GetResponseGetMethod(url);
exeption_flag=0;
status_flag = 0;
if (jsonStr != null) {
try {
if (jsonStr.equals("IO") || jsonStr.equals("MalFormed") || jsonStr.equals("NotResponse")) {
exeption_flag = 1;
} else {
JSONObject obj = new JSONObject(jsonStr);
if (obj.has("status") && !obj.isNull("status")) {
if (obj.getString("status").equals("false") || obj.getString("status").equals("403")) {
status_flag = 1;
} else {
JSONObject data = obj.getJSONObject("data");
JSONArray card = data.getJSONArray("cards");
PagerLength = 0;
lst_obj = new ArrayList<>();
list_status = new ArrayList<>();
lst_key = new ArrayList<>();
lst_key2 = new ArrayList<>();
arr_completed = new ArrayList<>();
for (int i = 0; i < card.length(); i++) {
JSONObject card_obj = card.getJSONObject(i);
if (card_obj.getString("status").equals("started")) {
PagerLength++;
lst_obj.add(card_obj);
list_status.add(card_obj.getString("status"));
lst_key.add(card_obj.getString("key"));
}
if (card_obj.getString("status").equals("notstarted")) {
PagerLength++;
lst_obj.add(card_obj);
list_status.add(card_obj.getString("status"));
lst_key.add(card_obj.getString("key"));
}
if (card_obj.getString("status").equals("completed")) {
arr_completed.add(card_obj);
lst_key2.add(card_obj.getString("key"));
}
}
}
}
}
}
catch(JSONException e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Utils.Pdialog_dismiss();
if (status_flag == 1 || exeption_flag==1) {
dialog_popup();
} else {
Recent_header_layout.setVisibility(View.VISIBLE);
LiveAdapter adapterTabRecent = new LiveAdapter(getContext(), lst_obj, PagerLength, list_status, lst_key);
adapterTabRecent.notifyDataSetChanged();
pagerRecentMatches.setAdapter(adapterTabRecent);
pagerRecentMatches.setCurrentItem(current_pos);
ScheduleAdapter CmAdapter = new ScheduleAdapter(getContext(), arr_completed, lst_key2);
CmAdapter.notifyDataSetChanged();
completed_listview.setAdapter(CmAdapter);
}
}
}
private void findViews() {
pagerRecentMatches = (ViewPager) rootView
.findViewById(R.id.pager_recent_matches);
imgOneSliderRecent = (ImageView) rootView
.findViewById(R.id.img_one_slider_recent);
imgTwoSliderRecent = (ImageView) rootView
.findViewById(R.id.img_two_slider_recent);
imgThreeSliderRecent = (ImageView) rootView
.findViewById(R.id.img_three_slider_recent);
imgFourSliderRecent=(ImageView)rootView.findViewById(R.id.img_four_slider_recent);
imgFiveSliderRecent=(ImageView)rootView.findViewById(R.id.img_five_slider_recent);
imgSixSliderRecent=(ImageView)rootView.findViewById(R.id.img_six_slider_recent);
imgSevenSliderRecent = (ImageView) rootView.findViewById(R.id.img_seven_slider_recent);
imgEightSliderRecent = (ImageView) rootView.findViewById(R.id.img_eight_slider_recent);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
After load the data from the server it passed to the onPost() i called an adapter which extends BaseAdpter
Here is my BaseAdapter
package adapter;
public class ScheduleAdapter extends BaseAdapter{
private Context context;
private List<JSONObject> arr_schedule;
private List<String> arr_matchKey;
private static LayoutInflater inflater;
int flag = 0;
String time="";
String status="";
String match_title = "";
String match_key="";
public ScheduleAdapter(Context context,List<JSONObject> arr_schedule,List<String> arr_matchKey){
this.context=context;
this.arr_schedule=arr_schedule;
this.arr_matchKey=arr_matchKey;
inflater=(LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.arr_schedule.size();
}
#Override
public Object getItem(int position) {
return this.arr_schedule.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class Holder{
TextView txt_one_country_name;
TextView txt_two_country_name;
TextView txt_venue;
TextView txtTimeGMT;
TextView txtDate;
TextView txtTimeIST;
ImageView team_one_flag_icon;
ImageView team_two_flag_icon;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Holder holder=new Holder();
String[] parts;
String[] state_parts;
String[] match_parts;
Typeface tf=null;
String winner_team = "";
String final_Score="";
String now_bat_team="",team_name="";
String related_status="";
if(convertView==null) {
convertView = inflater.inflate(R.layout.recent_home_layout, null);
holder.txt_one_country_name = (TextView) convertView.findViewById(R.id.txt_one_country_name);
holder.txt_two_country_name = (TextView) convertView.findViewById(R.id.txt_two_country_name);
holder.txt_venue = (TextView) convertView.findViewById(R.id.venue);
holder.txtTimeIST = (TextView) convertView.findViewById(R.id.txt_timeist);
holder.txtTimeGMT = (TextView) convertView.findViewById(R.id.txt_timegmt);
holder.txtDate = (TextView) convertView.findViewById(R.id.txt_date);
holder.team_one_flag_icon = (ImageView) convertView.findViewById(R.id.team_one_flag_icon);
holder.team_two_flag_icon = (ImageView) convertView.findViewById(R.id.team_two_flag_icon);
tf = Typeface.createFromAsset(convertView.getResources().getAssets(), "Roboto-Regular.ttf");
holder.txt_one_country_name.setTypeface(tf);
holder.txt_two_country_name.setTypeface(tf);
holder.txt_venue.setTypeface(tf);
holder.txtTimeIST.setTypeface(tf);
holder.txtTimeGMT.setTypeface(tf);
holder.txtDate.setTypeface(tf);
convertView.setTag(holder);
}
else{
holder=(Holder)convertView.getTag();
}
try {
String overs="";
String wickets_now="";
String now_runs="";
String[] over_parts;
time = "";
JSONObject mainObj = this.arr_schedule.get(position);
status = mainObj.getString("status");
String name = mainObj.getString("short_name");
String state = mainObj.getString("venue");
String title = mainObj.getString("title");
related_status=mainObj.getString("related_name");
JSONObject start_date = mainObj.getJSONObject("start_date");
JSONObject teams=null;
JSONObject team_a=null;
JSONObject team_b=null;
String team_a_key="";
String team_b_key="";
time = start_date.getString("iso");
parts = name.split("vs");
match_parts = title.split("-");
state_parts = state.split(",");
int length = state_parts.length;
flag=0;
match_title="";
winner_team="";
if (!mainObj.isNull("msgs")) {
JSONObject msgs = mainObj.getJSONObject("msgs");
winner_team = "";
if (msgs.has("info")) {
winner_team = msgs.getString("info");
flag = 1;
}
}
match_title=name+" - "+match_parts[1];
JSONObject now=null;
if(mainObj.has("now") && !mainObj.isNull("now")) {
now = mainObj.getJSONObject("now");
if (now.has("batting_team")) {
now_bat_team = now.getString("batting_team");
}
if (now.has("runs")) {
if (now.getString("runs").equals("0")) {
now_runs = "0";
} else {
now_runs = now.getString("runs");
}
}
if (now.has("runs_str") && !now.isNull("runs_str")) {
if (now.getString("runs_str").equals("0")) {
overs = "0";
} else {
if(now.getString("runs_str").equals("null")){
overs="0";
}
else{
over_parts=now.getString("runs_str").split(" ");
overs=over_parts[2];
}
}
}
if (now.has("wicket")) {
if (now.getString("wicket").equals("0")) {
wickets_now = "0";
} else {
wickets_now = now.getString("wicket");
}
}
}
try {
if (!mainObj.isNull("teams") && mainObj.has("teams")) {
teams = mainObj.getJSONObject("teams");
team_a = teams.getJSONObject("a");
team_b = teams.getJSONObject("b");
team_a_key = team_a.getString("key");
team_b_key = team_b.getString("key");
JSONArray team_arr = teams.names();
JSONObject team_obj;
for (int a = 0; a < team_arr.length(); a++) {
if (now_bat_team.equals(team_arr.getString(a))) {
team_obj = teams.getJSONObject(team_arr.getString(a));
if (team_obj.has("short_name") && !team_obj.isNull("short_name")) {
team_name = team_obj.getString("short_name");
}
}
}
}
}
catch (NullPointerException e){
e.printStackTrace();
}
if(mainObj.has("status_overview") && !mainObj.isNull("status_overview")){
if(mainObj.getString("status_overview").equals("abandoned") || mainObj.getString("status_overview").equals("canceled")){
final_Score="";
}
else{
final_Score=team_name+" - "+now_runs+"/"+wickets_now+" ("+overs+" ovr)";
}
}
holder.txt_one_country_name.setText(parts[0]);
holder.txt_two_country_name.setText(parts[1]);
if(length==1){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
holder.txtTimeGMT.setText(state_parts[0]);
}
if(length==2){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
holder.txtTimeGMT.setText(state_parts[0] + "," + state_parts[1]);
}
if(length==3){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
holder.txtTimeGMT.setText(state_parts[1] + "," + state_parts[2]);
}
if(length==4){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
holder.txtTimeGMT.setText(state_parts[2] + "," + state_parts[3]);
}
holder.txtDate.setText(final_Score);
holder.txtDate.setTypeface(tf, Typeface.BOLD);
holder.txtDate.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
holder.txtTimeIST.setText(winner_team);
holder.txt_venue.setText(related_status);
} catch (JSONException e) {
e.printStackTrace();
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
match_key = arr_matchKey.get(position);
MainActivity activity = (MainActivity) context;
GetValue gv = new GetValue(context);
gv.setFullUrl(match_key);
gv.setAccessToken(activity.getMyData());
gv.execute();
}
});
return convertView;
}
#Override
public boolean isEnabled(int position) {
return super.isEnabled(position);
}
}
This adapter set the listrow item into listview.
In ScheduleAdapter.java i set the onclick() on the convertView in which i called a GetValue class which is only implement a Asynctask to get the data and called and intent then it goes to an activity.
Means HomeFragment->ScheduleAdapter->GetValue->Scorecard
Here,
HomeFragment is fragment which have listview
ScheduleAdpter is an adapter which set data to listview which reside in homefragment
GetValue is class which implement some important task and it passed an intent and goes to an activity(It's work as a background)
ScoreCard is my activity which called after click on the row of the listview which reside in HomeFragment.
Please, help me to solve out this problem.
You can use a flag in Listview click - isListClicked, and set flag value as false in onPostexecute method of Aysnc task class -GetValue
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isListClicked){
match_key = arr_matchKey.get(position);
MainActivity activity = (MainActivity) context;
GetValue gv = new GetValue(context);
gv.setFullUrl(match_key);
gv.setAccessToken(activity.getMyData());
gv.execute();
isListClicked = true;
}
}
});
If you want to prevent multiple activities being opened when the user spams with touches, add into your onClick event the removal of that onClickListener so that the listener won't exist after the first press.
Easy way is you can create a model class of your json object with those field you taken in holder class. And add one more boolean field isClickable with by default with true value.Now when user press a row for the first time you can set your model class field isClickable to false. Now second time when user press a row,you will get a position of row and you can check for isClickable. it will return false this time.
Model Class :
public class CountryInfoModel {
//other fields to parse json object
private boolean isClickable; //<- add one more extra field
public boolean isClickable() {
return isClickable;
}
public void setIsClickable(boolean isClickable) {
this.isClickable = isClickable;
}
}
listview click perform :
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//country_list is your list of model class List<CountryInfo>
if(country_list.get(position).isClickable())
{
//Perform your logic
country_list.get(position).setIsClickable(false);
}else{
//Do nothing : 2nd time click
}
}
});
Try creating your custom click listener for your listview and use it. In this way
public abstract class OnListItemClickListener implements OnItemClickListener {
private static final long MIN_CLICK_INTERVAL=600;
private long mLastClickTime;
public abstract void onListItemSingleClick(View parent, View view, int position, long id);
public OnListItemClickListener() {
// TODO Auto-generated constructor stub
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
long currentClickTime=SystemClock.uptimeMillis();
long elapsedTime=currentClickTime-mLastClickTime;
mLastClickTime=currentClickTime;
if(elapsedTime<=MIN_CLICK_INTERVAL)
return;
onListItemSingleClick(parent, view, position, id);
}
}

Append new elements from custom adapter to ListView

I've got a ListView with a 'show next results' button. The list is filled by a custom adapter extending BaseAdapter. Using it as shown below, only the new results are shown.
How can I append the new results to the list?
ListView listView = (ListView)findViewById(android.R.id.list);
// Show next results button
View footerView = ((LayoutInflater)ItemList.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
listView.addFooterView(footerView);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = getIntent();
i.putExtra("firstIndex", mFirstIndex + NRES_PER_PAGE);
i.putExtra("itemCount", NRES_PER_PAGE);
startActivity(i);
}
});
mItems = json.getJSONArray("data");
setListAdapter(new ItemAdapter(ItemList.this, mType, mItems));
FIX
ListActivity
public class ItemList extends MenuListActivity{
ItemAdapter mItemAdapter;
Integer mFirstIndex = 0;
JSONArray mItems = new JSONArray();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item_list);
// Set data adapter
mItemAdapter = new ItemAdapter(ItemList.this, mType, mItems);
ListView listView = (ListView)findViewById(android.R.id.list);
View footerView = ((LayoutInflater)ItemList.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
listView.addFooterView(footerView);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
progressDialog = MyProgressDialog.show(ItemList.this, null, null);
mFirstIndex = mFirstIndex + ITEM_COUNT;
new GetItemInfoList().execute();
}
});
setListAdapter(mItemAdapter);
new GetItemInfoList().execute();
}
private class GetItemInfoList extends AsyncTask<Void, Void, JSONObject> {
protected JSONObject doInBackground(Void... params) {
// Set POST data to send to web service
List<NameValuePair> postData = new ArrayList<NameValuePair>(2);
postData.add(new BasicNameValuePair("firstindex", Integer.toString(mFirstIndex)));
postData.add(new BasicNameValuePair("itemscount", Integer.toString(ITEM_COUNT)));
JSONObject json = RestJsonClient.getJSONObject(URL_ITEMINFOLIST, postData);
return json;
}
protected void onPostExecute(JSONObject json) {
try {
// Get data from json object and set to list adapter
JSONArray jsonArray = json.getJSONArray("data");
for(int i=0; i<jsonArray.length(); i++)
mItems.put(jsonArray.get(i));
mItemAdapter.notifyDataSetChanged();
ListView listView = (ListView)findViewById(android.R.id.list);
View footerView = ((LayoutInflater)ItemList.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
listView.addFooterView(footerView);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
progressDialog = MyProgressDialog.show(ItemList.this, null, null);
mFirstIndex = mFirstIndex + ITEM_COUNT;
new GetItemInfoList().execute();
}
});
} catch (JSONException e) {
}
}
}
}
Adapter
public class ItemAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private JSONArray mItems;
private ImageLoader mImageLoader;
private int mCategory;
public ItemAdapter(Context context, int category, JSONArray items) {
mContext = context;
mInflater = LayoutInflater.from(context);
mItems = items;
mCategory = category;
this.mImageLoader = new ImageLoader(context, true);
}
public int getCount() {
return mItems.length();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_row, null);
holder = new ViewHolder();
holder.listitem_pic = (ImageView) convertView.findViewById(R.id.listitem_pic);
holder.listitem_desc = (TextView) convertView.findViewById(R.id.listitem_desc);
holder.listitem_title = (TextView) convertView.findViewById(R.id.listitem_title);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
JSONObject item = mItems.getJSONObject(position);
String listitem_pic = item.getString("picture");
holder.listitem_pic.setTag(listitem_pic);
mImageLoader.DisplayImage(listitem_pic, (Activity)mContext, holder.listitem_pic);
holder.listitem_title.setText(item.getString("title"));
holder.listitem_desc.setText(item.getString("desc"));
}
catch (JSONException e) {
}
return convertView;
}
static class ViewHolder {
TextView listitem_title;
ImageView listitem_pic;
TextView listitem_desc;
}
}
It depends on your implementation of ItemAdapter, I'd recommend holding a reference to ItemAdapter, then updating the data set behind it and then calling notifyDataSetChanged() on it. something like:
ItemAdapter ia = new ItemAdapter(ItemList.this, mType, mItems);
setListAdapter(ia);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mItems.append(newItems);
ia.notifyDataSetChanged();
}
});
It is tricky without knowing what data you are using or whether you have the entire data set available at the start.

Categories

Resources