Duplicate values doing Asynctask in Listview - android

I have an AsyncTask that connects to a service and with an adapter set the result in a ListView. In the action bar I want to put a button to do the refresh action but the problem is that when I click this button and I call to the service it duplicates the results in the list view.
I have tried:
ListView myList=(ListView)findViewById(R.id.list);
myList.setAdapter(null);
if ((new Utils(this)).isConnected()){
new MyTask().execute();
}
My AsyncTask code:
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MyActivity.this);
pDialog.setMessage("searching...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url+id, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonObj = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String nick = c.getString("nick");
String minuto = c.getString("minuto");
String fecha = c.getString("fecha");
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put("nick", nick);
contact.put("minuto", minuto);
contact.put("fecha", fecha);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} 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
* */
ListAdapter adapter = new SimpleAdapter(
DetallePelicula.this, contactList,
R.layout.list_rowopiniones, new String[] { "nick", "minuto",
"fecha" }, new int[] { R.id.title,
R.id.minuto, R.id.fecha });
ListView myList=(ListView)findViewById(R.id.list);
myList.setAdapter(adapter);
}
}
Somebody can help me? thanks

In your doInBackground, you are adding the new data to an already existing list. This means that, as you've mentioned, the data will duplicate.
Just add contactList.clear() to your onPreExecute method:
#Override
protected void onPreExecute() {
super.onPreExecute();
contactList.clear(); // Add this line
// Showing progress dialog
pDialog = new ProgressDialog(MyActivity.this);
pDialog.setMessage("searching...");
pDialog.setCancelable(false);
pDialog.show();
}

Related

saving json data into sqlite

Hi i need to save json data in sqlite. But iam getting following error.
Can't create handler inside thread that has not called
Looper.prepare().
This is my code. It is shwoing database open/database created...
/**
* Async task class to get json by making HTTP call
* */
private class GetDetails extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#SuppressLint("NewApi")
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Create an array to populate the spinner
branchlist = new ArrayList<String>();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
// System.out.println("response"+jsonStr);
if (jsonStr != null) {
try {
// jsonString is a string variable that holds the JSON
JSONArray itemArray=new JSONArray(jsonStr);
for (int i = 0; i < itemArray.length(); i++) {
value=itemArray.getString(i);
Log.e("json", i+"="+value);
dbhelper=new DataBaseHepler(getApplicationContext());
sqLiteDatabase=dbhelper.getWritableDatabase();
dbhelper.addinnformation(value,sqLiteDatabase);
Toast.makeText(getBaseContext(),"Data saved",Toast.LENGTH_LONG).show();
dbhelper.close();
branchlist.add(itemArray.getString(i));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} 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
* */
ArrayAdapter<String> stringadapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
branchlist);
spinner1.setAdapter(stringadapter);
// spinner1
// .setAdapter(new ArrayAdapter<String>(MainActivity.this,
// android.R.layout.simple_spinner_dropdown_item,
// branchlist));
}
}
This error is due to Toast inside doInBackground(Void... arg0) method:
Toast.makeText(getBaseContext(),"Data saved",Toast.LENGTH_LONG).show();
Clearly the Android OS wont let threads other than the main thread change UI elements. Follow this link for more details on this: https://dzone.com/articles/android-%E2%80%93-multithreading-ui

Listview with hashmap

I want show server json responce in listview.i get all value in hashmap i am confused about how to set that data in custom listview.please help me and show me the code
class viewticket extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pdialog = new ProgressDialog(UserLogedIn.this);
pdialog.setMessage("Loading....");
pdialog.setIndeterminate(false);
pdialog.setCancelable(false);
pdialog.show();
}
#Override
protected Void doInBackground(Void... params) {
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("userid", u_id));
JSONObject jsonArray = jpar.makeHttpRequest(URLMyTicket, "POST", param);
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(URLMyTicket, ServiceHandler.POST, param);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
contacts = new JSONArray(jsonStr);
int a=contacts.length();
Log.v(TAG,""+a);
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_PROB);
String email = c.getString(TAG_DESC);
HashMap<String, String> contact = new HashMap<String, String>();
contact.put(TAG_ID, id);
contact.put(TAG_PROB, name);
contact.put(TAG_DESC, email);
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} 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();
//What code to write
}
}
what should i write in onpost method and custom list class
Ticket_list.java
public class Ticket_list extends ArrayAdapter< String> {
HashMap<String, String> objects;
public Ticket_list(Context context, int resource, HashMap<String,String> objects) {
super(???? //what );
}
//What
}
Please help me to write onpost method code and code of Ticket_list
I highly recommend you to use RecyclerView instead of ListView and use Retrofit to send request and get the response as json.Take a look at these documents For RecyclerView.

Unable to show image in listview by imageloader class

I have used view in my application. I wants to show image in my list by using POST method. I got the image url by POST method but unable to show it in list. some part of my code snippet is here....
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Home1.this);
pDialog.setMessage("Please wait....");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler1 sh = new ServiceHandler1(apikey, latitude, longitude);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler1.POST);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String username = c.getString(TAG_USERNAME);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String contact_number = c.getString(TAG_CONTACT_NUMBER);
String postalcode = c.getString(TAG_POSTAL_CODE);
String image = c.getString(TAG_IMAGE);
Log.v("as.",image);
ImageLoader imageLoader = new ImageLoader(getApplicationContext());
ImageView Profileimage = (ImageView) findViewById(R.id.logo);
imageLoader.DisplayImage(image, Profileimage);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_NAME, name);
contact.put(TAG_IMAGE, image);
contact.put(TAG_EMAIL, email);
// contact.put(TAG_ADDRESS, address);
contact.put(TAG_ADDRESS, address);
// adding contact to contact list
contact.put(TAG_USERNAME, username);
contact.put(TAG_POSTAL_CODE, postalcode);
contact.put(TAG_CONTACT_NUMBER, contact_number);
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} 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();
ListAdapter adapter = new SimpleAdapter(
Home1.this, contactList,
R.layout.list_item1, new String[]{TAG_EMAIL, TAG_USERNAME, TAG_ADDRESS, TAG_POSTAL_CODE, TAG_CONTACT_NUMBER,
}, new int[]{
R.id.company, R.id.description, R.id.address, R.id.operating_hours, R.id.contact});
setListAdapter(adapter);
}
}
I have used image loader class for converting the image url... guys please help me
please suggest me how can I parse image in postExecute()...
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
Home1.this, contactList,
R.layout.list_item1, new String[]{TAG_EMAIL, TAG_USERNAME, TAG_ADDRESS, TAG_POSTAL_CODE, TAG_CONTACT_NUMBER,
}, new int[]{
R.id.company, R.id.description, R.id.address, R.id.operating_hours, R.id.contact});
ImageLoader imageLoader = new ImageLoader(getApplicationContext());
ImageView Profileimage = (ImageView) findViewById(R.id.logo);
imageLoader.DisplayImage(TAG_IMAGE, Profileimage);
setListAdapter(adapter);
}
}
You need to create custom Listview adapter to achieve this task. Please check loading-image-asynchronously-in-android-listview link to create one. In your post execute method you have to create object of adapter and then pass your contactList array list which consist images URL.
In the link you will get full code of showing images in listview with code of downloading image using Imageloader library.
Let me know if it helps.

Json Exception value going of type java .lang.string cannot be converted to jsonArray

I wants to get latitudes and longitudes from server,but i got Json Exception
my class is
private class GetContacts extends AsyncTask<Void, Void, Void> {
/*#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress
dialog pDialog = new ProgressDialog(Supervisornew.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}*/
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
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 {
contacts = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String lat = c.getString(TAG_LAT);
String lng = c.getString(TAG_LNG);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_LAT, lat);
contact.put(TAG_LNG, lng);
String latitude=contact.get(0);
String longitude=contact.get(1);
Toast.makeText(Supervisornew.this, latitude, Toast.LENGTH_SHORT).show();
Toast.makeText(Supervisornew.this, longitude, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Supervisornew.this,
Mapnew.class);
intent.putExtra("hashmap", contact);
startActivity(intent);
// adding contact to contact list
contactList.add(contact);
Intent inten = new Intent(Supervisornew.this,
Mapnew.class);
inten.putExtra("arraylist", contactList);
startActivity(inten);
// startActivityForResult(intent, 500);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("DY ", "see this");
}
} 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();*/
can anybody tells me hoe to get data from hashmap and show it on map.
How can we pass hashmap tp another activity and get data here

can't create multiple choice listview

This is my code i can't create the multiple choice mode listview.
Data is fetched by jason and set in the listview.
I want to multiple selection choice mode on the list view
public class ExamView extends ListActivity{
private ProgressDialog pDialog;
Intent activity;
// URL to get contacts JSON
// JSON Node names
private static final String TAG_USERMST = "products";
private static final String TAG_QID = "que_id";
private static final String TAG_QUE = "question";
private static final String TAG_QANS = "ans";
JSONArray products = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.user_activity_lv);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ExamView.this);
pDialog.setMessage("Exam Paper is downloading...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
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
products = jsonObj.getJSONArray(TAG_USERMST);
// looping through All Contacts
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String queid = c.getString(TAG_QID);
String que = c.getString(TAG_QUE);
String queans = c.getString(TAG_QANS);
// tmp hashmap for single contact
HashMap<String, String> product = new HashMap<String, String>();
// adding each child node to HashMap key => value
product.put(TAG_QID,queid);
product.put(TAG_QUE, que);
product.put(TAG_QANS, queans);
// adding contact to contact list
contactList.add(product);
}
} catch (JSONException e) {
e.printStackTrace();
}
} 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
* */
ListAdapter adapter = new SimpleAdapter(
ExamView.this, contactList,
R.layout.user_list_item_lbl, new String[] { TAG_QID, TAG_QUE,
TAG_QANS }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
setListAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_multiple_choice, array_sort));
Use this code its working for me.
Here array_sort is an arraylist i.e. list of all the items to be displayed.
Multiple items can be selected with this.

Categories

Resources