how to make the asynctask run in background even the activity destroyed? - android

i'm making some asynctask method, but i'm not really sure how to make it keep running on the background when the app was closed. Some said it could be used with Service or put the code in doinbackground but i'm not sure how to implement it. Btw, Here's my code:
private class DataBinatangOperation extends AsyncTask<String, Void, String> {
MainMenuAdapter adapter = new MainMenuAdapter(MainMenu.this,
listBinatang);
#Override
protected String doInBackground(String... params) {
JSONArray json;
try {
result = JSONParser.getPage(url);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
//updateList();
tv.setVisibility(View.GONE);
//mSwipeRefreshLayout.setRefreshing(false);
try {
System.out.print("result = " + result);
json = new JSONObject(result);
progress.dismiss();
JSONArray objek = json.getJSONArray("data_vaksinasi_menu");
for (int i = 0; i < objek.length(); i++) {
JSONObject jo = objek.getJSONObject(i);
ID_USER = jo.getString(id_user);
ID_BINATANG = jo.getString(id_binatang);
NAMA_BINATANG = jo.getString(nama_binatang);
JENIS_BINATANG = jo.getString(jenis_binatang);
FOTO_BINATANG = jo.getString(foto_binatang);
TANGGAL_VAKSIN = jo.getString(tanggal_vaksin);
NAMA_VAKSIN = jo.getString(nama_vaksin);
RAS_BINATANG = jo.getString(ras_binatang);
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
Calendar waktuSekarang = Calendar.getInstance();
Date date1 = waktuSekarang.getTime();
Date date2 = new Date();
date2 = formatter.parse(TANGGAL_VAKSIN);
/*waktuVaksin.setTime(date2);
DateMidnight start = new DateMidnight(tanggalSkrg);
DateMidnight vaksin = new DateMidnight(TANGGAL_VAKSIN);*/
if (pref.getPreferences("ID").equals(ID_USER)) {
if (date2.after(date1)) {
int days = Days.daysBetween(new DateTime(date1), new DateTime(date2)).getDays();
if (days > 7 && days <= 30) {
int weeks = days / 7;
sisaWaktu = String.valueOf(weeks) + " minggu";
} else if (days > 30 && days <= 365) {
int months = days / 30;
sisaWaktu = String.valueOf(months) + " bulan";
} else if (days > 365) {
int years = days / 365;
sisaWaktu = String.valueOf(years) + " tahun";
} else {
sisaWaktu = String.valueOf(days) + " hari";
if (days <= 5) {
NH.createSimpleNotification(getActivity(), NAMA_BINATANG, sisaWaktu, ID_BINATANG);
}
}
} else if (date2.before(date1)) {
int days = Days.daysBetween(new DateTime(date2), new DateTime(date1)).getDays();
sisaWaktu = "lewat " + String.valueOf(days) + " hari";
NH.createButtonNotification(getActivity(), NAMA_BINATANG, sisaWaktu, ID_BINATANG);
} else if (date2.equals(date1)) {
sisaWaktu = "sekarang";
NH.createButtonNotification(getActivity(), NAMA_BINATANG, sisaWaktu, ID_BINATANG);
}
}
HashMap<String, String> map = new HashMap<String, String>();
map.put(id_binatang, ID_BINATANG);
map.put(nama_binatang, NAMA_BINATANG);
map.put(jenis_binatang, JENIS_BINATANG);
map.put(foto_binatang, urlgambar+FOTO_BINATANG);
map.put(ras_binatang, RAS_BINATANG);
map.put(tanggal_vaksin, sisaWaktu);
map.put(nama_vaksin, NAMA_VAKSIN);
if (pref.getPreferences("ID").equals(ID_USER)) {
listBinatang.add(map);
}
}
System.out.println("hasil list : " + String.valueOf(listBinatang));
System.out.println("adapter : " + String.valueOf(adapter));
list.setAdapter(adapter);
/*list.setVisibility(View.VISIBLE);*/
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long idx) {
HashMap<String, String> ambilid = new HashMap<String, String>();
ambilid = listBinatang.get(position);
Toast.makeText(getActivity(), "pindah halaman", Toast.LENGTH_SHORT).show();
Intent a = new Intent(getActivity(), MainPetInformation.class);
pref.savePreferences("IDB", ambilid.get(MainMenu.id_binatang));
pref.savePreferences("NAMAB", ambilid.get(MainMenu.nama_binatang));
pref.savePreferences("FOTOB", ambilid.get(MainMenu.foto_binatang));
pref.savePreferences("JENISB", ambilid.get(MainMenu.jenis_binatang));
pref.savePreferences("RASB", ambilid.get(MainMenu.ras_binatang));
startActivity(a);
}
});
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
}
#Override
protected void onPreExecute() {
listBinatang.clear();
adapter.notifyDataSetChanged();
progress = ProgressDialog.show(getActivity(), "Please Wait",
"Loading Data", true);
}
#Override
protected void onProgressUpdate(Void... values) {
}
}

protected abstract Object doInBackground(Object... params)
Is the method from the AsyncTask that performs operations in the background of the main thread (also known as UI thread), which is used to do actions that either are required to be performed off the main thread (networking) or you want to do without preventing a negative user experience (such as a task that would prevent the user from using the app any further until the task has completed).
Here is a succinct and nice tutorial for Services, which is indeed what you are looking for: http://www.vogella.com/tutorials/AndroidServices/article.html. A service can perform operations in the background like an AsyncTask's doInBackground method does, but can do it when the app is in the background as you said, and in intervals if you need it to.
I could go into more depth on this, but that tutorial has all the information you need and I suspect it is what you are looking for.

Related

Obtaining an array of json format question and put them into an array in android studio

The goal here is to retrieve JSON format data from an API, convert the data into an array in android studio. Then to display a random question into a text view and the question will not repeat itself. The question changes everytime a button is clicked. There's something wrong with the logic of how I use my array/parsing the data to the array. I am not sure how to proceed. Any help is appreciated
MY JSON format
{
"error": false,
"message": "Successfully retrieved",
"questions": [
{
"question": "Tell us about yourself?"
},
{
"question": "Tell us about yourself2?"
},
{
"question": "Tell us about yourself3?"
},
{
"question": "Tell us about yourself4?"
},
{
"question": "Tell us about yourself5?"
}
]
}
My code so far ( simplified to this function )
public class MainActivity extends AppCompatActivity {
// create arraylist to store question
List<String> questionList = new ArrayList<>();
// use max to decide the number of question
// use i to find out the number of questions
int i = 10;
int min = 0;
int max = i;
int[] usedInt = new int[max];
//create another array to put all the used integer inside for 0 repeition of question
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textViewQuestions = (TextView) findViewById(R.id.questionView);
usedInt = new int[i];
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
//generate random number, set textview the question, set int to usedint array
textViewQuestions.setText(questionList.get(i1));
usedInt[0] = i1;
//set first question
findViewById(R.id.changeQuestion).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Log.d(TAG,questionList[updateQuestions(usedInt)]);
//final int[] usedIntTemp = usedInt;
getQuestions();
int n = updateQuestions(usedInt);
textViewQuestions.setText(questionList.get(n));
//finish();
}
});
}
}
public int updateQuestions(int usedInteger[]) {
int min = 0;
int max = i;
Random r = new Random();
int i2 = r.nextInt(max - min + 1) + min;
int uInteger[] = usedInteger;
int l = 0;
while (l != max) {
if (i2 == usedInteger[l]) {
l++;
if (l == max) {
Toast.makeText(getApplicationContext(), "No other questions available", Toast.LENGTH_LONG).show();
}
} else {
usedInteger[usedInteger.length + 1] = i2;
return i2;
}
}
return i2;
}
private void getQuestions()
{
class GetQuestions extends AsyncTask<Void, Void, String> {
//private ProgressBar progressBar;
#Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("role_id", "1");
//returing the response
return requestHandler.sendPostRequest(URLs.URL_QUESTIONS, params);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//displaying the progress bar while user registers on the server
//progressBar = (ProgressBar) findViewById(R.id.progressBar);
//progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//hiding the progressbar after completion
//progressBar.setVisibility(View.GONE);
boolean Error1 = false;
try {
//converting response to json object
JSONObject obj = new JSONObject(s);
//HashMap<String, String> questionJson = new HashMap<>();
// success = obj.getBoolean("error");
if (!obj.getBoolean("error")) {
//Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the questions from the response
JSONArray questionsJson = obj.getJSONArray("questions");
//creating a new questions object
for (i = 0; i < questionsJson.length(); i++) {
JSONObject object = questionsJson.getJSONObject(i);
questionList.add(object.getString("question"));
Log.d(TAG,"objcheck");
Log.d(TAG,object.getString("question"));
//q = c.getString("question");
//questionJson.put("question", q);
//questionList.add(questionJson);
}
finish();
//startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else {
Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
GetQuestions gq = new GetQuestions();
gq.execute();
}
Object[] array = new Object[10]; // say 10 objects
int remain = array.length;
Random rnd = new Random();
public Object next () {
if (remain == 0) {
return null;
} else {
int i = rnd.nextInt(remain--);
Object tmp = array[i];
array[i] = array[remain];
array[remain] = tmp;
return tmp;
}
}
This will generate next random question
I tried this, with
getQuestions();
String n = String.valueOf(next());
textViewQuestions.setText(n);
I also populated the array like this
for (i = 0; i < questionsJson.length(); i++) {
JSONObject object = questionsJson.getJSONObject(i);
array[i] = object.getString("question");
questionList.add(object.getString("question"));
Log.d(TAG,object.getString("question"));
}
However, the questions do repeat but will only show a set amount of questions. :( How to make the questions not repeat?

Get too many results

I'm trying to create Favorites class. I search for title I get from the user and adds the video to the Favorites class. But, I always get more than one result. ( I get the maximum results which is 10 ).
How can I get only 1 result for each title?
This is the on create:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites_layout);
getSupportActionBar().setTitle("Favorites");
initializeViews();
extras = getIntent().getExtras();
this.vidTitle = extras.getString("title");
this.vidID = extras.getString("id");
//Checking where to add the new Video
for(int i=0;i<favorites.length;i++){
if(favorites[i]==null){
favorites[i] = vidTitle;
}
break; // Break so it won't add same video to all array
}
AppUtils.showToast("Loading Favorites");
getVideo2();
}
This is the code which gets the 10 results:
public void getVideo(){
AppUtils.showToast("Loading Favorites");
mServiceTask = new ServiceTask(SEARCH_VIDEO);
mServiceTask.setmServerResponseListener(this);
for (int i=0; i<favorites.length;i++) {
if(favorites[i]!=null){
mServiceTask.execute(new Object[]{favorites[i]}); <--- Problem here
break;
}
else{
break;
}
}
}
ServiceTask:
public class ServiceTask extends AsyncTask<Object, Void, Object[]> implements ServiceTaskInterface{
private static final String TAG = ServiceTask.class.getSimpleName();
private ServerResponseListener mServerResponseListener = null;
private int mRequestCode = 0;
public void setmServerResponseListener(ServerResponseListener mServerResponseListener){
this.mServerResponseListener = mServerResponseListener;
}
public ServiceTask(int iReqCode){
mRequestCode = iReqCode;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mServerResponseListener.prepareRequest(mRequestCode);
}
#Override
protected Object[] doInBackground(Object... params) {
if(params == null)
throw new NullPointerException("Parameters to the async task can never be null");
mServerResponseListener.goBackground();
Object[] resultDetails = new Object[2];
resultDetails[0] = mRequestCode;
switch (mRequestCode){
case AppConstants.SEARCH_VIDEO:
try {
resultDetails[1] = loadVideos((String) params[0]);
break;
}catch (Exception e){
AppUtils.showToast("BLABLABLA");}
}
return resultDetails;
}
#Override
protected void onPostExecute(Object[] result) {
super.onPostExecute(result);
mServerResponseListener.completedRequest(result);
}
//Loading the videos, with help of Google's code.
private List<SearchResult> loadVideos(String queryTerm){
try{
YouTube youTube = new YouTube.Builder(transport,jsonFactory,new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest httpRequest) throws IOException {}
}).setApplicationName(YoutubeApplication.appName()).build();
YouTube.Search.List search = youTube.search().list("id,snippet");
search.setKey(AppConstants.KEY);
search.setQ(queryTerm);
//Only including videos
search.setType("video");
search.setFields("items(id/kind,id/videoId,snippet/title,snippet/description,snippet/thumbnails/default/url,snippet/thumbnails/medium/url)");
search.setMaxResults(AppConstants.NUMBER_OF_VIDEOS_RETURNED);
//Call the API to print results
SearchListResponse searchListResponse = search.execute();
List<SearchResult> searchResultList = searchListResponse.getItems();
if(searchResultList != null){
return searchResultList;
}
}catch (GoogleJsonResponseException e){
System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
}catch (IOException e){
System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
}catch (Throwable t){
t.printStackTrace();
}
return null;
}
}
How can I get only 1 result at time but still have place for 10 results ( like 10 different videos) ?
At first, comment your break; lines or your loop is useless. Then collect your not null objects in list and place it in execute method with toArray.
LinkedList<Object> list = new LinkedList<Object>();
for (int i=0; i<favorites.length; i++) {
if(favorites[i]!=null){
//mServiceTask.execute(new Object[]{favorites[i]}); //<--- Problem here
list.add(favorites[i]);
//break;
}
else{
//break;
}
}
mServiceTask.execute(list.toArray());
UPDATE
And about ServiceTask class. In doInBackground you are using only params[0] - the first array element. So there should be:
for (int i=0; i<params.length; i++) {
loadVideos((String) params[i]);
}

OnProgressUpdate are called at once time after end of for cycle

I want to update progress bar using AsyncTask and method onProgressUpdate. I have for cycle in method doInBackground, but progress are called at once time after for cycle is ended.
A tried add log above publishUpdate line and log is called in real time.
#Override
protected String doInBackground(Void... params) {
String message = "Inicialized";
JsonApiParser jsonApiParser = new JsonApiParser(NationalParks.getContext());
callList = getInicializationCallList();
int count = callList.size(), id;
for (int i = 0; i < count; i++) {
String call = callList.get(i);
String[] stringArray = call.split("/");
try {
id = Integer.parseInt(stringArray[stringArray.length - 1]);
} catch (NumberFormatException e) {
id = 0;
}
try {
if (call.contains("info")) {
JSONObject json = Request.getParkInfo(id);
jsonApiParser.insertPark(json);
} else if (call.contains("category-lodging")) {
JSONObject json = Request.getLodgingCategory(id);
jsonApiParser.insertLodgingCategory(json);
}
Log.e("call", call); // this called in real time
publishProgress((int) (((i + 1) / (float) count) * 100)); // this called after for cycle is ended
} catch (Exception e) {
message = e.getMessage();
e.printStackTrace();
return message;
}
}
SharedPreferences.Editor edit = NationalParks.getSharedPreferences().edit();
edit.putLong("lastUpdate", Calendar.getInstance().getTimeInMillis() / 1000);
edit.commit();
return message;
}
...
protected void onProgressUpdate(Integer... progress) {
Log.e("Progress", progress[0] + "%");
progressBar.setProgress(progress[0]);
}
Know anybody why?

AsynTask with Endless Listview Scroll in android

I am creating an application where in i need to have endless scrolling listview. I dnt want to use any library in my application. I have seen some examples on line that help in achieving such listview,but my doubt is how can i have an endless listview when my data are coming from server and are getting parsed in the Asynctask. How can i load 10 items at a time from my asynctask on scroll? I want to know to implement a endless listview on asyntask.
Do i call my asynctask in the onScroll() or not???
public class EndlessScrollExample extends ListActivity {
public JSONArray jsonarray,jsondatearray;
public String url;
public String selectedvalue;
public String TAG = "TAG Event Display";
public String SuggestCity;
public String SuggestState;
public String suggestCountry;
public String event_id,address;
String lat;
String lng;
public String event_name;
public String dateKey;
public String datetime,timenew;
Calendar cal;
public SharedPreferences prefs;
public Editor editor;
public String access_token,id,username;
public static ArrayList<EventsBean> arrayEventsBeans = new ArrayList<EventsBean>();
ArrayList<DateBean> sortArray = new ArrayList<DateBean>();
public SAmpleAdapter adapter;
public ImageView img_menu,img_calender;
public ListView listview;
public EventsBean eventsbean;
int counter = 0;
int currentPage = 0;
FetchEventValues fetchValues;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setTheme(android.R.style.Theme);
setContentView(R.layout.sample_endless);
listview = (ListView)findViewById(android.R.id.list);
try {
// Preferences values fetched from the preference of FBConnection class.
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
access_token = prefs.getString("access_token", null);
id = prefs.getString("uid", null);
username = prefs.getString("username", null);
if(access_token == null && id == null && username == null)
{
Toast.makeText(getApplicationContext(), "FaceBook Login was not successful" +
"/nPlease Relogin.", Toast.LENGTH_SHORT).show();
}
else
{
Log.i(TAG, "VALUES::" + access_token+ " " + id + " " +username);
url = "my Url";
}
} catch (NullPointerException e) {
Log.i(TAG, "User Not Logged IN " + e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
}
fetchValues = new FetchEventValues();
fetchValues.execute();
listview = getListView();
listview.setOnScrollListener(new EndlessScrollListener());
}
// AsyncTask Class called in the OnCreate() when the activity is first started.
public class FetchEventValues extends AsyncTask<Integer, Integer, Integer>
{
ProgressDialog progressdialog = new ProgressDialog(EndlessScrollExample.this);
#SuppressLint("SimpleDateFormat")
#SuppressWarnings("unchecked")
#Override
protected Integer doInBackground(Integer... params) {
currentPage++;
// Creating JSON Parser instance
JsonParser jParser = new JsonParser();
// getting JSON string from URL
//arrayEventsBeans.clear();
JSONObject jsonobj = jParser.getJSONFromUrl(url);
Log.i(TAG, "URL VALUES:" + url);
try{
// Code to get the auto complete values Autocomplete Values
JSONArray jsonAarray = jsonobj.getJSONArray(Constants.LOCATIONS);
eventsbean = new EventsBean();
Log.e(TAG, "Location Array Size:" + jsonAarray.length());
for(int j = 0 ; j < jsonAarray.length() ; j++)
{
if(!jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_CITY) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_STATE) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_COUNTRY))
{
JSONObject job = jsonAarray.getJSONObject(j);
if(job.has(Constants.LOCATION_STATE))
{
SuggestCity = job.getString(Constants.LOCATION_CITY);
eventsbean.setLocation_city(job.getString(Constants.LOCATION_CITY));
SuggestState = job.getString(Constants.LOCATION_STATE);
eventsbean.setLocation_state(job.getString(Constants.LOCATION_STATE));
suggestCountry = job.getString(Constants.LOCATION_COUNTRY);
eventsbean.setLocation_country(job.getString(Constants.LOCATION_COUNTRY));
}
}
}
// JSON object to fetch the events in datewise format
JSONObject eventobject = jsonobj.getJSONObject("events");
arrayEventsBeans = new ArrayList<EventsBean>();
// #SuppressWarnings("unchecked")
Iterator<Object> keys = eventobject.keys();
while (keys.hasNext()) {
String datestring = String.valueOf(keys.next());
if (datestring.trim().length() > 0) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter.parse(datestring);
DateBean dateBean = new DateBean(date);
sortArray.add(dateBean);
}
// JSONArray jsonArray = eventobject.getJSONArray(datestring);
//System.out.println(" --"+jsonArray);
}
System.out.println("size:"+sortArray.size());
System.out.println("==========sorting array======");
Collections.sort(sortArray,new CompareDate());
//reverse order
//Collections.reverse(sortArray);
for(DateBean d : sortArray){
dateKey = new SimpleDateFormat("yyyy-MM-dd").format(d.getDate());
System.out.println(dateKey);
Date today = new Date();
Date alldates = d.getDate();
/// Calendar alldates1 = Calendar.getInstance();
JSONArray jsonArray = eventobject.getJSONArray(dateKey);
System.out.println(" --"+jsonArray);
for (int i = 0 ; i < jsonArray.length() ; i++)
{
if ((today.compareTo(alldates) < 0 || (today.compareTo(alldates)== 0)))
// if (alldates1 > cal) alldates.getTime() >= today.getTime()
{
String currentTimeStr = "7:04 PM";
Date userDate = new Date();
String userDateWithoutTime = new SimpleDateFormat("yyyyMMdd").format(userDate);
String currentDateStr = userDateWithoutTime + " " + currentTimeStr;
Date currentDate = new SimpleDateFormat("yyyyMMdd h:mm a").parse(currentDateStr);
if (userDate.compareTo(currentDate) >= 0) {
System.out.println(userDate + " is greater than or equal to " + currentDate);
} else {
System.out.println(userDate + " is less than " + currentDate);
}
JSONObject jsonobjname = jsonArray.getJSONObject(i);
EventsBean eventsbean = new EventsBean();
JSONObject jobjectpicture = jsonobjname.getJSONObject(Constants.PICTURE);
JSONObject jobjeventpicture = jobjectpicture.getJSONObject(Constants.DATA);
eventsbean.setUrl(jobjeventpicture.getString(Constants.URL));
if(jsonobjname.has(Constants.OWNER))
{
JSONObject owner_obj = jsonobjname.getJSONObject(Constants.OWNER);
eventsbean.setOwner_id(owner_obj.getString(Constants.OWNER_ID));
eventsbean.setOwner_name(owner_obj.getString(Constants.OWNER_NAME));
String owner_name = owner_obj.getString(Constants.OWNER_NAME);
Log.i(TAG, "Owner:" + owner_name);
}
if(!jsonobjname.isNull(Constants.COVER))
{
JSONObject objectcover = jsonobjname.getJSONObject(Constants.COVER);
eventsbean.setCover_id(objectcover.getString(Constants.COVER_ID));
eventsbean.setSource(objectcover.getString(Constants.SOURCE));
String cover_url = objectcover.getString(Constants.SOURCE);
Log.i(TAG, "Cover Url:" + cover_url);
eventsbean.setOffset_y(objectcover.getString(Constants.OFFSET_Y));
eventsbean.setOffset_x(objectcover.getString(Constants.OFFSET_X));
}
eventsbean.setName(jsonobjname.getString(Constants.NAME));
eventsbean.setEvent_id(jsonobjname.getString(Constants.EVENT_ID));
eventsbean.setStart_time(jsonobjname.getString(Constants.START_TIME));
eventsbean.setDescription(jsonobjname.getString(Constants.DESCRIPTION));
eventsbean.setLocation(jsonobjname.getString(Constants.LOCATION));
if(!jsonobjname.isNull(Constants.IS_SILHOUETTE))
{
eventsbean.setIs_silhouette(jsonobjname.getString(Constants.IS_SILHOUETTE));
}
eventsbean.setPrivacy(jsonobjname.getString(Constants.PRIVACY));
datetime = jsonobjname.getString(Constants.START_TIME);
if(!jsonobjname.isNull(Constants.VENUE))
{
JSONObject objectvenue = jsonobjname.getJSONObject(Constants.VENUE);
if(objectvenue.has(Constants.VENUE_NAME))
{
eventsbean.setVenue_name(objectvenue.getString(Constants.VENUE_NAME));
event_name = objectvenue.getString(Constants.VENUE_NAME);
Log.i(TAG, "Event Venue Name:" + event_name);
}
else
{
eventsbean.setLatitude(objectvenue.getString(Constants.LATITUDE));
eventsbean.setLongitude(objectvenue.getString(Constants.LONGITUDE));
eventsbean.setCity(objectvenue.getString(Constants.CITY));
eventsbean.setState(objectvenue.getString(Constants.STATE));
eventsbean.setCountry(objectvenue.getString(Constants.COUNTRY));
eventsbean.setVenue_id(objectvenue.getString(Constants.VENUE_ID));
eventsbean.setStreet(objectvenue.getString(Constants.STREET));
address = objectvenue.getString(Constants.STREET);
eventsbean.setZip(objectvenue.getString(Constants.ZIP));
}
}
arrayEventsBeans.add(eventsbean);
Log.i(TAG, "arry list values:" + arrayEventsBeans.size());
}
}
}
}catch(Exception e){
Log.e(TAG , "Exception Occured:" + e.getMessage());
}
return null;
}
class CompareDate implements Comparator<DateBean>{
#Override
public int compare(DateBean d1, DateBean d2) {
return d1.getDate().compareTo(d2.getDate());
}
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Integer result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
if(this.progressdialog.isShowing())
{
this.progressdialog.dismiss();
}
if(adapter == null)
{
adapter = new SAmpleAdapter(EndlessScrollExample.this, 0, arrayEventsBeans);
listview.setAdapter(adapter);
}
else
{
adapter.notifyDataSetChanged();
}
//currentPage++;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
this.progressdialog.setMessage("Loading....");
this.progressdialog.setCanceledOnTouchOutside(false);
this.progressdialog.show();
}
public int setPage(int currentPage) {
return currentPage;
// TODO Auto-generated method stub
}
}
public class EndlessScrollListener implements OnScrollListener {
private int visibleThreshold = 0;
private int currentPage = 0;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (listview.getLastVisiblePosition() >= listview.getCount() - visibleThreshold) {
currentPage++;
fetchValues.setPage(currentPage);
fetchValues.execute();
}
}
}
}
}
Thanks in advance.
ListView already supports OnScrollListener, so you have to override it and check the condition(in onScroll()), whether it is reached to the end of the list or not.If yes, then add a footer(optional) and fire the async task. After reciving the result notify the adapter. You could check solution on this link, it works on the same concept.
here are few examples of what you are looking for:
http://mobile.dzone.com/news/android-tutorial-dynamicaly
https://github.com/johannilsson/android-pulltorefresh

Endless adapter always running to download data in background

I have customized the code of EndlessAdapter in my app but one mistake done by me as this Endless Adapter always download data in the background instead it should download the same after user scroll downs the list and I unable to find the same mistake in our project. Due to this mistake my app sometimes returns OutOfMemoryException which is not acceptable.
Please suggest me any solution regarding the same.
Code:
*MyEndlessAdapter:*
class DemoAdapterCat extends EndlessAdapter {
private RotateAnimation rotate=null;
ArrayList<String> tempListNamesCat = new ArrayList<String>();
ArrayList<String> tempListImagesCat = new ArrayList<String>();
ArrayList<String> tempListYearCat1 = new ArrayList<String>();
ArrayList<String> tempListYearCat2 = new ArrayList<String>();
ArrayList<String> tempListmpgCat1 = new ArrayList<String>();
ArrayList<String> tempListmpgCat2 = new ArrayList<String>();
ArrayList<String> tempListpriceCat1 = new ArrayList<String>();
ArrayList<String> tempListpriceCat2 = new ArrayList<String>();
ArrayList<String> tempListRatingCat1 = new ArrayList<String>();
ArrayList<String> tempListRatingCat2 = new ArrayList<String>();
DemoAdapterCat() {
super(new CategoryListLazyAdapter(ResearchList.this, countriesSubCat, imagesSubCat, YearSubCat1,YearSubCat2, mpgSubCat1,mpgSubCat2, priceSubCat1,priceSubCat2, ratingSubCat1, ratingSubCat2));
Utility util = new Utility();
util.setListViewHeightBasedOnChildren(lvCategory);
rotate=new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
rotate.setDuration(600);
rotate.setRepeatMode(Animation.RESTART);
rotate.setRepeatCount(Animation.INFINITE);
}
/*
#Override
public int getCount()
{
//return brandList.getDisplayNames().size();
return countriesSubCat.size();
}*/
#Override
protected View getPendingView(ViewGroup parent) {
row=getLayoutInflater().inflate(R.layout.categorylist, null);
child=row.findViewById(R.id.tv_CategoryItem_Name);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_MPG1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_MPG2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Price1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Price2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Rating1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Rating2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Year1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Year2);
child.setVisibility(View.GONE);
/*child = row.findViewById(R.id.img_CategoryItem);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.img_CategoryItem_Arrow);
child.setVisibility(View.GONE);*/
/*child = row.findViewById(R.id.linear_main_MPG);
child.setVisibility(View.GONE);*/
child=row.findViewById(R.id.throbber);
child.setVisibility(View.VISIBLE);
child.startAnimation(rotate);
return(row);
}
#Override
protected boolean cacheInBackground() {
SystemClock.sleep(10000);
tempListNamesCat.clear();
tempListImagesCat.clear();
tempListmpgCat1.clear();
tempListmpgCat2.clear();
tempListpriceCat1.clear();
tempListpriceCat2.clear();
tempListYearCat1.clear();
tempListYearCat2.clear();
tempListRatingCat1.clear();
tempListRatingCat2.clear();
int lastOffset = getLastOffset();
if(lastOffset < LIST_SIZE){
int limit = lastOffset + BATCH_SIZE;
for(int i=(lastOffset+1); (i<=limit && i<LIST_SIZE); i++){
tempListNamesCat.add(coll.getDisplayNames().get(i));
tempListImagesCat.add(coll.getImages().get(i));
tempListmpgCat1.add(coll.getMpg().get(i));
tempListmpgCat2.add(coll.getMpg().get(i+1));
tempListpriceCat1.add(coll.getPrice().get(i));
tempListpriceCat2.add(coll.getPrice().get(i+1));
tempListRatingCat1.add(coll.getRating().get(i));
tempListRatingCat2.add(coll.getRating().get(i+1));
tempListYearCat1.add(coll.getYears().get(i));
tempListYearCat2.add(coll.getYears().get(i+1));
}
setLastOffset(limit);
if(limit<LIST_SIZE){
//return true;
return(getWrappedAdapter().getCount()<coll.getDisplayNames().size());
} else {
return false;
}
} else {
return false;
}
}
#Override
protected void appendCachedData() {
#SuppressWarnings("unchecked")
//Activity activity = this;
//ArrayAdapter<String> arrAdapterNew = (ArrayAdapter<String>)getWrappedAdapter();
CategoryListLazyAdapter arrAdapterNewCategory = (CategoryListLazyAdapter)getWrappedAdapter();
//int listLen = tempList.size();
// int listLen = tempListNames.size();
countriesSubCat.addAll(tempListNamesCat);
imagesSubCat.addAll(tempListImagesCat);
mpgSubCat1.addAll(tempListmpgCat1);
mpgSubCat2.addAll(tempListmpgCat2);
priceSubCat1.addAll(tempListpriceCat1);
priceSubCat2.addAll(tempListpriceCat2);
ratingSubCat1.addAll(tempListRatingCat1);
ratingSubCat2.addAll(tempListRatingCat2);
YearSubCat1.addAll(tempListYearCat1);
YearSubCat2.addAll(tempListYearCat2);
arrAdapterNewCategory.notifyDataSetChanged();
Utility util = new Utility();
util.setListViewHeightBasedOnChildren(lvCategory);
/* for(int i=0; i<listLen; i++){
// arrAdapterNew.add(tempList.get(i));
}*/
}
}
Set Demoadapter to the list:
public void setValuesInCategoryChildSortByAZ(String url,final String filter, final String from, final String to)
{
if(isOnline())
{
final ProgressDialog dialog = ProgressDialog.show(
ResearchList.this, "Research List ",
"Please wait... ", true);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
// System.out.println("The id after Save:"+id.get(0).toString());
// catagory.addAll(keyword_vector1);
linear_Category_Child.setVisibility(View.GONE);
linear_Category_Child_Child.setVisibility(View.VISIBLE);
//tv_Child_Header.setText("Volvo");
/*adapter = new CategoryListLazyAdapter(
ResearchList.this);
lvCategory.setAdapter(adapter);*/
demoAdapterCat.notifyDataSetChanged();
Utility util = new Utility();
util.setListViewHeightBasedOnChildren(lvCategory);
dialog.dismiss();
}
};
final Thread checkUpdate = new Thread() {
public void run() {
try {
String sortEncode = URLEncoder.encode("alpha");
String filterEncode = URLEncoder.encode(filter);
String clientEncode = URLEncoder.encode("10030812");
String fromEncode = URLEncoder.encode(from);
String toEncode = URLEncoder.encode(to);
String catUrl = "/v1/vehicles/get-make-models.json?sort="+sortEncode+"&filter="+filterEncode+"&client-id="+clientEncode+"&from="+fromEncode;
genSig = new GetSignature(catUrl, "acura");
try {
signature = genSig.getUrlFromString();
} catch (InvalidKeyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// jsonString =
// getJsonSring("http://api.highgearmedia.com/v1/vehicles/get-models.json?make=acura&client-id=10030812&signature=LWQbdAlJVxlXZ1VO2mfqAA==");
//String signatureEncode = URLEncoder.encode(signature);
String urlEncode = URLEncoder.encode(catUrl+"&signature="+signature);
jsonString = getJsonSring("http://apibeta.highgearmedia.com"+catUrl+"&signature="+signature);
System.out.println("The json category:===>"+jsonString);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonParse json = new JsonParse(jsonString);
json.parseCat();
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();
}else
{
AlertDialog.Builder builder = new Builder(ResearchList.this);
builder.setTitle("Attention!");
builder.setMessage("Network Connection unavailable.");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.create().show();
}
}
Thanks in advance.
I unable to find the same mistake in our project
The EndlessAdapter sample app is here: https://github.com/commonsguy/cwac-endless/tree/master/demo.
If you look at that sample app, you will notice that it does not fork any threads.
If you read the EndlessAdapter documentation, you will see:
Your EndlessAdapter subclass also needs to implement cacheInBackground(). This method will be called from a background thread, and it needs to download more data that will eventually be added to the ListAdapter you used in the constructor. While the demo application simply sleeps for 10 seconds, a real application might make a Web service call or otherwise load in more data.
Since this method is called on a background thread, you do not need to fork your own thread. However, at the same time, do not try to update the UI directly.
So, change your project to not fork your own thread, but instead do your work in cacheInBackground() to retrieve and add the next batch of data.
If that approach does not fit the way your app needs to run, that is fine, but you may have difficulty in using EndlessAdapter.

Categories

Resources