Array overwrites instead of adding - android

Good afternoon,
I'm still a beginner in programming, currently learning Android.
I am making a screen that captures some information from a website and moves to a list view. The code below works when I use only the main page of the site, when I try to move to page 2 instead of adding to the end of the Array, it overwrites the entire Array.
I have reached the limit of my knowledge, I can kick it a silly mistake in how they are built, but I could not reach the solution alone.
I'm sorry if I have any typos, I'm using a translator.
package br.com.testejsoup.eu.testejsoup;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private ListView conteudo;
String[] aniNomes;
String[] aniLinks;
ArrayAdapter<String> adaptador;
Document doc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
conteudo = findViewById(R.id.html_conteudo);
new doit().execute();
conteudo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int posicao = position;
Intent intent = new Intent(MainActivity.this, Episodio.class);
intent.putExtra("aniLinks", aniLinks[posicao]);
//Toast.makeText(getApplicationContext(), aniLinks[posicao], Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
public class doit extends AsyncTask<Void, Void, Void>{
String URL = "http://www.URL.com/lancamentos?page=";
String nomeExp;
Elements nome;
Elements links;
int paginas = 5;
#Override
protected Void doInBackground(Void... voids) {
try {
for (int i=1; i<= paginas;i++) {
String new_URL = URL + i;
doc = Jsoup.connect(new_URL).get();
nome = doc.select("div.nome-thumb a.tt");
links = doc.select("div.nome-thumb a.tt");
aniNomes = new String[nome.size()];
aniLinks = new String[links.size()];
for(Element nomeTemp : nome){
nomeExp = nomeTemp.text();
adaptador.add(nomeExp);
}
}
for (int i = 0; i < nome.size(); i++) {
aniNomes[i] = nome.get(i).text();
}
for (int i = 0; i < links.size(); i++) {
aniLinks[i] = links.get(i).attr("abs:HREF");
}
adaptador = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, aniNomes);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
conteudo.setAdapter(adaptador);
}
}
}
New code after the proposed modification.
THANKS FOR THE HELP!!!
package br.com.testejsoup.eu.testejsoup;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ListView conteudo;
ArrayList<String> aniNomes = new ArrayList<>();
ArrayList<String> aniLinks = new ArrayList<>();
ArrayAdapter<String> adaptador;
Document doc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
conteudo = findViewById(R.id.html_conteudo);
new doit().execute();
conteudo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int posicao = position;
Intent intent = new Intent(MainActivity.this, Episodio.class);
intent.putExtra("aniLinks", aniLinks.get(position));
//Toast.makeText(getApplicationContext(), aniLinks[posicao], Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
public class doit extends AsyncTask<Void, Void, Void>{
String URL = "http://www.URL.com/lancamentos?page=";
String nomeExp;
Elements nome;
Elements links;
int paginas = 5;
#Override
protected Void doInBackground(Void... voids) {
try {
for (int i=1; i<= paginas;i++) {
String new_URL = URL + i;
doc = Jsoup.connect(new_URL).get();
nome = doc.select("div.nome-thumb a.tt");
links = doc.select("div.nome-thumb a.tt");
for (Element nomeT : nome){
aniNomes.add(nomeT.text());
}
for (Element linkT : links){
aniLinks.add(linkT.attr("abs:HREF"));
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adaptador = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, aniNomes);
conteudo.setAdapter(adaptador);
}
}
}

Its because you're creating a new adapter in your asynctask and then in your onPostExecute method you're calling setAdapter which swaps out the old adapter and its entries with the new adapter and its new entries.
Rather than creating a new adapter in your asynctask I would just create an array/arraylist, add the new entries to it and then in your onPostExecute just append the entries from this array/list into the one and only adapter entry set.

Related

adapter.notifyDataSetChanged() not working

I've wrote this code. Somehow when I call notifyDatasetChanged on my adapter it doesn't work. Could anyone explain me why this doesn't work.
Also I have another question (I think related to this) I give at the creation of the class a HoodID = 27 but how can I do this another way because when I do this I can't select the first item in my Spinner.
package com.example.sander.app;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.LegendRenderer;
import com.jjoe64.graphview.helper.StaticLabelsFormatter;
import com.jjoe64.graphview.series.BarGraphSeries;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.DataPointInterface;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview.series.OnDataPointTapListener;
import com.jjoe64.graphview.series.Series;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import android.R.layout.*;
import android.widget.Toast;
/**
* Created by Sander on 8-4-2017.
*/
public class GraphFrame extends Fragment implements AdapterView.OnItemSelectedListener {
Integer hoodSelector = 27;
ArrayList<HoodData> hoodDataList = new ArrayList<>();
ArrayList<String> hoodList = new ArrayList<>();
Context mContext;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void refreshFragment(){
hoodDataList.clear();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.detach(this).attach(this).commit();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_graph,
container, false);
//API Request for all the hoods
getDataFromApi((GraphView) view.findViewById(R.id.graph));
getDataForSpinner((Spinner) view.findViewById(R.id.spinner));
return view;
}
public void setHoodId(Integer hood){
hoodSelector = hood;
}
public void getDataFromApi(final GraphView graph) {
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
String url= "http://test.dontstealmywag.ga/api/damage_or_theft_car_wijk.php?hood_id=" + hoodSelector;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
try{
JSONObject o = new JSONObject(response);
JSONArray values=o.getJSONArray("");
for (int i = 0; i < values.length(); i++) {
JSONObject jsonObject = values.getJSONObject(i);
hoodDataList.add(new HoodData(jsonObject.getDouble("percentage"), jsonObject.getInt("hood_id"), jsonObject.getInt("year"), jsonObject.getString("hood_name")));
}
} catch (JSONException ex){}
StaticLabelsFormatter staticLabelsFormatter = new StaticLabelsFormatter(graph);
LineGraphSeries<DataPoint> series = new LineGraphSeries<>(new DataPoint[] {
new DataPoint(1, hoodDataList.get(0).getPercentage()),
new DataPoint(2, hoodDataList.get(1).getPercentage()),
new DataPoint(3, hoodDataList.get(2).getPercentage()),
new DataPoint(4, hoodDataList.get(3).getPercentage()),
new DataPoint(5, hoodDataList.get(4).getPercentage())
//new DataPoint(12, 0)
});
// set manual x bounds
staticLabelsFormatter.setHorizontalLabels(new String[] {"2006", "2007","2008","2009","2011"});
//creates custom x-axis
graph.getGridLabelRenderer().setLabelFormatter(staticLabelsFormatter);
graph.setTitle("Wijk " + hoodSelector + " - " + hoodDataList.get(0).getHood_name());
//set nice background color :)
series.setDrawBackground(true);
//shows points at datapoints
series.setDrawDataPoints(true);
//size of the points
series.setDataPointsRadius(10.0f);
series.setOnDataPointTapListener(new OnDataPointTapListener() {
#Override
public void onTap(Series series, DataPointInterface dataPoint) {
Toast.makeText(getActivity(), "Punt "+ dataPoint, Toast.LENGTH_SHORT).show();
}
});
series.setTitle("%");
series.setAnimated(true);
graph.getLegendRenderer().setVisible(true);
graph.getLegendRenderer().setAlign(LegendRenderer.LegendAlign.TOP);
graph.addSeries(series);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
rq.add(stringRequest);
}
public void getDataForSpinner(final Spinner spinner){
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
String url= "http://test.dontstealmywag.ga/api/damage_or_theft_car_wijk.php";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
try{
JSONObject o = new JSONObject(response);
JSONArray values=o.getJSONArray("");
for (int i = 0; i < values.length(); i++) {
JSONObject jsonObject = values.getJSONObject(i);
if (!hoodList.contains(jsonObject.getString("hood_name"))) {
hoodList.add(jsonObject.getString("hood_name"));
}
}
} catch (JSONException ex){}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(spinner.getContext(), android.R.layout.simple_spinner_item, hoodList);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setPrompt("Title");
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
for(int i = 1; i < hoodList.size(); i++) {
if (item.equals(hoodList.get(i))) {
setHoodId(i + 27);
adapter.notifyDataSetChanged();
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
rq.add(stringRequest);
}
}
Declare
private GraphView mGraphView;
private Spinner mSpinner;
private ArrayAdapter<String> adapter;
And remove parameter in method getDataFromApi and getDataForSpinner.
Recall getDataFromApi instead of adapter.notifyDataSetChanged();
Add adapter.notifyDataSetChanged(); in the end of onResponse in getDataFromApi

Cannot Find symbol method setOnItemClickListener

so I currently have a list of returned JSON objects as a ListView on my application, and I'm trying to make it so that I can click the object and then edit the details, however I'm at a bit of a loss as to why my setOnItemClickListener isn't working, code below
package mmu.tom.linkedviewproject;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private ListView GetAllDevicesListView;
private JSONArray jsonArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.GetAllDevicesListView = (ListView) this.findViewById(R.id.GetAllDevicesListView);
new GetAllDevicesTask().execute(new ApiConnector());
GetAllDevicesTask.setOnItemClickListener (new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
try
{
//GetDevice that was clicked
JSONObject deviceClicked = jsonArray.getJSONObject(position);
//Send DeviceId
Intent showDetails = new Intent(getApplicationContext(), DeviceDetailsActivity.class);
showDetails.putExtra("deviceID", deviceClicked.getString("deviceID"));
}
catch(
JSONException e
)
{
e.printStackTrace();
}
}
});
}
public void setListAdapter(JSONArray jsonArray){
this.jsonArray = jsonArray;
this.GetAllDevicesListView.setAdapter((new GetAllDeviceListViewAdapter(jsonArray,this)));
}
private class GetAllDevicesTask extends AsyncTask<ApiConnector,Long,JSONArray>
{
#Override
protected JSONArray doInBackground(ApiConnector... params) {
// it is executed on Background thread
return params[0].GetAllDevicesState();
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
setListAdapter(jsonArray);
}
}
}
You are not taking List view object.
Change to this.
GetAllDevicesListView.setOnItemClickListener (new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
try
{
//GetDevice that was clicked
JSONObject deviceClicked = jsonArray.getJSONObject(position);
//Send DeviceId
Intent showDetails = new Intent(getApplicationContext(), DeviceDetailsActivity.class);
showDetails.putExtra("deviceID", deviceClicked.getString("deviceID"));
}
catch(
JSONException e
)
{
e.printStackTrace();
}
}
});
You are not setting the setOnItemClickListener on a ListView but on a class name.
Change
GetAllDevicesTask.setOnItemClickListener (new AdapterView.OnItemClickListener() {
to
GetAllDevicesListView.setOnItemClickListener (new AdapterView.OnItemClickListener() {

How can I delete an item from an online database via android application?

I started to develop Android recently and I'm having difficulty in solving a thing probably much simpler than what I think.
I am creating a CRUD application that communicates with an online database, I can read and enter data, unfortunately I can't delete and modify the list once it is created.
To manage the data that use JSON and the row in the list that I add is made up of three fields: animal_id, animal_name, animal_type.
The activity data on which I read and on which I want to implement methods to modify and delete via listener is formed by the following code:
import java.sql.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ListAnimalActivity extends ListActivity {
ArrayList<HashMap<String,?>> animalList;
JSONParser jParser = new JSONParser();
JSONArray animals = null;
Button button_add;
private static String url_read = "http://example.com/list_animals.php";
private static String url_delete = "http://example.com/delete_animal.php";
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
load_ListAnimalActivity();
}
public void onResume(){
super.onResume();
load_ListAnimalActivity();
}
private void load_ListAnimalActivity(){
setContentView(R.layout.activity_list_animal);
animalList = new ArrayList<HashMap<String,?>>();
new Read_Object().execute();
final ListView listView = (ListView)findViewById(android.R.id.list);
final ListAdapter adapter = new SimpleAdapter(
ListAnimalActivity.this, animalList,
R.layout.row_list, new String[] { "animal_id",
"animal_name","animal_type"},
new int[] { R.id.animal_id, R.id.animal_name,R.id.animal_type });
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder adb = new AlertDialog.Builder(ListAnimalActivity.this);
adb.setTitle("Attenzione!");
adb.setMessage("Vuoi eliminare l\'elemento \"" + animalList.get(position)+ "\" ?");
final int posizione = position;
adb.setNegativeButton("Annulla",new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {}
});
adb.setPositiveButton("Elimina", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new Delete_Object().execute();
}
});
adb.show();
}
});
button_add = (Button)findViewById(R.id.button_add);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ListAnimalActivity.this,CRUDAnimalActivity.class));
}
});
}
class Read_Object extends AsyncTask<String, String, String> {
private ProgressDialog progressMessage = new ProgressDialog(ListAnimalActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressMessage.setMessage("Loading ...");
progressMessage.setIndeterminate(false);
progressMessage.setCancelable(false);
progressMessage.show();
}
protected String doInBackground(String... args) {
List params = new ArrayList();
JSONObject json = jParser.makeHttpRequest(url_read, "POST", params);
try{
Log.d("Animals: ", json.toString());
} catch (NullPointerException e){
e.printStackTrace();
}
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
animals = json.getJSONArray("animals");
for (int i = 0; i < animals.length(); i++) {
JSONObject c = animals.getJSONObject(i);
String id = c.getString("animal_id");
String name = c.getString("animal_name");
String type = c.getString("animal_type");
HashMap map = new HashMap();
map.put("animal_id", id);
map.put("animal_name", name);
map.put("animal_type", type);
animalList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
progressMessage.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
ListAnimalActivity.this, animalList,
R.layout.row_list, new String[] { "animal_id",
"animal_name","animal_type"},
new int[] { R.id.animal_id, R.id.animal_name,R.id.animal_type });
setListAdapter(adapter);
}
});
}
}
class Delete_Object extends AsyncTask<String, String, String>{
private ProgressDialog progressMessage = new ProgressDialog(ListAnimalActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressMessage.setMessage("Deleting ...");
progressMessage.setIndeterminate(false);
progressMessage.setCancelable(false);
progressMessage.show();
}
protected String doInBackground(String... args) {
/*
Code to delete
*/
return null;
}
protected void onPostExecute(String file_url){
}
}
}
When i click on a list Item, the listener show me the object in this format:
{animal_type=firstType, animal_name=firstName, animal_id=1}
So my question is:
How can I collect only animal_id from the array animalList > ?
Your animalList is an array list with HashMaps as its elements, so when you call animalList.get(position), it will return a HashMap. To retrieve an animal_id just use :
(animalList.get(position)).get(animal_id).toString();
you have to create a Modelclass/Pojo Class (Private variable and getters and setters) for Animals,
ArrayList<AnimalModel> animalsArrayList = new ArrayList<AnimalModel>();
add the Animals object/data to animalsArrayList and listview.setAdapter(animalsArrayList);
then
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Object object = speakerListView.getItemAtPosition(position);
AnimalModel animals_data = (AnimalModel) object;
id = animals_data.getAnimal_id()
// call delete Async with thid Id
}
});
You code looks pretty messy. If I were you I would create a Custom Adapter that extends the base adapter and takes as a parameter either a hashmap or a list that you pass in the constructor. There you can have different listeners. Also if you want to notify the activity you can have the "luxury" to pass an interface as a parameter and notify the activity when something changes.
Regarding the json part, I would create two new classes, one which is a Thread Manager that receives tasks and handles them further and another class where u make the http calls and the json parsing.
I have done a similar application that receives data from a nebula interface and displays them to the user.

how to get all editext's value from ListItems in android and pass them to api

I have made an activity in that one ListView is ther,In that ListView each listItem is having an editText named "qty",which can be edited,one textView is there which displays "price",I need is when i edit the edittext and if the entered value is more than some limi the textView value will change,After that i have to pass them as a parameter to an api as below:
http://yehki.epagestore.in/app_api/updateCart.php?customer_id=41&product_id=30&quantity=90&product_id=23&quantity=90
from that i will get subtotal's of eact item and have to set them to each item in the list,can anyone please help me for it?My code is as below..Please help me save my life...thank you
main.java
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.epe.yehki.adapter.CartAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.example.yehki.R;
public class CartListActivity extends Activity {
private ProgressDialog pDialog;
Intent in = null;
ListView lv;
JSONObject jsonObj;
ArrayList<HashMap<String, String>> cartList;
Bitmap bitmap;;
private CartAdapter cartContent;
JSONArray carts = null;
ImageView back;
TextView tv_place_order, tv_home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_cart_list);
lv = (ListView) findViewById(R.id.cart_list);
back = (ImageView) findViewById(R.id.iv_bak);
tv_place_order = (TextView) findViewById(R.id.tv_place_order);
tv_home = (TextView) findViewById(R.id.tv_home);
cartList = new ArrayList<HashMap<String, String>>();
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
// execute the cartList api()...........!!!!
new GetCartList().execute();
// listView ClickEvent
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
lv.removeViewAt(position);
cartContent.notifyDataSetChanged();
}
});
tv_home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
in = new Intent(CartListActivity.this, HomeActivity.class);
startActivity(in);
}
});
tv_place_order.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
/*
* CART LIST PRODUCT LIST...............!!!!!!!!!
*/
private class GetCartList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CartListActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
String cartUrl = Const.API_CART_LIST + "?customer_id=" + Pref.getValue(CartListActivity.this, Const.PREF_CUSTOMER_ID, "");
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(cartUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_PRO_LIST)) {
carts = jsonObj.getJSONArray(Const.TAG_PRO_LIST);
if (carts != null && carts.length() != 0) {
// looping through All Contacts
for (int i = 0; i < carts.length(); i++) {
JSONObject c = carts.getJSONObject(i);
String proId = c.getString(Const.TAG_PRODUCT_ID);
String proName = c.getString(Const.TAG_PRODUCT_NAME);
String wPrice = c.getString(Const.TAG_WHOLESALE_PRICE);
String rPrice = c.getString(Const.TAG_RETAIL_PRICE);
String qty = c.getString(Const.TAG_QUANTITY);
String proimg = Const.API_HOST + "/" + c.getString(Const.TAG_PRODUCT_IMG);
HashMap<String, String> cartProduct = new HashMap<String, String>();
cartProduct.put(Const.TAG_PRODUCT_ID, proId);
cartProduct.put(Const.TAG_PRODUCT_NAME, proName);
cartProduct.put(Const.TAG_PRODUCT_IMG, proimg);
cartProduct.put(Const.TAG_WHOLESALE_PRICE, wPrice);
cartProduct.put(Const.TAG_RETAIL_PRICE, rPrice);
cartProduct.put(Const.TAG_QUANTITY, qty);
cartList.add(cartProduct);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
cartContent = new CartAdapter(CartListActivity.this, cartList);
lv.setAdapter(cartContent);
}
}
}
In ListAdapter, getItem() should return an item using which you populate the Views
#Override
public HashMap<String, String> getItem(int paramInt) {
return cartArray.get(paramInt);
}
To get all values,
final CartAdapter adapter = (CardAdapter) lv.getAdapter();
for (int i = 0; i < adapter.getCount(); i++) {
final HashMap<String, String> item = adapter.getItem(i);
final String quantity = item.get(Const.TAG_QUANTITY); // value of EditText of one row
}

android - removing list view items before rebuilding list view

I have a list view, when I go back and come back to my list activity the list is duplicated. The first list needs to be removed so only one list is displayed. Any ideas???
This is my List Activity code:
package com.sportspubfinder;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class ListPubsActivity extends Activity {
ProgressDialog ShowProgress;
ListView lv1;
int selectedRadius;
Double userLat;
Double userLong;
public static ArrayList<SetterGetter> PubList = new ArrayList<SetterGetter>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pubslist);
lv1 = (ListView) findViewById(R.id.listView1);
Bundle extras = getIntent().getExtras();
if(extras != null){
//retrieve the passed through radius and location readings
selectedRadius = extras.getInt("radius_set");
userLat = extras.getDouble("latitude_set");
userLong = extras.getDouble("longitude_set");
}
//show progres bar whilst a connection is made with the url
ShowProgress = ProgressDialog.show(ListPubsActivity.this, "",
"Loading Pubs. Please wait...", true);
/* --If the INAPUB api was implemented, the url would take the passed radius (selectRadius) and location of the user---
* "http://api.inapub.co.uk/venues/geocode/"+userLat+"/"+userLong+"/"+selectedRadius+"/?API_Key=7xa3tdmjkhu6jwjvp746zgg4");*/
new loadingTask().execute("http://itsuite.it.brighton.ac.uk/jp232/pubs.php");
//check which list item has been selected
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(ListPubsActivity.this, PubActivity.class);
//pass the pubs information through to the next activity
intent.putExtra("pubName", PubList.get(position).getName());
intent.putExtra("pubImage", PubList.get(position).getThumbnail());
intent.putExtra("pubAddress", PubList.get(position).getAddress());
intent.putExtra("pubTown", PubList.get(position).getTown());
intent.putExtra("pubCounty", PubList.get(position).getCounty());
intent.putExtra("pubDescription", PubList.get(position).getDescription());
intent.putExtra("pubFacilities", PubList.get(position).getFacilities());
intent.putExtra("pubRating", PubList.get(position).getRating());
intent.putExtra("pubLatitude", PubList.get(position).getLatitude());
intent.putExtra("pubLongitude", PubList.get(position).getLongitude());
startActivity(intent);
}
});
}
class loadingTask extends AsyncTask<String, Void, String> {
//check if there's an Internet connection
/*public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null &&
cm.getActiveNetworkInfo().isConnectedOrConnecting();
}*/
protected String doInBackground(String... urls) {
//in background wait to receive the information from the ListHandler
SAXHelper sh = null;
try {
sh = new SAXHelper(urls[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
sh.parseContent("");
return "";
}
protected void onPostExecute(String s) {
//add Custom List Adapter once ListHandler has been received
lv1.setAdapter(new CustomAdapter(ListPubsActivity.this, PubList));
//stop progress bar
ShowProgress.dismiss();
}
}
class SAXHelper {
public HashMap<String, String> userList = new HashMap<String, String>();
private URL url2;
public SAXHelper(String url1) throws MalformedURLException {
this.url2 = new URL(url1);
}
public ListHandler parseContent(String parseContent) {
//add the ListHandler
ListHandler df = new ListHandler();
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(df);
xr.parse(new InputSource(url2.openStream()));
} catch (Exception e) {
e.printStackTrace();
}
return df;
}
}
#Override
protected void onPause(){
super.onPause();
}
#Override
protected void onStop(){
super.onStop();
}
}
public static ArrayList PubList = new ArrayList();
I believe, due to the static type, your list contents are getting appended.

Categories

Resources