Swipte to Refresh keeps adding TextViews - android

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();
}
}
}

Related

how can i display google nearbyplace api images response in listview?

I am using json volley to for getting information from google api.I know how to display text in listview but dont know how to display images because they are in string form i really dont know how to convert that string into image and display in listview . here is my code
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ListView lst_1;
Button btn_one;
String url;
ArrayList<CostumAdapter> contactList;
private ProgressDialog progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
contactList = new ArrayList<>();
lst_1 = (ListView) findViewById(R.id.lst_1);
btn_one = (Button) findViewById(R.id.btn_1);
btn_one.setOnClickListener(this);
}
public void Progress() {
progress = new ProgressDialog(this);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setMessage("Loading");
progress.show();
}
private void jsonfunction() {
Progress();
url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?" +
"location=-33.8670522,151.1957362&" +
"radius=500&" +
"type=restaurant&" +
"key=AIzaSyAG5Fndg4wPzs81FNv5-Ycl7GDlAdqeIaI" +
"&sensor=true";
Log.e("url", url);
final StringRequest stringrequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response", response);
try {
JSONObject jsonobj = new JSONObject(response);
JSONArray jsonArray = jsonobj.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
JSONArray jsonArray2 = object.getJSONArray("photos");
for (int a = 0; a < jsonArray2.length(); a++) {
JSONObject object2 = jsonArray2.getJSONObject(a);
contactList.add(new CostumAdapter(
jsonArray.getJSONObject(i).getString("name"),
object2.getString("photo_reference")
));
}
}
Log.e("response in a", String.valueOf(contactList));
} catch (JSONException e) {
Toast.makeText(MainActivity.this, "error in jason", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
function();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(MainActivity.this, "error in ErrorListener", Toast.LENGTH_LONG).show();
}
});
singalton.getinstance(MainActivity.this).addtorequestque(stringrequest);
}
public void function() {
CustomListAdapter adapter = new CustomListAdapter(getApplicationContext(), R.layout.custumlistview, contactList);
lst_1.setAdapter(adapter);
}
#Override
public void onClick(View v) {
jsonfunction();
}
}

Can not get checkbox text from ListView CheckBox?

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.

how to send all the list view items to the server in android

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();
}

how to refresh the ListView in android when data i appended to ListView

I have made a ListView and made a custom adapter for it,I am calling two Asynctask one for getting all messages from webservice and another is for reply of the message,I want to append the replied message to the ListView. Currently i am not getting it right way. My code is as below:
main.java
import com.epe.yehki.adapter.ChatAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.uc.Header;
import com.epe.yehki.uc.Menu;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.epe.yehki.util.Utils;
import com.example.yehki.R;
public class ChatHistoryActivity extends Activity {
private ProgressDialog pDialog;
JSONArray msgArry;
JSONObject jsonObj;
private ChatAdapter chatContent;
ArrayList<HashMap<String, String>> msgList;
ListView lv;
JSONArray msgs = null;
String pro_id, pro_name, pro_img, grup_id, sender_id, cust_id;
TextView tv_switch;
public boolean flag = false;
Header header;
Menu menu;
Intent in;
Button reply;
RelativeLayout rl_reply;
EditText et_reply;
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_chat_history);
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);
reply = (Button) findViewById(R.id.btn_reply);
rl_reply = (RelativeLayout) findViewById(R.id.rl_reply);
rl_reply.setVisibility(View.GONE);
et_reply = (EditText) findViewById(R.id.et_reply);
menu.setSelectedTab(3);
header.title.setText("Conversation");
msgList = new ArrayList<HashMap<String, String>>();
pro_id = getIntent().getStringExtra(Const.TAG_PRODUCT_ID);
sender_id = getIntent().getStringExtra(Const.TAG_CUSTOMER_ID);
grup_id = getIntent().getStringExtra(Const.TAG_GROUP_ID);
cust_id = Pref.getValue(ChatHistoryActivity.this, Const.PREF_CUSTOMER_ID, "");
/* new GetChatHistory().execute(); */
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
rl_reply.setVisibility(View.VISIBLE);
}
});
// message reply ...!!Chat api(conversation)
reply.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new DoReply().execute();
// new GetChatHistory().execute();
}
});
}
#Override
protected void onResume() {
super.onResume();
new GetChatHistory().execute();
}
private class GetChatHistory extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ChatHistoryActivity.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_CHAT_HISTORY;
url = "?customer_id=" + cust_id + "&group_id=" + grup_id + "&sender_id=" + sender_id + "&product_id=" + pro_id;
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 msg_body = c.getString(Const.TAG_MESSAGE_BODY);
HashMap<String, String> message = new HashMap<String, String>();
message.put(Const.TAG_CUSTOMER_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_MESSAGE_BODY, msg_body);
msgList.add(message);
}
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Utils.showCustomeAlertValidation(ChatHistoryActivity.this, "No messgaes found", "yehki", "Ok");
msgList.clear();
}
});
}
} 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 != null)
pDialog.dismiss();
System.out.println("::::::::::::inside post:::::::::::");
chatContent = new ChatAdapter(ChatHistoryActivity.this, msgList);
chatContent.notifyDataSetChanged();
lv.setAdapter(chatContent);
}
}
/*
* GET CONVERSATION LIST.........REPLY
*/
private class DoReply extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ChatHistoryActivity.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_MESSAGE_REPLY;
url = "?customer_id=" + cust_id + "&group_id=" + grup_id + "&receiver_id=" + sender_id + "&product_id=" + pro_id + "&message=" + et_reply.getText().toString().trim();
url = url.replace(" ", "%20");
url = query + url;
System.out.println(":::::::::::::My MESSGES URL::::::::::::::" + url);
System.out.println(":::::::::::::::get chat history called:::::::::::::;;");
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.getString("status").equals("sucess")) {
// et_reply.setText("");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ChatHistoryActivity.this, "Message has been sent", Toast.LENGTH_SHORT).show();
}
});
} else {
// et_reply.setText("");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ChatHistoryActivity.this, "Message has not been sent", Toast.LENGTH_SHORT).show();
}
});
}
} 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);
System.out.println("::::::::::::inside post:::::::::::");
// Dismiss the progress dialog
if (pDialog != null)
pDialog.dismiss();
chatContent = new ChatAdapter(ChatHistoryActivity.this, msgList);
chatContent.notifyDataSetChanged();
lv.setAdapter(chatContent);
new GetChatHistory().execute();
}
}
}

old data in the ListView remains there when i bind new values to ListView in android

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);

Categories

Resources