I have used json with my Listview in fragment but it take time because i have 190 object so i want it to show only 15 items of Json and will so 15 more if the user scroll to the end. My json file i got from dropbox the size is 2,3MB. Can any tell me a good suggestion ? Thank in advance.
Here are the code.
public class UniversityFragment extends Fragment implements OnScrollListener{
ListView lv;
private ProgressDialog pDialog;
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_NAME = "name";
private static final String TAG_ADDRESS = "address";
private static final String TAG_CityProvince = "city/province";
private static final String TAG_Country = "country";
private static final String TAG_PHONE_OFFICE = "officephone";
private static final String TAG_Fax = "fax";
private static final String TAG_EMAIL = "email";
private static final String TAG_Site = "site";
private static final String TAG_image = "image";
int textlength = 0;
// contacts JSONArray
JSONArray contacts = null;
JSONObject jsonobject;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
// Search EditText
EditText inputSearch;
public UniversityFragment() {
}
#SuppressLint("CutPasteId")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_university,
container, false);
// Execute DownloadJSON AsyncTask
contactList = new ArrayList<HashMap<String, String>>();
lv = (ListView) rootView.findViewById(R.id.listView1);
inputSearch = (EditText) rootView.findViewById(R.id.inputSearch);
lv.setTextFilterEnabled(true);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int start, int before,
int count) {
// TODO Auto-generated method stub
// When user changed the Text
// UniversityFragment.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence cs, int start,
int count, int after) {
// TODO Auto-generated method stub
try {
// ((Filterable)
// UniversityFragment.this.contacts).getFilter().filter(cs);
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getActivity(), "" + e, Toast.LENGTH_SHORT)
.show();
}
// lv.setTextFilterEnabled(true);
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "Clicked" + position,
Toast.LENGTH_LONG).show();
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cp = ((TextView) view.findViewById(R.id.CPt)).getText()
.toString();
String country = ((TextView) view.findViewById(R.id.countryt))
.getText().toString();
String fax = ((TextView) view.findViewById(R.id.faxt))
.getText().toString();
String site = ((TextView) view.findViewById(R.id.sitet))
.getText().toString();
String email = ((TextView) view.findViewById(R.id.emailt))
.getText().toString();
String phone = ((TextView) view.findViewById(R.id.phonet))
.getText().toString();
String address = ((TextView) view.findViewById(R.id.addresst))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getActivity(), SingleListItem.class);
in.putExtra("email", email);
in.putExtra("city/province", cp);
in.putExtra("country", country);
in.putExtra("fax", fax);
in.putExtra("site", site);
in.putExtra("name", name);
in.putExtra("officephone", phone);
in.putExtra("address", address);enter code here
startActivity(in);
}
});
lv.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
if (firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0) {
}
}
});
// Calling async task to get json
new GetContacts().execute();
return rootView;
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setTitle("Loading");
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Create an array
contactList = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
String url = "https://dl.dropbox.com........";
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
enter code here
// 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 name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADDRESS);
String country = c.getString(TAG_Country);
String cityprovince = c.getString(TAG_CityProvince);
String officephone = c.getString(TAG_PHONE_OFFICE);
String fax = c.getString(TAG_Fax);
String email = c.getString(TAG_EMAIL);
String site = c.getString(TAG_Site);
// // Phone node is JSON Object
// JSONObject phone = c.getJSONObject(TAG_PHONE);
// String home = phone.getString(TAG_PHONE_HOME);
// 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_ADDRESS, address);
contact.put(TAG_CityProvince, cityprovince);
contact.put(TAG_Country, country);
contact.put(TAG_PHONE_OFFICE, officephone);
contact.put(TAG_EMAIL, email);
contact.put(TAG_Site, site);
contact.put(TAG_Fax, fax);
// 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) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
Toast.makeText(getActivity(), "Thank for your patience", Toast.LENGTH_LONG).show();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(getActivity(), contactList,
R.layout.listsingleitem, new String[] { TAG_NAME,
TAG_ADDRESS, TAG_CityProvince, TAG_Country,
TAG_PHONE_OFFICE, TAG_Fax, TAG_EMAIL, TAG_Site },
new int[] { R.id.name, R.id.addresst, R.id.CPt,
R.id.countryt, R.id.phonet, R.id.faxt, R.id.emailt,
R.id.sitet });
adapter.notify();
//adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
}
}
You need to implement an endless adapter (custom listview adapter) to support loading and displaying concurrently.
See this tutorial: http://www.survivingwithandroid.com/2013/10/android-listview-endless-adapter.html
Related
I have a JSON data from YouTube. I want to show data in LIST VIEW. But when i run my code I get a blank page. But I have the respond of YouTube DATA API. How can I solve it?
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "https://www.googleapis.com/youtube/v3/search?part=snippet&maxResult=30&q=natok+bangla+mosharrof+karim&key=AIzaSyCR40QlsuX0aFfBV-wEPDsH_jxna1tDFRA";
private static final String TAG_ITEMS = "items";
private static final String TAG_ID = "id";
private static final String TAG_ID_VIDEOID = "vid";
private static final String TAG_TITLE = "title";
private static final String TAG_DESCRIPTION = "description";
private static final String YouTubeThumbnail = "https://i.ytimg.com/vi/hlaX2OZ_kDg/default.jpg";
private static final String TAG_CHANNELTITLE = "channelTitle";
JSONArray items = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String vid = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String title = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_ID_VIDEOID, vid);
in.putExtra(TAG_TITLE, title);
in.putExtra(TAG_DESCRIPTION, description);
startActivity(in);
}
});
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Boolean 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);
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String,String>>();
int count = 0;
try {
JSONObject js = new JSONObject(jsonStr);
JSONArray jsItem = js.getJSONArray("items");
for (int i = 0; i < jsItem.length(); i++) {
JSONObject item = jsItem.getJSONObject(i);
JSONObject vid =item.getJSONObject("id");
String videoId = getStringResult(vid.toString(), "videoId");
if (!videoId.equalsIgnoreCase(""))
{
JSONObject snippet =item.getJSONObject("snippet");
String title = sh.getStringResult(snippet.toString(), "title");
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", title);
map.put("vid", videoId);
map.put ("img","http://img.youtube.com/vi/" + videoId + "/hqdefault.jpg");
map.put ("id",++count+"");
dataList.add(map);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, dataList,R.layout.list_item, new String[] { TAG_TITLE, TAG_DESCRIPTION,
TAG_CHANNELTITLE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
public String getStringResult(String data, String node) {
try {
JSONObject js = new JSONObject(data);
return js.getString(node);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
Use notifyDataSetChanged(). This notifies a change in data and updated the list view. LINK
Here are the changes that would help:
public class MainActivity extends ListActivity {
...
ListAdapter adapter = null;
#Override
public void onCreate(Bundle savedInstanceState) {
...
ListView lv = getListView();
adapter = new SimpleAdapter(
MainActivity.this, dataList,R.layout.list_item, new String[] { TAG_TITLE, TAG_DESCRIPTION,
TAG_CHANNELTITLE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
lv.setListAdapter(adapter);
...
}
private class GetContacts extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
...
}
#Override
protected Boolean doInBackground(Void... arg0) {
...
}
#Override
protected void onPostExecute(Boolean result) {
if(adapter ! = null) {
adapter.notifyDataSetChanged();
}
}
public String getStringResult(String data, String node) {
...
}
Explanation:
ListAdapter is the bridge between a ListView and the data that backs the list.
Whenever the data is changed, adapter is responsible to notify about the changed data and consequently the view gets updated with the new data. This is achieved by notifyDataSetChanged().
For some more details, please go through this link.
So I'm stuck on this... I need to display images in a listview which gets its data from a json file.
I've already setup the connection, parsed the json file and displayed what i need. But somehow I can't find much information about how to turn a string (which has the URL) into an image in a listview.
The string which has the url is called "ImageLink"
Below is my MainActivity.
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get game info JSON
private static String url = "https://dl.dropboxusercontent.com/u/38379784/Upcoming%20Games/DataForUPG.js";
// JSON Node names
private static final String TAG_Games = "games";
private static final String TAG_Title = "Title";
private static final String TAG_Description = "Description";
private static final String TAG_Release = "Release";
private static final String TAG_ImageLink = "ImageLink";
// Gameinfo JSONArray
JSONArray games = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> GamesList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GamesList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String Title = ((TextView) view.findViewById(R.id.Title))
.getText().toString();
String Description = ((TextView) view.findViewById(R.id.Description))
.getText().toString();
String Release = ((TextView) view.findViewById(R.id.Release))
.getText().toString();
String ImageLink = ((TextView) view.findViewById(R.id.ImageLink_label))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleListItem.class);
in.putExtra(TAG_Title, Title);
in.putExtra(TAG_Description, Description);
in.putExtra(TAG_Release, Release);
in.putExtra(TAG_ImageLink, ImageLink);
startActivity(in);
}
});
// Calling async task to get json
new GetGames().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetGames extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading Data...");
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
games = jsonObj.getJSONArray(TAG_Games);
// looping through All games
for (int i = 0; i < games.length(); i++) {
JSONObject c = games.getJSONObject(i);
String Title = c.getString(TAG_Title);
String Description = c.getString(TAG_Description);
String Release = c.getString(TAG_Release);
String ImageLink = c.getString(TAG_ImageLink);
// tmp hashmap for single game
HashMap<String, String> games = new HashMap<String, String>();
// adding each child node to HashMap key => value
games.put(TAG_Title, Title);
games.put(TAG_Description, Description);
games.put(TAG_Release, Release);
games.put(TAG_ImageLink, ImageLink);
// adding contact to gameinfo list
GamesList.add(games);
}
} 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(
MainActivity.this, GamesList,
R.layout.list_item, new String[] { TAG_Title, TAG_Release,
TAG_Description, TAG_ImageLink }, new int[] { R.id.Title,
R.id.Release, R.id.Description, R.id.ImageLink_label });
setListAdapter(adapter);
}
}
}
I would appreciate any help
Well, you could probably create another async task to handle downloading the image like this:
private class DownloadImg extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
String TAG_ImageLink = params[0];
Bitmap bm = null;
try {
InputStream in = new java.net.URL(TAG_ImageLink).openStream();
bm = BitmapFactory.decodeStream(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm;
}
#Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
or you could use a 3rd party image loading library like picasso or volley's ImageRequest
I successfully get json data and already show it in a listview. Now my requirement is to set data one entry at a time in list on click of add button.
Here is my main activity in which data is set to listview
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_OWNER = "owner";
private static final String TAG_ID = "id";
private static final String TAG_LOGIN = "login";
// contacts JSONArray
JSONArray data = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id1) {
// TODO Auto-generated method stub
// getting values from selected ListItem
String login = ((TextView) view.findViewById(R.id.login))
.getText().toString();
String id = ((TextView) view.findViewById(R.id.id))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_ID, id);
in.putExtra(TAG_LOGIN, login);
startActivity(in);
}
});
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
// TODO Auto-generated method stub
Log.v("long clicked","pos: " + pos);
removeItemFromList(pos);
return true;
}
private void removeItemFromList(int pos) {
// TODO Auto-generated method stub
final int deletePosition = pos;
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Delete");
alert.setMessage("Do you want delete this item?");
alert.setPositiveButton("YES", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TOD Auto-generated method stub
// main code on after clicking yes
dataList.remove(deletePosition);
setListAdapter(getListAdapter());
}
});
alert.setNegativeButton("CANCEL", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
alert.show();
}
});
// Calling async task to get json
new GetData().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetData 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();
}
#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 {
JSONArray json = new JSONArray(jsonStr);
Log.d("in json object block", jsonStr);
// looping through All Contacts
for(int i=0;i<json.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = json.getJSONObject(i);
// adding contact to contact list
JSONObject owner = e.getJSONObject("owner");
// map.put("id", String.valueOf(i));
map.put("login", "Login is:" + owner.getString("login"));
map.put("id", "ID is: " + owner.getString("id"));
// map.put("owner", "OWNER is" + e.getString("") );
dataList.add(map);
}
} 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(
MainActivity.this, dataList,
R.layout.list_item, new String[] { TAG_OWNER, TAG_LOGIN,
TAG_ID }, new int[] { R.id.owner,
R.id.login, R.id.id });
setListAdapter(adapter);
}
}
}
create a button on main layout. Implement onclicklistener for the button and call populateListView() inside the onlick method.
Creat a new list. When you click a button add an item to a new list. call notifydatasetchanged(). When you click a button check whether the item is already added in the new list or not. Use newly created list in your adapter so that every time new item will be added.
Thanks
I was looking for a simple example on parsing a JSON file, using the loopj AsyncHttpClient. But so far I could not find any useful information. :(
Simple JSON file to parse:
{
"contact": [
{
"id": "10",
"name": "Tom",
"email": "tom#gmail.com"
}
}
]
}
I would be grateful for any suggestion.
Thanks!!
You need to get the json first. I assume you have done that
{ // json object node
"contact": [ //json array contact
{ // json object node
To parse
JSONObject jb = new JSONObject("your json");
JSONArray con = jb.getJSONArray("contact");
JSONObject contact = (JSONObject) con.getJSONObject(0);
String id = contact.getString("id");
String name = contact.getString("name");
String id = contact.getString("id");
public class MainActivity extends Activity {
private ProgressDialog pdialog;
private static String url = "http://highspecificationservers.com/apk/webservice.php";
private static final String TAG_STUDENT = "student";
private static final String TAG_FNAME = "fname";
private static final String TAG_EMAIL = "email";
private static final String TAG_MOBILE = "mobile";
JSONArray student = null;
ArrayList<HashMap<String, String>> studentlist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
studentlist = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String fname = ((TextView) view.findViewById(R.id.fname))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_FNAME, fname);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_MOBILE, description);
startActivity(in);
}
});
new GetStudent().execute();
}
private class GetStudent extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pdialog = new ProgressDialog(MainActivity.this);
pdialog.setMessage("please wait");
pdialog.setCancelable(false);
pdialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
ServiceHandler sh = new ServiceHandler();
String jString = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response:", "> " + jString);
if (jString != null) {
try {
JSONObject Jsonobj = new JSONObject(jString);
student = Jsonobj.getJSONArray(TAG_STUDENT);
for (int i = 0; i < student.length(); i++) {
JSONObject c = student.getJSONObject(i);
String fname = c.getString(TAG_FNAME);
String email = c.getString(TAG_EMAIL);
String mobile = c.getString(TAG_MOBILE);
HashMap<String, String> student = new HashMap<String, String>();
student.put(TAG_FNAME, fname);
student.put(TAG_EMAIL, email);
student.put(TAG_MOBILE, mobile);
studentlist.add(student);
}
} 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) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (pdialog.isShowing())
pdialog.dismiss();
ListAdapter adapter = new SimpleAdapter(MainActivity.this,
studentlist, R.layout.list_item, new String[] { TAG_FNAME,
TAG_EMAIL, TAG_MOBILE }, new int[] { R.id.fname,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
}
}
private ListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
Go with this...
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
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 id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
// 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");
}
I have a API which responds in JSON. When I clicked a button I am comfortably parse the JSON and implement it in the listview. The problem is When I go back to the previous activity and clicked the button once again I am getting the values repeat. i.e. previous values also, even I had called finish(); in on pause state of the listview activity. Following is my code.
Invoice Class
public class Invoice extends Activity{
public static ArrayList<HashMap<String, String>> ModuleName = new ArrayList<HashMap<String, String>>();
boolean tree = true;
ArrayList<String> KEY = new ArrayList<String>();
ListView mListView;
ProgressBar mProgress;
JSONObject json;
JSONArray Module_list = null;
Invoice_adapter adapter;
public static String KEY_SUCCESS = "success";
public static String KEY_ERROR = "error";
public static String KEY_ERROR_MSG = "error_msg";
public static String KEY_MODULELIST_MODULEHEADER = "moduleHeader";
public static String KEY_MODULELIST_MODULELIST = "moduleList";
public static String KEY_MODULELIST_DATAFOUND = "datafound";
public static String KEY_INVOICE_INVOICENO = "";
public static String KEY_INVOICE_SUBJECT = "";
public static String KEY_INVOICE_SALESORDER = "";
public static String KEY_INVOICE_STATUS = "";
public static String KEY_INVOICE_TOTAL = "";
public static String KEY_INVOICE_ASSIGNEDTO = "";
public static String KEY_INVOICE_RECORDID = "";
public static String KEY_INVOICE_ACTION = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_module_data);
mListView = (ListView) findViewById(R.id.module_list);
mProgress = (ProgressBar) findViewById(R.id.progressBar1);
try {
json = new ParseDATA().execute().get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
String data_found = json.getString(KEY_MODULELIST_DATAFOUND);
if (data_found.equals("Data Found!")){
JSONArray array = json.getJSONArray(KEY_MODULELIST_MODULELIST);
int count1 = array.length();
String Count1 = Integer.toString(count1);
Log.d("Count_array", Count1);
JSONObject keyarray = array.getJSONObject(0);
#SuppressWarnings("rawtypes")
Iterator temp = keyarray.keys();
while (temp.hasNext()) {
String curentkey = (String) temp.next();
KEY.add(curentkey);
}
Collections.sort(KEY, String.CASE_INSENSITIVE_ORDER);
KEY_INVOICE_ACTION = KEY.get(0);
KEY_INVOICE_ASSIGNEDTO = KEY.get(1);
KEY_INVOICE_INVOICENO = KEY.get(2);
KEY_INVOICE_RECORDID = KEY.get(3);
KEY_INVOICE_SALESORDER = KEY.get(4);
KEY_INVOICE_STATUS = KEY.get(5);
KEY_INVOICE_SUBJECT = KEY.get(6);
KEY_INVOICE_TOTAL = KEY.get(7);
Log.d("Parsing Json class", " ---- KEYS---- " + KEY);
Module_list = json.getJSONArray(KEY_MODULELIST_MODULELIST);
int count = Module_list.length();
String Count = Integer.toString(count);
Log.d("Count_Module_LIST", Count);
// looping through All Contacts
for(int i = 0; i < Module_list.length(); i++){
JSONObject c = Module_list.getJSONObject(i);
// Storing each json item in variable
String mAction = c.getString(KEY_INVOICE_ACTION);
String mAssignedTo = c.getString(KEY_INVOICE_ASSIGNEDTO);
String mInvoice = c.getString(KEY_INVOICE_INVOICENO);
String mRecordid = c.getString(KEY_INVOICE_RECORDID);
String mSalesorder = c.getString(KEY_INVOICE_SALESORDER);
String mStatus = c.getString(KEY_INVOICE_STATUS);
String mSubject = c.getString(KEY_INVOICE_SUBJECT);
String mTotal = c.getString(KEY_INVOICE_TOTAL);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_INVOICE_ACTION, mAction);
map.put(KEY_INVOICE_ASSIGNEDTO, mAssignedTo);
map.put(KEY_INVOICE_INVOICENO, mInvoice);
map.put(KEY_INVOICE_RECORDID, mRecordid);
map.put(KEY_INVOICE_SALESORDER, mSalesorder);
map.put(KEY_INVOICE_STATUS, mStatus);
map.put(KEY_INVOICE_SUBJECT, mSubject);
map.put(KEY_INVOICE_TOTAL, mTotal);
// adding HashList to ArrayList
ModuleName.add(map);
}
}else
{
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
return;
}
}
mProgress.setVisibility(View.INVISIBLE);
adapter = new Invoice_adapter(Invoice.this, ModuleName);
mListView.setAdapter(adapter);
mListView.setVisibility(View.VISIBLE);
//mListView.invalidateViews();
}
else
{
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ERROR, "Error");
ModuleName.add(map);
//JSONObject json_user = json.getJSONObject("user");
//error_message = json_user.getString(KEY_ERROR_MSG);
}
}catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Something went wrong.Please try again.!!", Toast.LENGTH_LONG).show();
}
}
class ParseDATA extends AsyncTask<Void, String,JSONObject >
{
ProgressDialog dialog = new ProgressDialog(Invoice.this);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setTitle("Loading");
dialog.setIndeterminate(true);
dialog.setMessage("Please wait");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected JSONObject doInBackground(
Void... params) {
// TODO Auto-generated method stub
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.getModuleList("1", "20", "Invoice");
return json;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
dialog.dismiss();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Toast.makeText(getApplicationContext(), "PAUSE STATE", Toast.LENGTH_LONG).show();
finish();
}}
Adapter class
public class Invoice_adapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public Invoice_adapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.activity_module_data_detail, null);
TextView title = (TextView)vi.findViewById(R.id.textView1); // category title name
//ImageView moduleImage = (ImageView) vi.findViewById(R.id.recipe_image);
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
Log.i("list", ""+data.get(position));
//Log.i("list", data);
String ff = song.get(Invoice.KEY_INVOICE_SUBJECT);
title.setText(ff);
//moduleImage.setImageResource(mModuleImages[position]);
return vi;
}}
Please Help.. !! I dnt know what Is I am doing wrong.
Thanks in advance.
The problem is with the "static" key word for the ArrayList
public static ArrayList<HashMap<String, String>> ModuleName = new ArrayList<HashMap<String, String>>();
static variables are initialized only when the class is loaded, that means the value will be persisted till the end of the application process.
Either remove static keyword for array list or clear the array list before you load new data.
ModuleName.clear();