Firstly, let me tell what I am trying to do...
Please,see the screenshot.When user select a checkbox,I want to add the digit given in the left and show the total on top.example: if user select 3 boxes named chairman,auditor and jr. officer,it will add 3 digits from the left of checkbox. that is 1+1+1=3 and this total will take place on top instead of 0.
I have implemented using listview with checkbox.But now can't add the digits.This values are coming from database.
Let me show you my code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_sms);
// Sets the Toolbar to act as the ActionBar for this Activity window.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Remove default title text
getSupportActionBar().setDisplayShowTitleEnabled(false);
// Get access to the custom title view
TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
openInfo();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(GroupSms.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("all_group");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
gid = c.getString("group_id");
groupName = c.getString("group_name");
total = c.getString("total");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
contact.put("group_id", gid);
contact.put("group_name", groupName);
contact.put("total", total);
//contact.put("mobile", mobile);
// adding contact to contact list
contactList.add(contact);
Log.d("Contactlist", String.valueOf(contactList));
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
/* *
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
GroupSms.this,
contactList,
R.layout.groups,
new String[]{
"group_name","total"},
new int[]{R.id.check,R.id.groupsNo});
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckBox cb = (CheckBox) view.findViewById(R.id.check);
cb.setChecked(!cb.isChecked());
if(cb.isChecked())
{
//TextView cTotal = (TextView) findViewById(R.id.idTotal);
Toast.makeText(GroupSms.this,cb.getText(),Toast.LENGTH_SHORT).show();
}
}
});
}
}
Try On lv.setOnItemClickListener event on AdapterClass.
Related
I'm working on an Android app that uses information form an API and displays it in a list view. It works, but I can't figure out how to implement Swipe to Refresh properly. Right now when it refreshes it doesnt update the data in the lists TextView fields, but adds more of them underneath. I'm very new to this and would appreciate help figuring it out.
Here is the code I have so far.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
ArrayList<HashMap<String, String>> coinList;
ArrayList<HashMap<String, String>> priceList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Swipe Refresh tests
final SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeView.setEnabled(false);
ListView lView = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adp = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, R.id.list);
lView.setAdapter(adp);
swipeView.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeView.setRefreshing(true);
( new Handler()).postDelayed(new Runnable() {
#Override
public void run() {
swipeView.setRefreshing(false);
}
}, 1000);
new GetStats().execute();
}
});
lView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int i) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem == 0)
swipeView.setEnabled(true);
else
swipeView.setEnabled(false);
}
});
///// END OF SWIPE REFRESH TEST CODE ////
coinList = new ArrayList<>();
priceList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list); // Needs to be here seemingly!!
new GetStats().execute();
}
// Async task class to get JSON over HTTP call
private class GetStats extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute () {
super.onPreExecute();
// Progress Dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please Wait...");
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// URL request and response
String url = "URL";
String url2 = "URL";
String jsonStr = sh.makeServiceCall(url);
String jsonStr2 = sh.makeServiceCall(url2);
Log.e(TAG, "Response from url: " + jsonStr);
Log.e(TAG, "Response from url2: " + jsonStr2);
if (jsonStr != null) {
try { /// BEGINNING of Parsing Try
JSONObject jsonObj = new JSONObject(jsonStr);
// Get JSON Object "getuserallbalances"
JSONObject userBalances = jsonObj.getJSONObject("getuserallbalances");
// Get JSON Array "data"
JSONArray data = userBalances.getJSONArray("data");
// Loop through all data
for (int i = 0; i < data.length(); i++) {
JSONObject d = data.getJSONObject(i);
String coin = d.getString("coin");
String confirmed = d.getString("confirmed");
String unconfirmed = d.getString("unconfirmed");
String aeConfirmed = d.getString("ae_confirmed");
String aeUnconfirmed = d.getString("ae_unconfirmed");
String exchange = d.getString("exchange");
//Convert to BigDecimal
BigDecimal dConfirmed = new BigDecimal(confirmed);
BigDecimal dUnconfirmed = new BigDecimal(unconfirmed);
BigDecimal dAeConfirmed = new BigDecimal(aeConfirmed);
BigDecimal dAeUnconfirmed = new BigDecimal(aeUnconfirmed);
BigDecimal dExchange = new BigDecimal(exchange);
// Temp HashMap for single coin
HashMap<String, String> coins = new HashMap<>();
// Add each child node to HashMap key => value
coins.put("coin", coin.toUpperCase());
coins.put("confirmed", "Confirmed: " + dConfirmed);
coins.put("exchange", "Exchange: " + dExchange);
coins.put("unconfirmed", "Unconfirmed: " + dUnconfirmed);
coins.put("ae_confirmed", "AE Confirmed: " + dAeConfirmed);
coins.put("ae_unconfirmed", "AE Unconfirmed: " + dAeUnconfirmed);
// Add to list
coinList.add(coins);
}
} catch (final JSONException e) { /// END of Parsing TRY
Log.e(TAG, "JSON parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"JSON parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get JSON from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get JSON from server. Check LogCat!",
Toast.LENGTH_LONG).show();
}
});
}
// Second API call (CoinMarketCap)
if (jsonStr2 != null) {
try { /// BEGINNING of Parsing Try
// Get JSON Array
JSONArray jsonArr = new JSONArray(jsonStr2);
// Loop through all data
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject p = jsonArr.getJSONObject(i);
String id = p.getString("id");
String price_usd = p.getString("price_usd");
// Temp HashMap for single coin
HashMap<String, String> prices = new HashMap<>();
// Add each child node to HashMap key => value
prices.put("id", id.toUpperCase());
prices.put("perice_usd", price_usd);
// Add to list
priceList.add(prices);
}
} catch (final JSONException e) { /// END of Parsing TRY
Log.e(TAG, "JSON parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"JSON parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get JSON from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get JSON from server. Check LogCat!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// Update parsed JSON into ListView
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, coinList,
R.layout.list_item, new String[]{"coin", "confirmed",
"exchange", "unconfirmed", "ae_confirmed", "ae_unconfirmed"}, new int[]{R.id.coin,
R.id.confirmed, R.id.exchange, R.id.unconfirmed, R.id.ae_confirmed, R.id.ae_unconfirmed});
lv.setAdapter(adapter);
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
Hope this makes some sense and would really apreciate any help! If I can get that working, I will probably have more questions, but right now one thing at a time. :P
Thanks! :)
In your swipe refresh listener when you call your async task, your are creating a new adapter every time. simply call notifyDataChanged on your data.
In your on background task first check if the data is already present in your priceList then don't add the item in your list.
Or you can first clear the list and then add all the result from json in to price list.
Here is the code which clears list on swipe refresh:
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
ListAdapter adapter;
ArrayList<HashMap<String, String>> coinList;
ArrayList<HashMap<String, String>> priceList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Swipe Refresh tests
final SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeView.setEnabled(false);
ListView lView = (ListView) findViewById(R.id.list);
adapter = new SimpleAdapter(
MainActivity.this, coinList,
R.layout.list_item, new String[]{"coin", "confirmed",
"exchange", "unconfirmed", "ae_confirmed", "ae_unconfirmed"}, new int[]{R.id.coin,
R.id.confirmed, R.id.exchange, R.id.unconfirmed, R.id.ae_confirmed, R.id.ae_unconfirmed});
lView.setAdapter(adapter);
swipeView.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeView.setRefreshing(true);
( new Handler()).postDelayed(new Runnable() {
#Override
public void run() {
swipeView.setRefreshing(false);
}
}, 1000);
new GetStats().execute();
}
});
lView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int i) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem == 0)
swipeView.setEnabled(true);
else
swipeView.setEnabled(false);
}
});
///// END OF SWIPE REFRESH TEST CODE ////
coinList = new ArrayList<>();
priceList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list); // Needs to be here seemingly!!
new GetStats().execute();
}
// Async task class to get JSON over HTTP call
private class GetStats extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute () {
super.onPreExecute();
// Progress Dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please Wait...");
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// URL request and response
String url = "https://miningpoolhub.com/index.php?page=api&action=getuserallbalances&api_key=MyApiKey";
String url2 = "https://api.coinmarketcap.com/v1/ticker/";
String jsonStr = sh.makeServiceCall(url);
String jsonStr2 = sh.makeServiceCall(url2);
Log.e(TAG, "Response from url: " + jsonStr);
Log.e(TAG, "Response from url2: " + jsonStr2);
if (jsonStr != null) {
try {
coinList.clear(); /// BEGINNING of Parsing Try
JSONObject jsonObj = new JSONObject(jsonStr);
// Get JSON Object "getuserallbalances"
JSONObject userBalances = jsonObj.getJSONObject("getuserallbalances");
// Get JSON Array "data"
JSONArray data = userBalances.getJSONArray("data");
// Loop through all data
for (int i = 0; i < data.length(); i++) {
JSONObject d = data.getJSONObject(i);
String coin = d.getString("coin");
String confirmed = d.getString("confirmed");
String unconfirmed = d.getString("unconfirmed");
String aeConfirmed = d.getString("ae_confirmed");
String aeUnconfirmed = d.getString("ae_unconfirmed");
String exchange = d.getString("exchange");
//Convert to BigDecimal
BigDecimal dConfirmed = new BigDecimal(confirmed);
BigDecimal dUnconfirmed = new BigDecimal(unconfirmed);
BigDecimal dAeConfirmed = new BigDecimal(aeConfirmed);
BigDecimal dAeUnconfirmed = new BigDecimal(aeUnconfirmed);
BigDecimal dExchange = new BigDecimal(exchange);
// Temp HashMap for single coin
HashMap<String, String> coins = new HashMap<>();
// Add each child node to HashMap key => value
coins.put("coin", coin.toUpperCase());
coins.put("confirmed", "Confirmed: " + dConfirmed);
coins.put("exchange", "Exchange: " + dExchange);
coins.put("unconfirmed", "Unconfirmed: " + dUnconfirmed);
coins.put("ae_confirmed", "AE Confirmed: " + dAeConfirmed);
coins.put("ae_unconfirmed", "AE Unconfirmed: " + dAeUnconfirmed);
Coin coinObj= new Coin(/*pass the arguments*/);
// Add to list
coinList.add(coins);
}
} catch (final JSONException e) { /// END of Parsing TRY
Log.e(TAG, "JSON parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"JSON parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get JSON from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get JSON from server. Check LogCat!",
Toast.LENGTH_LONG).show();
}
});
}
// Second API call (CoinMarketCap)
if (jsonStr2 != null) {
try {
priceList.clear(); /// BEGINNING of Parsing Try
// Get JSON Array
JSONArray jsonArr = new JSONArray(jsonStr2);
// Loop through all data
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject p = jsonArr.getJSONObject(i);
String id = p.getString("id");
String price_usd = p.getString("price_usd");
// Temp HashMap for single coin
HashMap<String, String> prices = new HashMap<>();
// Add each child node to HashMap key => value
prices.put("id", id.toUpperCase());
prices.put("perice_usd", price_usd);
// Add to list
priceList.add(prices);
}
} catch (final JSONException e) { /// END of Parsing TRY
Log.e(TAG, "JSON parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"JSON parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get JSON from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get JSON from server. Check LogCat!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// Update parsed JSON into ListView
// ListAdapter adapter = new SimpleAdapter(
// MainActivity.this, coinList,
// R.layout.list_item, new String[]{"coin", "confirmed",
// "exchange", "unconfirmed", "ae_confirmed", "ae_unconfirmed"}, new int[]{R.id.coin,
// R.id.confirmed, R.id.exchange, R.id.unconfirmed, R.id.ae_confirmed, R.id.ae_unconfirmed});
adapter.notifyDataSetChanged();
}
}
}
I cant send all the rows of list view,Every time just last row of list view is going to the server,i want send all the items of list view when i click place order button.here is edited code my full code:
public class Order_From_App_All_new extends Activity implements View.OnClickListener {
ProgressDialog mProgressDialog
ArrayList<Actor> productlist = new ArrayList<>();
TextView txt1;
Button order;
ListView listview;
ImageView ivImage;
EditText edt2;
String address;
TextView txt17;
int position;
String product_id;
String product_qty;
ListView listview1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.orderfromapp);
listview = (ListView) findViewById(R.id.listView1);
order=(Button)findViewById(R.id.button4);
edt2=(EditText)findViewById(R.id.editText2);
ListView listview = (ListView) findViewById(R.id.listView1);
adapter = new Product_Adapter(Order_From_App_All_new.this, R.layout.row1, productlist);
listview.setAdapter(adapter);
new DownloadJSON().execute();
order.setOnClickListener(this);
}
// #Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
product_name = (String) mySpinner.getSelectedItem();
String product_quantity = edt1.getEditableText().toString();
String addtocartquerystring = "?product_name=" + product_name + "&product_quantity=" + product_quantity;
Log.d("Request : ", "starting 00 " + CC14.GETURL17 + addtocartquerystring);
new GetAddToCart(this, CC14.GETURL17 + addtocartquerystring).execute();
break;
case R.id.button4:
address=edt2.getEditableText().toString();
String[] productid = new String[productlist.size()];
String[] productquantity = new String[productlist.size()];
for (int i = 0; i < productlist.size(); i++) {
productid[i]=productlist.get(i).getProductid();
productquantity[i]=productlist.get(i).getProductquantity();
product_qty=productquantity[i];
product_id=productid[i];
}
String placeorderquerystring = "?address=" + address + "&product_id=" + product_id+"&product_qty="product_qty;
Log.d("Request : ", "starting 00 " + CC14.GETURL23 + placeorderquerystring);
new GetPlaceOrder(Order_From_App_All_new.this, CC14.GETURL23 + placeorderquerystring).execute();
break;
default:
break;
}
}
public class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Locate the WorldPopulation Class
// productlist = new ArrayList<>();
// Create an array to populate the spinner
spinnerlist = new ArrayList<String>();
// JSON file URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://duraent.net/android_order_app/api/android/orderList.php");
try {
// Locate the NodeList name
jsonarray = jsonobject.getJSONArray("product");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
spinnerlist.add(jsonobject.optString("productname"));
// Actor actors = new Actor();
// actors.setProductname("Productname", jsonobject.optString("Productname"));
// actors.setDirectmobileorderprice("directmobileorderprice", jsonobject.getString("directmobileorderprice"));
// productlist.add(actors);
//Populate spinner with country names
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the spinner in activity_main.xml
Spinner mySpinner = (Spinner) findViewById(R.id.spinner2);
// Spinner adapter
mySpinner
.setAdapter(new ArrayAdapter<String>(Order_From_App_All_new.this,
android.R.layout.simple_spinner_dropdown_item,
spinnerlist));
}
}
public class GetAddToCart extends AsyncTask<String, String, String> {
Http_OrderFromAppNew request = new Http_OrderFromAppNew();
Context ctx;
ListView listview;
TextView txt1;
String latLong_url;
ProgressDialog pd;
private String json;
public GetAddToCart(Context _ctx, String _latong_url) {
ctx = _ctx;
latLong_url = _latong_url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(Order_From_App_All_new.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
// Locate the WorldPopulation Class
// Create an array to populate the spinner
// spinnerlist = new ArrayList<String>();
// JSON file URL address
String json = request
.makeHttpRequest(latLong_url, "GET", null);
// Populate spinner with country names
Log.d("Request Login attempt", json.toString());
return json;
}
#Override
protected void onPostExecute(String json) {
// Locate the spinner in activity_main.xml
//adapter.notifyDataSetChanged();
try {
JSONObject jsonobject = new JSONObject(json);
// Locate the NodeList name
jsonarray = jsonobject.getJSONArray("product");
for (int i = 0; i < jsonarray.length(); i++) {
try {
jsonobject = jsonarray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
// spinnerlist.add(jsonobject.optString("productname"));
Actor actors = new Actor();
actors.setProductname("productname",jsonobject.getString("productname"));
actors.setProductid("productid",jsonobject.getString("productid"));
actors.setSellingprice("sellingprice",jsonobject.getString("sellingprice"));
actors.setPricetotal("pricetotal", jsonobject.getString("pricetotal"));
actors.setProductquantity("productquantity", jsonobject.getString("productquantity"));
productlist.add(actors);
adapter.changeData(productlist);
// ListView listview = (ListView) findViewById(R.id.listView1);
//adapter = new Product_Adapter(getApplicationContext(), R.layout.row1, productlist);
//adapter.notifyDataSetChanged();
//listview.setAdapter(adapter);
mProgressDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class GetPlaceOrder extends AsyncTask<String, String,String> {
Http_OrderFromAppNew request = new Http_OrderFromAppNew();
Context ctx;
ListView listview;
TextView txt1;
String latLong_url;
ProgressDialog pd;
private String json;
public GetPlaceOrder(Context _ctx, String _latong_url) {
ctx = _ctx;
latLong_url = _latong_url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(Order_From_App_All_new.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
// Locate the WorldPopulation Class
// Create an array to populate the spinner
// spinnerlist = new ArrayList<String>();
// JSON file URL address
String json = request
.makeHttpRequest(latLong_url, "GET", null);
// Populate spinner with country names
Log.d("Request Login attempt", json.toString());
return json;
}
#Override
protected void onPostExecute(String json) {
// Locate the spinner in activity_main.xml
//adapter.notifyDataSetChanged();
try {
TextView txt17=(TextView)findViewById(R.id.textView17);
txt17.append(json);
mProgressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The few lines doing the sending should be inside the for loop:
for (int i = 0; i < productlist.size(); i++) {
productid[i]=productlist.get(i).getProductid();
productquantity[i]=productlist.get(i).getProductquantity();
product_qty=productquantity[i];
product_id=productid[i];
String placeorderquerystring = "?address=" + address + "&product_id=" + product_id+"&product_qty="product_qty;
Log.d("Request : ", "starting 00 " + CC14.GETURL23 + placeorderquerystring);
new GetPlaceOrder(Order_From_App_All_new.this, CC14.GETURL23 + placeorderquerystring).execute();
}
You need to send the cart items as an JSON obj or array to server,
{
"Customer":"Name",
"cart":"Cart ID",
"date":"10-06-2016",
"time":"3.36",
"cartItems":[
{
"ProductID":"1",
"ProductQuantity":"3"
},
{
"ProductID":"2",
"ProductQuantity":"5"
},
{
"ProductID":"6",
"ProductQuantity":"4"
}
]
}
To get the above format, use the following code
private String getItems() {
JSONObject dataObj = new JSONObject();
try {
dataObj.putOpt("Customer", "Name");
dataObj.putOpt("cart", "Cart ID");
dataObj.putOpt("date", "DATE");
dataObj.putOpt("time", "TIME");
JSONArray cartItemsArray = new JSONArray();
JSONObject cartItemsObjedct;
for (int i = 0; i < cartItems.size(); i++) {
cartItemsObjedct = new JSONObject();
cartItemsObjedct.putOpt("ProductID", cartItems.get(i).getId);
cartItemsObjedct.putOpt("ProductQuantity", cartItems.get(i).getProductQuantity);
cartItemsArray.put(cartItemsObjedct);
}
dataObj.put("cartItems", cartItemsArray);
} catch (JSONException e) { // TODO Auto-generated catch bloc
e.printStackTrace();
}
return dataObj.toString();
}
I have Listview for displaying JSON data. I get pdf title but i can't get pdf title images using JSON webservices. In Log the whole data display in arraylist. I used hashmap concept for setting JSON data on Listview. Below is my source code.
// Default url
private static String url = "http://.....";
// JSON Node names
public static final String TAG_DOCUMENT = "docs";
public static final String TAG_TITLE = "name";
public static final String TAG_IMAGEPATH = "imagepath";
ArrayList<HashMap<String, String>> documentList = new ArrayList<HashMap<String,String>>();
Button mPdf_list_btn_more;
ListView lv;
JSONArray document = null;
ProgressDialog pDialog;
// flag for Internet connection status
Boolean isInternetPresent = false;
ConnectionDetector cd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Remove Titlebar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Remove Notificationbar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
setContentView(R.layout.pdf_list);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
mPdf_list_btn_more = (Button)findViewById(R.id.mPdf_list_btn_more);
mPdf_list_btn_more.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(PDF_List.this,Info_Screen.class);
startActivity(i);
}
});
lv = (ListView)findViewById(R.id.listView1);
ServiceHandler sh = new ServiceHandler();
cd = new ConnectionDetector(getApplicationContext());
// new GetPDF().execute();
new GetPDFNew().execute();
}
public void ListViewData() {
/* ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
document = jsonObj.getJSONArray(TAG_DOCUMENT);
// looping through All Contacts
for (int i = 0; i < document.length(); i++) {
JSONObject c = document.getJSONObject(i);
String name = c.getString(TAG_TITLE);
String image_path = c.getString(TAG_IMAGEPATH);
Log.i("Name:--->", name);
Log.i("Image_Path--->",image_path);
// tmp hashmap for single contact
HashMap<String, String> doc = new HashMap<String, String>();
doc.put(TAG_TITLE,name);
doc.put(TAG_IMAGEPATH, image_path);
documentList.add(doc);
Log.i("ArrayList for documentList ","-->"+ documentList);
Log.i("TAG IMAGEPATH IN ListviewData", TAG_IMAGEPATH);
Log.i("TAG TITLE IN ListviewData", TAG_TITLE);
String[] from = {TAG_IMAGEPATH,TAG_TITLE};
final int[] to = {R.id.mImageview_pdf,R.id.mtextview_title};
SimpleAdapter adapter = new SimpleAdapter(PDF_List.this, documentList, R.layout.list_item, from, to);
lv.setAdapter(adapter);
}
}
catch(JSONException e){
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}*/
Log.i("TAG IMAGEPATH IN ListviewData", TAG_IMAGEPATH);
Log.i("TAG TITLE IN ListviewData", TAG_TITLE);
String[] from = {TAG_IMAGEPATH,TAG_TITLE};
final int[] to = {R.id.mImageview_pdf,R.id.mtextview_title};
SimpleAdapter adapter = new SimpleAdapter(PDF_List.this, documentList, R.layout.list_item, from, to);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Object position1 = lv.getItemAtPosition(position);
System.out.println(position1+"-->:item postion");
for (HashMap<String, String> map : documentList)
for (Entry<String, String> mapEntry : map.entrySet())
{
String key = mapEntry.getKey();
String value = mapEntry.getValue();
// Log.i("arraylist key-->",key);
// Log.i("arraylist value-->",value);
// Log.i("cccc","->>"+documentList.get(position).get(key).valueOf(pathforurl+file_path));
}
}
});
}
private class GetPDF extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(PDF_List.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
// Internet Connection is Present
// make HTTP requests
// showAlertDialog(MainActivity.this, "Internet Connection",
// "You have internet connection", true);
} else {
// Internet connection is not present
// Ask user to connect to Internet
showAlertDialog(PDF_List.this, "No Internet Connection",
"You don't have internet connection.", false);
pDialog.dismiss();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
document = jsonObj.getJSONArray(TAG_DOCUMENT);
// looping through All Contacts
for (int i = 0; i < document.length(); i++) {
JSONObject c = document.getJSONObject(i);
String name = c.getString(TAG_TITLE);
String image_path = c.getString(TAG_IMAGEPATH);
Log.i("Name:--->", name);
Log.i("Image_Path--->",image_path);
// tmp hashmap for single contact
HashMap<String, String> doc = new HashMap<String, String>();
doc.put(TAG_TITLE,name);
doc.put(TAG_IMAGEPATH, image_path);
documentList.add(doc);
Log.i("ArrayList for documentList ","-->"+ documentList);
}
}
catch(JSONException e){
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
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
* */
ListViewData();
}
}
private class GetPDFNew extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(PDF_List.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
// Internet Connection is Present
// make HTTP requests
// showAlertDialog(MainActivity.this, "Internet Connection",
// "You have internet connection", true);
} else {
// Internet connection is not present
// Ask user to connect to Internet
showAlertDialog(PDF_List.this, "No Internet Connection",
"You don't have internet connection.", false);
pDialog.dismiss();
}
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListViewData();
}
#Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
document = jsonObj.getJSONArray(TAG_DOCUMENT);
// looping through All Contacts
for (int i = 0; i < document.length(); i++) {
JSONObject c = document.getJSONObject(i);
String name = c.getString(TAG_TITLE);
String image_path = c.getString(TAG_IMAGEPATH);
Log.i("Name:--->", name);
Log.i("Image_Path--->",image_path);
// tmp hashmap for single contact
HashMap<String, String> doc = new HashMap<String, String>();
doc.put(TAG_TITLE,name);
doc.put(TAG_IMAGEPATH, image_path);
documentList.add(doc);
Log.i("ArrayList for documentList ","-->"+ documentList);
}
}
catch(JSONException e){
}
}
return null;
}
}
#SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.ic_launcher : R.drawable.ic_launcher);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
}
You can achieve this by using a simple library called Picasso
The most accurate way and which takes care of everything like cache maintenance , offline rendering and image loading from network as well as from disk
1. Most of the times you may get an exception called bitmap size exceeds vm budget if you not handle it properly in case of bulk images
so i recommend you to go with an Universal image loading library or Picasso
public static void loadNetworkThumNail(final Context context, final ImageView imageview, final String Url) {
Picasso.with(context).load(Url.trim()).resize(98, 98).placeholder(R.drawable.default_image).into(imageview);
}
I have one ListView,I have made a custom adapter for binding data to it,I have made an asynctask in the activity for getting data and display it into the listView,I have two different Urls for the same asyctask ,based on the condition i am using it,Thing is that when i am second time the listView doesn't remove the previous values.
main.java
public class MyMessagesActivity extends Activity {
private ProgressDialog pDialog;
JSONArray msgArry;
private MessageAdapter msgContent;
ArrayList<HashMap<String, String>> msgList;
ListView lv;
JSONArray msgs = null;
String pro_id, pro_name, pro_img, pro_unit;
TextView tv_switch;
public boolean flag = false;
Header header;
Menu menu;
String url;
#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_messgaes);
lv = (ListView) findViewById(R.id.list);
tv_switch = (TextView) findViewById(R.id.tv_switch);
header = (Header) findViewById(R.id.header_msg);
menu = (Menu) findViewById(R.id.menu_msg);
menu.setSelectedTab(3);
header.title.setText("Messages");
msgList = new ArrayList<HashMap<String, String>>();
// url = "?customer_id=" + Pref.getValue(MyMessagesActivity.this,
// Const.PREF_CUSTOMER_ID, "") + "&group_id=2";
tv_switch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (flag) {
tv_switch.setText("Switch to supplier");
new GetMessages().execute();
flag = false;
} else {
tv_switch.setText("Switch to buyer");
new GetMessages().execute();
flag = true;
}
}
});
// AsyncTAsk for Wholesale Product List...!!!
new GetMessages().execute();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
// in = new Intent(getApplicationContext(),
// ProductDetailActivity.class);
/*
* pro_name = ((TextView)
* view.findViewById(R.id.product_label)).getText().toString();
*
* // getting ProductId from the tag...
*
* pro_id = msgList.get(position).get(Const.TAG_PRODUCT_ID);
* pro_name = msgList.get(position).get(Const.TAG_PRODUCT_NAME);
* pro_img = msgList.get(position).get(Const.TAG_PRODUCT_IMG);
* System.out.println(
* ":::::::::::::::;;THE INTENT FOR THE PRODUCUT DETIALS ACTIVITY================="
* + pro_name); Toast.makeText(MyMessagesActivity.this,
* pro_name, Toast.LENGTH_SHORT).show();
*/
// startActivity(in);
}
});
}
private class GetMessages extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MyMessagesActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
String query = Const.API_MESSAGES;
if (flag) {
url = "?customer_id=" + Pref.getValue(MyMessagesActivity.this, Const.PREF_CUSTOMER_ID, "") + "&group_id=1";
} else {
url = "?customer_id=" + Pref.getValue(MyMessagesActivity.this, Const.PREF_CUSTOMER_ID, "") + "&group_id=2";
}
url = url.replace(" ", "%20");
url = query + url;
System.out.println(":::::::::::::My MESSGES URL::::::::::::::" + url);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
msgArry = new JSONArray(jsonStr);
if (msgArry != null && msgArry.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + msgArry.length());
for (int i = 0; i < msgArry.length(); i++) {
JSONObject c = msgArry.getJSONObject(i);
String custID = c.getString(Const.TAG_CUSTOMER_ID);
String custName = c.getString(Const.TAG_CUSTOMER_NAME);
String proID = c.getString(Const.TAG_PRODUCT_ID);
String email = c.getString(Const.TAG_CUSTOMER_EMAIL);
String photo = Const.API_HOST + "/" + c.getString(Const.TAG_PHOTO);
String subject = c.getString(Const.TAG_SUBJECT);
String msg_read = c.getString(Const.TAG_MESSAGE_READ);
HashMap<String, String> message = new HashMap<String, String>();
message.put(Const.TAG_CAT_ID, custID);
message.put(Const.TAG_CUSTOMER_NAME, custName);
message.put(Const.TAG_PRODUCT_ID, proID);
message.put(Const.TAG_CUSTOMER_EMAIL, email);
message.put(Const.TAG_PHOTO, photo);
message.put(Const.TAG_SUBJECT, subject);
message.put(Const.TAG_MESSAGE_READ, msg_read);
msgList.add(message);
}
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Utils.showCustomeAlertValidation(MyMessagesActivity.this, "No messgaes found", "yehki", "Ok");
}
});
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
msgContent = new MessageAdapter(MyMessagesActivity.this, msgList);
msgContent.notifyDataSetChanged();
lv.setAdapter(msgContent);
}
}
}
Please help me for it,thank you eve-one
Try to remove the old records from your HashMap arraylist as below to remove all the data from arraylist.
After binding the data into ListView just clear your arraylist as below:
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
msgContent = new MessageAdapter(MyMessagesActivity.this, msgList);
msgContent.notifyDataSetChanged();
lv.setAdapter(msgContent);
msgList.clear();
}
just clear your list
add mgList.clear(); in protected void onPreExecute()..
Put these lines in OnCreate() method itself,
msgContent = new MessageAdapter(MyMessagesActivity.this, msgList);
lv.setAdapter(msgContent);
Use this line in onPostExecute() of the AsynTask class,
msgContent.notifyDataSetChanged();
If this doesn't work try to add static keyword before msglist variable.
In your doInBackground() add below line before starting for loop:
msgList.clear();
You need to call msgList.clear(); before add data in to msgList arrayList. After that in onPostExecute() method just check condition while set adapter in to listview,
try {
if (msgList!= null
&& msgList.size() > 0) {
msgContent = new MessageAdapter(MyMessagesActivity.this, msgList);
lv.setAdapter(msgContent);
msgContent.notifyDataSetChanged();
} else {
Toast.makeText(YourActivityName.this,
"No Data connection", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
Clearing the msgList is not worked for me. And use
msgList = new ArrayList>();
in doInBackground() before you adding the new content to the list. And just an info, there is no need to call notifyDataSetChanged() when you set a new instance of the adapter to a listview(And there is no problem if you called the notifyDataSetChanged).
msgContent = new MessageAdapter(MyMessagesActivity.this, msgList);
lv.setAdapter(msgContent);
I am developing android app in that i want to display json data in listview with load more button, but when i click load more button old data is replaceing by new one i want both and old and new data to be displayed.Lihstview should show all data whats wrong in the code below
public class Newjava extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
CustomAdapter1 adapter2;
CustomAdapter1 adapter;
ProgressDialog mProgressDialog;
ArrayList<FeedAddress> arraylist;
String url = "http://xxxx.vdv.com/api/fvn/page1";
String arraymovie = "all";
public String string;
ListView listView;
int i = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.list);
arraylist = new ArrayList<FeedAddress>();
// Retrive JSON Objects from the given website URL in
// JSONfunctions.class
jsonobject = JSONfunctions.getJSONfromURL(url);
try {
// Locate the array name
JSONObject jsonObject1 = jsonobject.getJSONObject("appname");
jsonarray = jsonObject1.getJSONArray("kfnh");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject post = (JSONObject) jsonarray.getJSONObject(i);
FeedAddress map = new FeedAddress();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.setMovieName(post.getString("movieName"));
map.setName(post.getString("movieActors"));
map.setMovieId(post.getString("movieId"));
String imageUrl = "http://www.xxhbc.com/upload/dv/thumbnail/"
+ post.getString("moviePhoto")
+ post.getString("moviePhotoExt");
map.setImageUrl(imageUrl);
System.out.println("ldhslhdljh " + imageUrl);
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
Button btnLoadMore = new Button(this);
btnLoadMore.setText("Load More");
// Adding Load More button to lisview at bottom
listView.addFooterView(btnLoadMore);
// Getting adapter
adapter = new CustomAdapter1(this, arraylist);
listView.setAdapter(adapter);
/**
* Listening to Load More button click event
* */
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Starting a new async task
i += 1;
new DownloadJSON().execute();
}
});
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(Newjava.this);
// Set progressdialog title
mProgressDialog.setTitle("APP Name");
mProgressDialog.setIcon(R.drawable.ic_launcher);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
arraylist = new ArrayList<FeedAddress>();
// Retrive JSON Objects from the given website URL in
// JSONfunctions.class
String URL = "http://zvzvs.vczx.com/api/v/page"
+ i;
System.out.println("new url " + URL);
jsonobject = JSONfunctions.getJSONfromURL(URL);
try {
// Locate the array name
JSONObject jsonObject1 = jsonobject
.getJSONObject("fvvzx");
jsonarray = jsonObject1.getJSONArray("allmovies");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject post = (JSONObject) jsonarray.getJSONObject(i);
FeedAddress map = new FeedAddress();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.setMovieName(post.getString("movieName"));
// map.setName(post.getString("movieActors"));
map.setMovieId(post.getString("movieId"));
String imageUrl = "http://www.vsv.com/upload/vc/thumbnail/"
+ post.getString("moviePhoto")
+ post.getString("moviePhotoExt");
map.setImageUrl(imageUrl);
System.out.println("ldhslhdljh " + imageUrl);
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
int currentPosition = listView.getFirstVisiblePosition();
// Appending new data to menuItems ArrayList
adapter = new CustomAdapter1(Newjava.this, arraylist);
listView.setAdapter(adapter);
// Setting new scroll position
listView.setSelectionFromTop(currentPosition + 1, 0);
updateList(string);
}
}
public void updateList(final String string) {
// TODO Auto-generated method stub
listView.setVisibility(View.VISIBLE);
// mProgressDialog.dismiss();
listView.setAdapter(new CustomAdapter1(Newjava.this, arraylist));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(),"position[]" ,
// Toast.LENGTH_SHORT).show();
Object o = listView.getItemAtPosition(position);
FeedAddress newsData = (FeedAddress) o;
System.out.println("hgsh " + string);
System.out.println("next " + newsData.getMovieId());
Intent intent = new Intent(Newjava.this,
SingleMenuItemActivity.class);
intent.putExtra("feed", newsData.getMovieId());
intent.putExtra("actor", newsData.getName());
startActivity(intent);
}
});
}
}
It replaces data because you recreate adapter every time. You should create adapter once and then add to it more data, not recreate it.