ExpandableListView with multiple choice save selected item into an array - android

I have an array that is filled with API data, and I have an expandablelistview to show the items of that array, now what I'm trying to do is when the user clicks on an item it saves th ID of that item into an array, so if the user select 2 items I want 2 Ids in my array, what is happening now is this: no matter if I select only one of the items it gets all of them and save it inside my array.
public class MainActivity extends Fragment {
private ExpandListAdapter ExpAdapter;
private ExpandableListView ExpandList;
private Button notificar;
private Context context;
MainActivity mContext;
private Button footer;
private double RaioEscola;
private CircleOptions mCircle;
GPSTracker tracker;
private Location location;
private Integer IdEscola;
public MainActivity() {
}
public MainActivity(Context context) {
this.context = context;
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.expand, container, false);
ExpandList = (ExpandableListView) rootView.findViewById(R.id.exp_list);
notificar = (Button) rootView.findViewById(R.id.btnGetMoreResults);
new asyncTask(MainActivity.this).execute();
return rootView;
}
private class asyncTask extends AsyncTask<String, Void, Void> {
private ProgressDialog pd;
public asyncTask(MainActivity context) {
mContext = context;
pd = new ProgressDialog(getActivity());
pd.setTitle("Por Favor Espere ...");
pd.setMessage("Enviando ...");
if (!pd.isShowing()) {
pd.show();
}
}
#Override
protected Void doInBackground(final String... params) {
try {
String[] resposta = new WebService().get("filhos");
if (resposta[0].equals("200")) {
JSONObject mJSONObject = new JSONObject(resposta[1]);
JSONArray dados = mJSONObject.getJSONArray("data");
/* cria o array que vai receber os dados da api */
final ArrayList<Escolas> mArrayList = new ArrayList<Escolas>();
/* percorre o array, adicionando cada linha encontrada em um ArrayList */
for (int i = 0; i < dados.length(); i++) {
JSONObject item = dados.getJSONObject(i);
Escolas mEscolas = new Escolas();
mEscolas.setId_escola(item.optInt("id_escola"));
mEscolas.setCnpj(item.getString("cnpj"));
mEscolas.setRazao_social(item.getString("razao_social"));
mEscolas.setNome_fantasia(item.getString("nome_fantasia"));
mEscolas.setDistancia(Float.valueOf(item.getString("distancia")));
mEscolas.setLogradouro(item.optString("logradouro"));
mEscolas.setNumero(item.optString("numero"));
mEscolas.setBairro(item.getString("bairro"));
mEscolas.setComplemento(item.getString("complemento"));
mEscolas.setCep(item.getString("cep"));
mEscolas.setCidade(item.getString("cidade"));
mEscolas.setEstado(item.getString("estado"));
mEscolas.setLatitude(Float.parseFloat(item.getString("latitude")));
mEscolas.setLongitude(Float.parseFloat(item.getString("longitude")));
RaioEscola = Double.parseDouble(String.valueOf(mEscolas.getDistancia()));
IdEscola = mEscolas.getId_escola();
JSONObject alunos = item.optJSONObject("alunos");
JSONArray data = alunos.getJSONArray("data");
if (data != null) {
ArrayList<Filhos> arrayalunos = new ArrayList<Filhos>();
for (int a = 0; a < data.length(); a++) {
Filhos mFilhos = new Filhos();
JSONObject clientes = data.getJSONObject(a);
mFilhos.setId_aluno(clientes.optInt("id_aluno"));
mFilhos.setNome(clientes.optString("nome"));
mFilhos.setSobrenome(clientes.optString("sobrenome"));
mFilhos.setFoto(clientes.optString("foto"));
mFilhos.setModalidade_de_ensino(clientes.optString("modalidade_de_ensino"));
mFilhos.setObservacoes(clientes.optString("observacoes"));
arrayalunos.add(mFilhos);
}
mEscolas.setalunos(arrayalunos);
}
/* popula o array de viagens */
mArrayList.add(mEscolas);
ExpAdapter = new ExpandListAdapter(getActivity(), mArrayList);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
ExpandList.setAdapter(ExpAdapter);
ExpAdapter.notifyDataSetChanged();
ExpAdapter.setChoiceMode(ExpandListAdapter.CHOICE_MODE_MULTIPLE);
ExpandList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(final ExpandableListView parent, View v, final int groupPosition, final int childPosition, final long id) {
ExpAdapter.setClicked(groupPosition, childPosition);
final int index = parent.getFlatListPosition(ExpandableListView.getPackedPositionForChild(groupPosition, childPosition));
parent.setItemChecked(index, true);
parent.setSelectedChild(groupPosition, childPosition, true);
parent.getChildAt(index);
notificar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
class update extends TimerTask {
public void run() {
try {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
final float latitude = mArrayList.get(groupPosition).getLatitude();
final float longitude = mArrayList.get(groupPosition).getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
drawMarkerWithCircle(latLng);
GPSTracker gps = new GPSTracker(getActivity());
double latitudegps = gps.getLatitude();
double longitudegps = gps.getLongitude();
float[] distance = new float[2];
Location.distanceBetween(mCircle.getCenter().latitude, mCircle.getCenter().longitude, latitudegps, longitudegps, distance);
if (distance[0] > mCircle.getRadius()) {
Toast.makeText(getActivity(), "Outside", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getActivity(), "Inside", Toast.LENGTH_LONG).show();
AlertRest mAlertRest = new AlertRest();
try {
List<Integer> myIdList = new ArrayList<Integer>();
for (int i = 0; i < mArrayList.get(groupPosition).getalunos().size(); i++) {
Integer Idalunos = mArrayList.get(groupPosition).getalunos().get(i).getId_aluno();
myIdList.add(Idalunos);
}
mAlertRest.getNotificacao(1, mArrayList.get(groupPosition).getId_escola(), String.valueOf(myIdList), latitudegps, longitudegps);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Timer timer = new Timer();
timer.schedule(new update(), 0, 15000);
}
private void drawMarkerWithCircle(LatLng position) {
mCircle = new CircleOptions().center(position).radius(RaioEscola);
}
});
return false;
}
});
}
});
}
/* retorna um array de objetos */
}
else {
throw new Exception("[" + resposta[0] + "] ERRO: " + resposta[1]);
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void cursor) {
if (pd.isShowing()) {
pd.dismiss();
}
}
}
}
AlertRest:
public class AlertRest extends WebService {
private String recurso = "notificacoes";
private String[] resposta;
private AlertModelo mAlertModelo;
public AlertModelo getNotificacao(Integer id_usuario, String token, Integer id_escola, String ids_aluno, Double latitude, Double longitude) throws Exception {
/* dispara a requisição para a API retornar os dados do "recurso" necessário */
resposta = new WebService().postToken(recurso, token, "{\"id_usuario\":" + id_usuario + "," + "\"id_escola\":" + id_escola + "," + "\"ids_aluno\":\"" + ids_aluno + "\"," + "\"latitude\":" + latitude + "," + "\"longitude\":" + longitude + "}");
JSONObject mJSONObject = new JSONObject(resposta[1]);
if (resposta[1].equals("201")) {
mAlertModelo = new AlertModelo();
mAlertModelo.setId_usuario(mJSONObject.getInt(String.valueOf(id_usuario)));
mAlertModelo.setId_escola(mJSONObject.getInt(String.valueOf(id_escola)));
mAlertModelo.setIds_aluno(mJSONObject.getInt(String.valueOf(ids_aluno)));
mAlertModelo.setLatitude(mJSONObject.getDouble(String.valueOf(latitude)));
mAlertModelo.setLongitude(mJSONObject.getDouble(String.valueOf(longitude)));
}
return mAlertModelo;
}
}

The code is difficult to follow due to few nested loops and running tasks.
Anyway, I suspect the code below is causing your app to save all (unselected) items in the list:
for (int i = 0; i < mArrayList.get(groupPosition).getalunos().size(); i++) {
Integer Idalunos = mArrayList.get(groupPosition).getalunos().get(i).getId_aluno();
myIdList.add(Idalunos);
}
Note: Iterating through the entire list is a suspect. It should pick a certain item or items in the list.
So...another set of relevant codes can help us determine the code fix. I am not certain if there is a bug here also.
parent.setItemChecked(index, true);
parent.setSelectedChild(groupPosition, childPosition, true);
parent.getChildAt(index);
Note: These codes may be fine. The key code, I think, is the index. I am not too familiar with ExpandableListView.
Finally, suggested code fix:
Integer Idalunos = mArrayList.get(groupPosition).getalunos().get(index).getId_aluno();
...
myIdList.add(Idalunos);
Notice the variable index is used to get the correct item, Idalunos.

You are using mArrayList variable for initializing adapter and for filling myIdList at the same time. Of course myIdList would contain full list of your adapter.
UPDATE
It would be better to define myIdList as field of your MainActivity class and initialize it in onCreateView method.
On click not just add the value - you should check if this value is allready in list:
if(myIdList.contains(Idalunos)) {
myIdList.remove(Idalunos);
} else {
myIdList.add(Idalunos);
}

Related

Return button to previous activity with BaseAdapter

I currently have two activities doing HTTP requests.
The first activity contains a CustomList class extends BaseAdapter.
On the second, there is a previous button allowing me to return to the first activity.
Returning to the first activity, I would like to be able to recover the state in which I left it. That is to say to be able to find the information which also come from an HTTP request. I would like to find the data "infos_user" which is in the first activity and all the data in the BaseAdapter.
My architecture is as follows: Activity 0 (HTTP request) -> Activity 1 (with BaseAdapter and HTTP request) -> Activity 2 (HTTP request)
I put all the code because I really don't know how can I do this :/
First activity:
public class GetChildrenList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<Child> childrenImeList = new ArrayList<Child>();
private Button btn_previous;
private ListView itemsListView;
private TextView tv_signin_success;
int id = 0;
String infos_user;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_children_list);
infos_user = (String) getIntent().getSerializableExtra("infos_user");
Intent intent = new Intent(GetChildrenList.this , GetLearningGoalsList.class);
intent.putExtra("username", infos_user);
btn_previous = (Button) findViewById(R.id.btn_previous);
btn_previous.setOnClickListener(this);
tv_signin_success = (TextView) findViewById(R.id.tv_signin_success);
tv_signin_success.setText("Bonjour " + infos_user + "!");
itemsListView = (ListView)findViewById(R.id.list_view_children);
new GetChildrenAsync().execute();
}
class GetChildrenAsync extends AsyncTask<String, Void, ArrayList<Child>> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(GetChildrenList.this, "Please wait", "Loading...");
}
#Override
protected ArrayList<Child> doInBackground(String... params) {
int age = 0;
email = (String) getIntent().getSerializableExtra("email");
password = (String) getIntent().getSerializableExtra("password");
String first_name = null;
String last_name = null;
try {
SendRequest sr = new SendRequest();
String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/childrenime/list", "GET", true, email, password);
String jsonResult = "{ \"children\":" + result + "}";
Log.d("result1", jsonResult);
//Manage JSON result
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray childrenArray = jsonObject.getJSONArray("children");
for (int i = 0; i < childrenArray.length(); ++i) {
JSONObject child = childrenArray.getJSONObject(i);
id = child.getInt("id");
first_name = child.getString("first_name");
last_name = child.getString("last_name");
age = child.getInt("age");
String name = first_name + " " + last_name;
childrenImeList.add(new Child(id,name,age));
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenImeList;
}
#Override
protected void onPostExecute(final ArrayList<Child> childrenListInformation) {
loadingDialog.dismiss();
if(childrenListInformation.size() > 0) {
CustomListChildrenAdapter adapter = new CustomListChildrenAdapter(GetChildrenList.this, childrenListInformation);
itemsListView.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des enfants", Toast.LENGTH_LONG).show();
}
}
}
}
BaseAdapter:
public class CustomListChildrenAdapter extends BaseAdapter implements View.OnClickListener {
private Context context;
private ArrayList<Child> children;
private Button btnChoose;
private TextView childrenName;
private TextView childrenAge;
public CustomListChildrenAdapter(Context context, ArrayList<Child> children) {
this.context = context;
this.children = children;
}
#Override
public int getCount() {
return children.size(); //returns total item in the list
}
#Override
public Object getItem(int position) {
return children.get(position); //returns the item at the specified position
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_list_view_children,null);
childrenName = (TextView)view.findViewById(R.id.tv_childrenName);
childrenAge = (TextView) view.findViewById(R.id.tv_childrenAge);
btnChoose = (Button) view.findViewById(R.id.btn_choose);
btnChoose.setOnClickListener(this);
} else {
view = convertView;
}
btnChoose.setTag(position);
Child currentItem = (Child) getItem(position);
childrenName.setText(currentItem.getChildName());
childrenAge.setText(currentItem.getChildAge() + "");
return view;
}
#Override
public void onClick(View v) {
Integer position = (Integer) v.getTag();
Child item = (Child) getItem(position);
String email = (String) ((Activity) context).getIntent().getSerializableExtra("email");
String password = (String) ((Activity) context).getIntent().getSerializableExtra("password");
Intent intent = new Intent(context, GetLearningGoalsList.class);
intent.putExtra("idChild",item.getId());
intent.putExtra("email",email);
intent.putExtra("password",password);
context.startActivity(intent);
}
}
Second Activity:
public class GetLearningGoalsList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<LearningGoal> childrenLearningList = new ArrayList<LearningGoal>();
private Button btn_previous;
private ListView itemsListView;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_learning_goals_list);
btn_previous = (Button) findViewById(R.id.btn_previous);
btn_previous.setOnClickListener(this);
itemsListView = (ListView)findViewById(R.id.list_view_learning_goals);
new GetLearningGoalsAsync().execute();
}
#Override
public void onClick(View v) {
Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
return;
}
class GetLearningGoalsAsync extends AsyncTask<String, Void, ArrayList<LearningGoal>> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(GetLearningGoalsList.this, "Please wait", "Loading...");
}
#Override
protected ArrayList<LearningGoal> doInBackground(String... params) {
int id = 0;
email = (String) getIntent().getSerializableExtra("email");
password = (String) getIntent().getSerializableExtra("password");
int idChild = (int) getIntent().getSerializableExtra("idChild");
String name = null;
String start_date = null;
String end_date = null;
try {
List<BasicNameValuePair> parameters = new LinkedList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("idchild", Integer.toString(idChild)));
SendRequest sr = new SendRequest();
String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/learningchild/list"+ "?"+ URLEncodedUtils.format(parameters, "utf-8"), "POST", true, email, password);
String jsonResult = "{ \"learningGoals\":" + result + "}";
Log.d("result1", jsonResult);
//Manage JSON result
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray learningGoalsArray = jsonObject.getJSONArray("learningGoals");
for (int i = 0; i < learningGoalsArray.length(); ++i) {
JSONObject learningGoal = learningGoalsArray.getJSONObject(i);
id = learningGoal.getInt("id");
name = learningGoal.getString("name");
start_date = learningGoal.getString("start_date");
end_date = learningGoal.getString("end_date");
childrenLearningList.add(new LearningGoal(id,name,start_date,end_date));
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenLearningList;
}
#Override
protected void onPostExecute(final ArrayList<LearningGoal> learningListInformation) {
loadingDialog.dismiss();
if(learningListInformation.size() > 0) {
CustomListLearningGoalAdapter adapter = new CustomListLearningGoalAdapter(GetLearningGoalsList.this, learningListInformation);
itemsListView.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des scénarios de cet enfant", Toast.LENGTH_LONG).show();
}
}
}
}
Thanks for your help.
if you want to maintain GetChildrenList state as it is then just call finish() rather than new intent on previous button click as follow
replace in GetLearningGoalsList
#Override
public void onClick(View v) {
Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
return;
}
with
#Override
public void onClick(View v) {
finish();
}

Android - Add Item to RecyclerView one by one?

I need to add my Items one by one to my RcyclerView for example add first item to recyclerView and show then add another item....
I have a volley that connect to a service then get me some data, in this volley I call a method :
private void makeJsonArryReq(String uri) {
userPointList = new ArrayList<>();
orginal = new ArrayList<>();
final JsonArrayRequest req = new JsonArrayRequest(uri,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
orginal = MarketingPoints_JSONParser.FeedOriginal(response.toString(), mUser_Code, ReportActivity.this);
userPointList = MarketingPoints_JSONParser.parseFeed(response.toString(), mUser_Code, ReportActivity.this);
FillList();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Custom Log Error", "Error: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(req, tag_json_arry);
}
when I call this method FillList(); it fill and show first item on RecyclerView,How can I listen to adapter for finalized and call FillList(); again for next item .
My FillList():
public void FillList() {
Geocoder geocoder = new Geocoder(activity, Locale.getDefault());
List<Address> addresses;
StepModel stp = null;
List<StepModel> Step = new ArrayList<>();
if (check < userPointList.size()) {
try {
addresses = geocoder.getFromLocation(userPointList.get(check).getLat(), userPointList.get(check).getLng(), 1);
stp = new StepModel();
stp.setsCity(addresses.get(0).getAdminArea());
stp.setsStreet(addresses.get(0).getThoroughfare());
stp.setSlat(userPointList.get(check).getLat());
stp.setSlng(userPointList.get(check).getLng());
stp.setSdate(userPointList.get(check).getDate());
stp.setStime(userPointList.get(check).getTime());
stp.setsCounts(userPointList.get(check).getCounts());
stp.setSprofilePhoto(userPointList.get(check).getProfilePhoto());
stp.setsUserCode(userPointList.get(check).getUserCode());
Step.add(stp);
} catch (IOException e) {
e.printStackTrace();
}
pointAdapter = new PointsList_Adapter(Step, ReportActivity.this,this, city, street);
Points_Recycler.setAdapter(pointAdapter);
pointAdapter.notifyDataSetChanged();
check++;
}else {
return;
}
}
Explain :
I connect to a service then I get a json then I convert it and store in a List.In my json I have two specific data (Lat and lng) that I should get name country and name street(For example 100 lat lng) then show on recyclerView but it get long time because I should fill recyclerView on by one.
My adapter :
public class PointsList_Adapter extends RecyclerView.Adapter<PointsList_Adapter.ViewHolder> {
int count = 0;
private List<StepModel> mpList;
public static Activity activity;
public static boolean flagItem = true;
public static boolean flagToast = true;
private mstep Mstep;
public PointsList_Adapter(List<StepModel> userCodeList, Activity activity) {
this.mpList = userCodeList;
this.activity = activity;
}
#Override
public PointsList_Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.listpoints_cardview, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(PointsList_Adapter.ViewHolder viewHolder, final int position) {
String dateValue = mpList.get(position).getDate();
final String countValue = String.valueOf(mpList.get(position).getCounts());
final Double lat = mpList.get(position).getLat();
final Double lng = mpList.get(position).getLng();
final String userCode = mpList.get(position).getUserCode();
final String time = mpList.get(position).getTime();
final int counts = mpList.get(position).getCounts();
final String city = mpList.get(position).getCity();
final String street = mpList.get(position).getStreet();
viewHolder.txtDate.setText(dateValue);
viewHolder.txtPoints.setText(lat + " , " + lng);
viewHolder.txtTime.setText(time);
viewHolder.txtAddress.setText(city + " , " + street);
viewHolder.txtCount.setText(countValue);
}
#Override
public int getItemCount() {
return mpList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtDate, txtPoints, txtTime, txtAddress, txtCount;
public LinearLayout lLstPoints;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
txtDate = (TextView) itemLayoutView.findViewById(R.id.txtDate);
txtPoints = (TextView) itemLayoutView.findViewById(R.id.txtPoints);
txtTime = (TextView) itemLayoutView.findViewById(R.id.txtTime);
txtAddress = (TextView) itemLayoutView.findViewById(R.id.txtAddress);
txtCount = (TextView) itemLayoutView.findViewById(R.id.txtCount);
lLstPoints = (LinearLayout) itemLayoutView.findViewById(R.id.lLstPoints);
}
}
}
Please add below method in your adapter:
public reloadList(ArrayList<String> mpList) {
this.mpList.addAll(mpList);
}
When you want to update list or want to add one more item in your listview, use below code:
public void FillList() {
Geocoder geocoder = new Geocoder(activity, Locale.getDefault());
List<Address> addresses;
StepModel stp = null;
List<StepModel> Step = new ArrayList<>();
if (check < userPointList.size()) {
try {
addresses = geocoder.getFromLocation(userPointList.get(check).getLat(), userPointList.get(check).getLng(), 1);
stp = new StepModel();
stp.setsCity(addresses.get(0).getAdminArea());
stp.setsStreet(addresses.get(0).getThoroughfare());
stp.setSlat(userPointList.get(check).getLat());
stp.setSlng(userPointList.get(check).getLng());
stp.setSdate(userPointList.get(check).getDate());
stp.setStime(userPointList.get(check).getTime());
stp.setsCounts(userPointList.get(check).getCounts());
stp.setSprofilePhoto(userPointList.get(check).getProfilePhoto());
stp.setsUserCode(userPointList.get(check).getUserCode());
Step.add(stp);
} catch (IOException e) {
e.printStackTrace();
}
// Just update your list and call notifyDataSetChanged()
pointAdapter .reloadList(Step);
pointAdapter .notifyDataSetChanged();
check++;
}else {
return;
}
}
Initialize your adapter as below:
ArrayList<StepModel> userCodeList = new ArrayList<StepModel>();
pointAdapter = new PointsList_Adapter(userCodeList , activity) ;
Thank You.
After retrieving all data from server at once, inside Filllist() method you should use for, while or do..while loops to iterate your code.You have used if conditional loop that will run only once.
Else, you can create a method inside adapter to add item to your list and then call notifydatasetchanged() method there.
public void add(Object obj){
mArraylist.add(obj);
notifyDataSetChanged();
}

Set notifyDataSetChanged() on Recyclerview adapter

I'm implementing an endless data loading for a RecyclerView. When software detects that last item is going to be shown, it downloads new items and call to the loadMoreData() function but new dataset is not showing.
When I called notifyDataSetChanged() so nothing to be happened.
I have only one solution that is refresh the view is to set again the adapter but problem is that the recyclerview returns to the first position then again recyclerview scrolled up from the first position to last position.
RecyclerViewActivity.java
RecyclerView rv;
DatabaseHelpr databaseHelpr;
RVAdapter adapter;
LocationFinder locationfinder;
Location currentLocation;
ArrayList<ServiceModel> childList, list;
private int MainService_ID, city_id;
String url2;
ActionBar actionBar;
JSONArray items = null;
Utility utility;
Double lat, longi;
LinearLayoutManager llm;
int counter=0;
ProgressBar progressBar;
private static final String TAG_ITEMS = "items";
private static final String TAG_LOCALITY = "Locality";
private static final String TAG_BUSINESS_ID = "Business_Id";
private static final String TAG_LONGITUDE = "Longitude";
private static final String TAG_BUSINESS_NAME = "Business_Name";
private static final String TAG_LATITUDE = "Latitude";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview_activity);
list = new ArrayList<>();
utility = new Utility(this);
llm = new LinearLayoutManager(this);
Bundle bundle=getIntent().getExtras();
MainService_ID=bundle.getInt("service_id");
String mainService_Name = bundle.getString("service_name");
city_id = bundle.getInt("city_id");
lat= bundle.getDouble("lat");
longi=bundle.getDouble("longi");
rv=(RecyclerView)findViewById(R.id.rv);
rv.setLayoutManager(llm);
actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(mainService_Name);
//Here city_id = 8, lat = 18.552954, longi = 73.897200, counter=0, MainService_ID = 5
String url="https://servicedata2-dot-indiacomapi.appspot.com/_ah/api/servicedata/v1/ServiceData?city_id=";
url2 =url+city_id+"&lat="+lat+"&lng="+longi+"&roll="+counter+"&service_id="+MainService_ID;
AsyncHttpClient client = new AsyncHttpClient();
progressBar=(ProgressBar) findViewById(R.id.progressBar1);
progressBar.setVisibility(View.VISIBLE);
client.get(url2, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
String s = new String(response);
try {
JSONObject jsonObj = new JSONObject(s);
// Getting JSON Array node
items = jsonObj.getJSONArray(TAG_ITEMS);
// looping through All Contacts
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String locality = c.getString(TAG_LOCALITY);
String business_Id = c.getString(TAG_BUSINESS_ID);
String longitude = c.getString(TAG_LONGITUDE);
String latitude = c.getString(TAG_LATITUDE);
String business_Name = c.getString(TAG_BUSINESS_NAME);
locationfinder = new LocationFinder(RecyclerViewActivity.this);
// check if GPS enabled
if (locationfinder.canGetLocation()) {
double lat = locationfinder.getLatitude();
double longi = locationfinder.getLongitude();
currentLocation = new Location("");
currentLocation.setLatitude(lat);
currentLocation.setLongitude(longi);
} else {
locationfinder.showSettingsAlert();
}
Location savedLocation = new Location("databaseLocation");
savedLocation.setLatitude(Double.parseDouble(latitude));
savedLocation.setLongitude(Double.parseDouble(longitude));
Double difference = currentLocation.distanceTo(savedLocation) * (0.001);
difference = Double.parseDouble(new DecimalFormat("##.##").format(difference));
String newDifference = String.valueOf(difference) + " km";
ServiceModel serviceModel = new ServiceModel(business_Id, business_Name, newDifference, locality);
list.add(serviceModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
adapter = new RVAdapter(RecyclerViewActivity.this, list);
rv.setAdapter(adapter);
rv.addOnScrollListener(new EndlessRecyclerOnScrollListener(llm) {
#Override
public void onLoadMore(int current_page) {
// counter= counter+1;
loadMoreData();
}
});
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
//Toast.makeText(getApplicationContext(),""+statusCode,Toast.LENGTH_LONG).show();
}
});
}
private void loadMoreData() {
counter= counter+1;
//Here city_id = 8, lat = 18.552954, longi = 73.897200, counter=1, MainService_ID = 5
String url="https://servicedata2-dot-indiacomapi.appspot.com/_ah/api/servicedata/v1/ServiceData?city_id=";
url2 =url+city_id+"&lat="+lat+"&lng="+longi+"&roll="+counter+"&service_id="+MainService_ID;
AsyncHttpClient client = new AsyncHttpClient();
progressBar=(ProgressBar) findViewById(R.id.progressBar1);
progressBar.setVisibility(View.VISIBLE);
client.get(url2, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
String s = new String(response);
try {
JSONObject jsonObj = new JSONObject(s);
// Getting JSON Array node
items = jsonObj.getJSONArray(TAG_ITEMS);
// looping through All Contacts
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String locality = c.getString(TAG_LOCALITY);
String business_Id = c.getString(TAG_BUSINESS_ID);
String longitude = c.getString(TAG_LONGITUDE);
String latitude = c.getString(TAG_LATITUDE);
String business_Name = c.getString(TAG_BUSINESS_NAME);
locationfinder = new LocationFinder(RecyclerViewActivity.this);
// check if GPS enabled
if (locationfinder.canGetLocation()) {
double lat = locationfinder.getLatitude();
double longi = locationfinder.getLongitude();
currentLocation = new Location("");
currentLocation.setLatitude(lat);
currentLocation.setLongitude(longi);
} else {
locationfinder.showSettingsAlert();
}
Location savedLocation = new Location("databaseLocation");
savedLocation.setLatitude(Double.parseDouble(latitude));
savedLocation.setLongitude(Double.parseDouble(longitude));
Double difference = currentLocation.distanceTo(savedLocation) * (0.001);
difference = Double.parseDouble(new DecimalFormat("##.##").format(difference));
String newDifference = String.valueOf(difference) + " km";
ServiceModel serviceModel = new ServiceModel(business_Id, business_Name, newDifference, locality);
list.add(serviceModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
//adapter = new RVAdapter(RecyclerViewActivity.this, list);
//rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
}
});
Toast.makeText(this, "Net is present", Toast.LENGTH_SHORT).show();
}
}
RVAdapter.java
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder>{
private final LayoutInflater mInflater;
List<ServiceModel> persons ;
private Context mContext;
public RVAdapter(Context context,List<ServiceModel> persons){
this.mInflater = LayoutInflater.from(context);
this.persons = new ArrayList<>(persons);
this.mContext = context;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false);
PersonViewHolder pvh = new PersonViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
ServiceModel person = persons.get(i);
personViewHolder.businessName.setOnClickListener(clickListener);
personViewHolder.image_url.setOnClickListener(clickListenerImage);
personViewHolder.businessName.setTag(personViewHolder);
personViewHolder.difference.setTag(personViewHolder);
personViewHolder.business_id.setTag(personViewHolder);
personViewHolder.image_url.setTag(personViewHolder);
personViewHolder.locality.setTag(personViewHolder);
personViewHolder.businessName.setText(Html.fromHtml(person.getBusinessname()));
String firstLetter = String.valueOf(person.getBusinessname().charAt(0));
ColorGenerators generator = ColorGenerators.MATERIAL; // or use DEFAULT
int color = generator.getColor(person.getBusinessname());
TextDrawable drawable = TextDrawable.builder().buildRound(firstLetter, color); // radius in px
personViewHolder.image_url.setImageDrawable(drawable);
personViewHolder.difference.setText(Html.fromHtml(person.getNewDiffer()));
personViewHolder.locality.setText(Html.fromHtml(person.getLocality()));
personViewHolder.bind(person);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
PersonViewHolder holder = (PersonViewHolder) view.getTag();
int position = holder.getPosition();
ServiceModel person = persons.get(position);
String businessids = person.getBusinessid();
Intent intent = new Intent(mContext, BusinessInfoActivity.class);
intent.putExtra("businessids", businessids);
mContext.startActivity(intent);
}
};
View.OnClickListener clickListenerImage = new View.OnClickListener() {
#Override
public void onClick(View view) {
PersonViewHolder holder = (PersonViewHolder) view.getTag();
int position = holder.getPosition();
ServiceModel person = persons.get(position);
String businessids = person.getBusinessid();
Intent intent = new Intent(mContext, BusinessInfoActivity.class);
intent.putExtra("businessids", businessids);
mContext.startActivity(intent);
}
};
#Override
public int getItemCount() {
return persons.size();
}
public void animateTo(List<ServiceModel> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
private void applyAndAnimateRemovals(List<ServiceModel> newModels) {
for (int i = persons.size() - 1; i >= 0; i--) {
final ServiceModel model = persons.get(i);
if (!newModels.contains(model)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(List<ServiceModel> newModels) {
for (int i = 0, count = newModels.size(); i < count; i++) {
final ServiceModel model = newModels.get(i);
if (!persons.contains(model)) {
addItem(i, model);
}
}
}
private void applyAndAnimateMovedItems(List<ServiceModel> newModels) {
for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
final ServiceModel model = newModels.get(toPosition);
final int fromPosition = persons.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
public ServiceModel removeItem(int position) {
final ServiceModel model = persons.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, ServiceModel model) {
persons.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final ServiceModel model = persons.remove(fromPosition);
persons.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
public static class PersonViewHolder extends RecyclerView.ViewHolder {
protected CardView cv;
protected TextView businessName, difference, business_id, locality;
protected ImageView image_url;
public PersonViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
businessName = (TextView)itemView.findViewById(R.id.business_name);
difference = (TextView)itemView.findViewById(R.id.txtDifferenece);
business_id = (TextView)itemView.findViewById(R.id.business_id);
image_url = (ImageView)itemView.findViewById(R.id.thumbnail);
locality= (TextView)itemView.findViewById(R.id.txtLocality);
}
public void bind(ServiceModel model) {
businessName.setText(model.getBusinessname());
}
}
}
Please help me, How to set notifyDataSetChanged() to the adapter. it is not working in my code. I already checked all answers which is posted on the stackoverflow.
you are setting the new list to the RecyclerView Adapter , set the list in the Adapter:
make a method setItems(list) in adapter and call it before notifyDataSetChanged() and in adapter do
this.persons = new ArrayList<>(persons);
in setItems
add this method in adapter:
public void setItems(List<ServiceModel> persons) {
this.persons = persons;
}
and call it before notifyDataSetChanged() like this:
adapter.setItems(list);
adapter.notifyDataSetChanged();
Issue is in these lines..
adapter = new RVAdapter(RecyclerViewActivity.this, list);
rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
You are initialising your adapter every time. No need to reinitialize it.
Just update your arraylist and invoking to adapter.notifyDataSetChanged(); will make it work.
Like #Beena mentioned, you are creating and setting new adapter ever time, in your success response.
One approach would be to create an adapter and set it to the recycler view only for the first time, and then onSuceess() of your api callback, call a method of your adapter.
In, them adapter method, just add that new data in your main arraylist and do notifyItemInserted() instead of notifyDataSetChanged, in this way you will also see the default adding animation of recyclerView.
Every time you fill your list call the method below:
if (adapter != null) // it works second time and later
adapter.notifyDataSetChanged();
else { // it works first time
adapter = new AdapterClass(context,list);
listView.setAdapter(adapter);
}
I solved this with added method in RVAdapter that call notifyDataSetChanged().
Simply in RVAdapter:
public void refreshList(){
notifyDataSetChanged();
}
and call this method in MainActivity when need:
rVAdapter.refreshList();

listview does not updates

I am expirience wierd situation because my list view updates only once.
The idia is following, i want to download posts from web, which are located on page 3 and page 5 and show both of them on listview. However, List view shows posts only from page 3. MEanwhile, log shows that all poast are downloded and stored in addList.
So the problem - objects from second itteration are not shown in listview. Help me please to fix this issue.
public class MyAddActivateActivity extends ErrorActivity implements
AddActivateInterface {
// All static variables
// XML node keys
View footer;
public static final String KEY_ID = "not_id";
public static final String KEY_TITLE = "not_title";
Context context;
public static final String KEY_PHOTO = "not_photo";
public final static String KEY_PRICE = "not_price";
public final static String KEY_DATE = "not_date";
public final static String KEY_DATE_TILL = "not_date_till";
private int not_source = 3;
JSONObject test = null;
ListView list;
MyAddActivateAdapter adapter;
ArrayList<HashMap<String, String>> addList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.aadd_my_add_list_to_activate);
footer = getLayoutInflater().inflate(R.layout.loading_view, null);
addList = new ArrayList<HashMap<String, String>>();
ImageView back_button = (ImageView) findViewById(R.id.imageView3);
back_button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
ChooserActivity.class);
startActivity(i);
finish();
}
});
Intent intent = this.getIntent();
// if (intent != null) {
// not_source = intent.getExtras().getInt("not_source");
// }
GAdds g = new GAdds();
g.execute(1, not_source);
list = (ListView) findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter = new MyAddActivateAdapter(this, addList);
list.addFooterView(footer);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String add_id = ((TextView) view
.findViewById(R.id.tv_my_add_id)).getText().toString();
add_id = add_id.substring(4);
Log.d("ADD_ID", add_id);
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(),
AddToCheckActivity.class);
// sending data to new activity
UILApplication.advert.setId(add_id);
startActivity(i);
finish();
}
});
}
private void emptyAlertSender() {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Ничего не найдено");
alertDialog.setMessage("У вас нет неактивных объявлений.");
alertDialog.setButton("на главную",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(),
ChooserActivity.class);
startActivity(intent);
finish();
}
});
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.show();
}
class GAdds extends AsyncTask<Integer, Void, JSONObject> {
#Override
protected JSONObject doInBackground(Integer... params) {
// addList.clear();
Log.d("backgraund", "backgraund");
UserFunctions u = new UserFunctions();
return u.getAdds(params[0] + "", params[1] + "");
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
Log.d("postexecute", "postexecute");
footer.setVisibility(View.GONE);
JSONArray tArr = null;
if (result != null) {
try {
tArr = result.getJSONArray("notices");
for (int i = 0; i < tArr.length(); i++) {
JSONObject a = null;
HashMap<String, String> map = new HashMap<String, String>();
a = (JSONObject) tArr.get(i);
if (a.getInt("not_status") == 0) {
int premium = a.getInt("not_premium");
int up = a.getInt("not_up");
if (premium == 1 && up == 1) {
map.put("status", R.drawable.vip + "");
} else if (premium == 1) {
map.put("status", R.drawable.prem + "");
} else if (premium != 1 && up == 1) {
map.put("status", R.drawable.up + "");
} else {
map.put("status", 0 + "");
}
map.put(KEY_ID, "ID: " + a.getString(KEY_ID));
map.put(KEY_TITLE, a.getString(KEY_TITLE));
map.put(KEY_PRICE,
"Цена: " + a.getString(KEY_PRICE) + " грн.");
map.put(KEY_PHOTO, a.getString(KEY_PHOTO));
map.put(KEY_DATE,
"Создано: " + a.getString(KEY_DATE));
map.put(KEY_DATE_TILL,
"Действительно до: "
+ a.getString(KEY_DATE_TILL));
map.put("check", "false");
Log.d("MyAddList", "map was populated");
}
if (map.size() > 0)
{
addList.add(map);
Log.d("MyAddList", "addlist was populated");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
if (UILApplication.login != 2) {
UILApplication.login = 3;
}
onCreateDialog(LOST_CONNECTION).show();
}
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
if (not_source == 3) {
not_source = 5;
GAdds task = new GAdds();
task.execute(1, 5);
}
if (not_source == 5) {
Log.d("ID", m.get(KEY_ID));
if (addList.size() == 0) {
emptyAlertSender();
}
}
}
}
#SuppressWarnings("unchecked")
public void addAct(View v) {
AddActivate aAct = new AddActivate(this);
aAct.execute(addList);
}
#Override
public void onAddActivate(JSONObject result) {
if (result != null) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
}
adapter
public class MyAddActivateAdapter extends BaseAdapter {
private List<Row> rows;
private ArrayList<HashMap<String, String>> data;
private Activity activity;
public MyAddActivateAdapter(Activity activity,
ArrayList<HashMap<String, String>> data) {
Log.d("mediaadapter", "listcreation: " + data.size());
rows = new ArrayList<Row>();// member variable
this.data = data;
this.activity = activity;
}
#Override
public int getViewTypeCount() {
return RowType.values().length;
}
#Override
public void notifyDataSetChanged() {
rows.clear();
for (HashMap<String, String> addvert : data) {
rows.add(new MyAddActivateRow((LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE), addvert));
Log.d("MyActivateAdapter", "update " + data.size());
}
}
#Override
public int getItemViewType(int position) {
return rows.get(position).getViewType();
}
public int getCount() {
return rows.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
return rows.get(position).getView(convertView);
}
}
I think the problem is you aren't calling the super class of notifyDataSetChanged(), maybe try
#Override
public void notifyDataSetChanged() {
rows.clear();
for (HashMap<String, String> addvert : data) {
rows.add(new MyAddActivateRow((LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE), addvert));
Log.d("MyActivateAdapter", "update " + data.size());
}
super.notifyDataSetChanged();
}

How to Use onresume() and onpause() for on tabclick Event

I had four tabs in my view and the tab output depend on other tab input in same view. So when I click on one tab, it generates an array list and show item in list view but when second time I click on the same tab it gives array index out of bound exception. I think it is because of previous downloaded content was in the view so how to remove/delete previous loaded content when I clicked first time on tab. I know it can be done onresume() and onpause() method but what code should be in onpause() for removing previous loaded content. For refreshing it with new content. ontabclick().
Thanks!
public class OpeningToday extends ListActivity {
String name = null;
String typename = null;
static String array_type[];
static int totalartist;
static String array_galleryname[]=null;
static String array_address[]=null;
static String array_galleryurl[]=null;
static String array_email[];
static String array_web[];
static String array_phone[];
static String array_latitude[];
static String array_longitude[];
SitesList2 sitesList;
//static String gallerynames;
//static String addresses;
private ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i("saurabh trivedi","saurabh trivedui");
super.onCreate(savedInstanceState);
setContentView(R.layout.openingtoday);
ImageView iv=(ImageView)findViewById(R.id.imv);
iv.setBackgroundResource(R.drawable.fiiatlogo);
new ProgressTask6().execute();
}
protected void onPause() {
super.onPause();
}
protected void onResume()
{
super.onResume();
new ProgressTask6().execute();
}
private class ProgressTask6 extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
private Context context;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(OpeningToday.this);
dialog.setMessage("Processing...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing())
{
dialog.dismiss();
setListAdapter(new MyAdapter(OpeningToday.this));
}
if(totalartist==0)
{
AlertDialog.Builder alt_bld = new AlertDialog.Builder(OpeningToday.this);
alt_bld.setMessage("galleries not found..")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("Title");
// Icon for AlertDialog
alert.setIcon(R.drawable.icon);
alert.show();
}
}
#Override
protected Boolean doInBackground(String... args) {
try{
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
String temp = "http://www.arteonline.mobi/iphone/output.php?visit=1";
temp = temp.replaceAll(" " ,"%20");
Log.i("temp url..",temp);
URL sourceUrl = new URL(temp);
XMLHandler myXMLHandler = new XMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
}
catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
sitesList = XMLHandler.sitesList2;
keywordresulttab.array_galleryname = new String[sitesList.getGalleryname().size()];
totalartist= sitesList.getGalleryname().size();
Log.i("opening today artist..",Integer.toString(totalartist));
for (int i = 0; i < sitesList.getGalleryname().size(); i++)
{
name = sitesList.getGalleryname().get(i);
keywordresulttab.array_galleryname[i] = name;
// Log.i("array_spinner" + i, array_galleryname[i]);
}
keywordresulttab.array_type = new String[sitesList.getType().size()];
for (int i = 0; i < sitesList.getType().size(); i++)
{
name = sitesList.getType().get(i);
keywordresulttab.array_type[i] = name;
// Log.i("array_spinner" + i, array_estado[i]);
}
keywordresulttab.array_email = new String[sitesList.getEmail().size()];
for (int i = 0; i < sitesList.getEmail().size(); i++)
{
name = sitesList.getType().get(i);
keywordresulttab.array_email[i] = name;
// Log.i("array_spinner" + i, array_estado[i]);
}
keywordresulttab.array_address = new String[sitesList.getAddress().size()];
for (int i = 0; i < sitesList.getAddress().size(); i++)
{
name = sitesList.getAddress().get(i);
keywordresulttab.array_address[i] = name;
//Log.i("array_spinner" + i, array_address[i]);
}
keywordresulttab.array_web = new String[sitesList.getWeb().size()];
for (int i = 0; i < sitesList.getWeb().size(); i++)
{
name = sitesList.getWeb().get(i);
keywordresulttab.array_web[i] = name;
}
keywordresulttab.array_lati = new String[sitesList.getLati().size()];
for (int i = 0; i < sitesList.getLati().size(); i++)
{
name = sitesList.getLati().get(i);
keywordresulttab.array_lati[i] = name;
Log.i("array_spinner" + i,keywordresulttab.array_lati[i]);
}
keywordresulttab.array_longi = new String[sitesList.getLongi().size()];
for (int i = 0; i < sitesList.getLongi().size(); i++)
{
name = sitesList.getLongi().get(i);
keywordresulttab.array_longi[i] = name;
Log.i("array_spinner" + i, keywordresulttab.array_longi[i]);
}
keywordresulttab.array_phone = new String[sitesList.getPhoneno().size()];
for (int i = 0; i < sitesList.getPhoneno().size(); i++)
{
name = sitesList.getPhoneno().get(i);
keywordresulttab.array_phone[i] = name;
}
keywordresulttab.array_imgurl = new String[sitesList.getImagegalleryurl().size()];
for (int i = 0; i < sitesList.getImagegalleryurl().size(); i++)
{
name = sitesList.getImagegalleryurl().get(i);
keywordresulttab.array_imgurl[i] = name;
}
} catch (Exception e){
Log.e("tag", "error", e);
return false;
}
return null;
}
class MyAdapter extends BaseAdapter implements OnClickListener
{
private LayoutInflater inflater;
public MyAdapter(Context ctx) {
super();
this.inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return totalartist;
}
/* Not implemented but not really needed */
#Override
public Object getItem(int position) {
return null;
}
/* Not implemented but not really needed */
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View ConvertView, ViewGroup parent)
{
View v = inflater.inflate(R.layout.listitem_layout, parent, false);
// Log.i("array galoijewdh..",keywordresulttab.array_galleryname[position]);
Log.i("saurabh trivedi","saurabh trivedui");
// Variables.a=3;
String gallerynames = keywordresulttab.array_galleryname[position];
String addresses = keywordresulttab.array_address[position];
TextView tv = (TextView) v.findViewById(R.id.barrio);
tv.setText(gallerynames);
tv = (TextView) v.findViewById(R.id.ciudad);
tv.setText(addresses);
((BaseAdapter)(getListAdapter())).notifyDataSetChanged();
return v;
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}
}
}
Make your array list empty on onResume() method and fill it by new content now.

Categories

Resources