Application is doing too much work on its main thread? - android

I am having huge problems with my android application. In the app, I fetch data every thirty seconds from a JSON stream to update a listview--i only update the custom adapter if there is new data. If I call the JSONParse/update tasks once, everything works fine, though when I put this method inside a timer task, my application barely runs and ends up closing down after 10 seconds. If there is any way you can help me, i would be more than grateful. I am really sorry there is so much code here. Most importantly, pay attention to the callAsynchonousTask() method.
Here is the class where most the application work is being done:
public class LiveStreamFragment extends Fragment{
public WXYCMediaPlayer mediaPlayer;
ListView list;
TextView song;
TextView artist;
public ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
private static String wxycUrl = "http://www.wxyc.info/playlists/recentEntries?v=2";
private static String streamURL = "http://152.2.204.90:8000/wxyc.mp3";
private static final String TAG_PLAYCUTS = "playcuts";
private static final String TAG_SONG = "songTitle";
private static final String TAG_ARTIST = "artistName";
private static final String TAG_ALBUM = "releaseTitle";
private static final String TAG_TALKSETS = "talksets";
private static final String TAG_CHRONID = "chronOrderID";
private static final String TAG_BREAKPOINTS = "breakpoints";
private static final String TAG_HOUR = "hour";
private static final String TAG_LAYOUT = "layoutType";
private SwipeRefreshLayout swipeLayout;
private Button update_button;
private JSONArray playcuts = null;
private JSONArray talksets = null;
private JSONArray breakpoints = null;
private Playcut[] playcutArr;
private Talkset[] talksetArr;
private Breakpoint[] breakpointArr;
public View rootView;
boolean firstCall = true;
boolean buttonActivated;
LiveAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rootView = inflater.inflate(R.layout.stream_fragment, container, false);
list = (ListView) rootView.findViewById(R.id.list);
adapter = new LiveAdapter(LiveStreamFragment.this.getActivity(), oslist, LiveStreamFragment.this, list);
list.setAdapter(adapter);
buttonActivated = false;
new JSONParse().execute();
this.callAsynchronousTask();
update_button = (Button) rootView.findViewById(R.id.update_button);
update_button.setText("New Tracks!");
update_button.setGravity(Gravity.CENTER_HORIZONTAL);
update_button.setVisibility(View.GONE);
update_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.updateDataList(oslist);
update_button.setVisibility(View.GONE);
buttonActivated = false;
}
});
list.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
if(buttonActivated) {
update_button.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(buttonActivated) {
update_button.setVisibility(View.GONE);
}
}
});
return rootView;
}
public void addHeartData(HashMap<String, String> heartMap){
Bus bus = new Bus();
BusProvider.getInstance().post(heartMap);
}
/******** Calling the JSON Feed to update every 30 seconds ********/
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
new JSONParse().execute();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 30000); //execute in every 50000 ms
}
/******** JSON Parsing and sorting class ********/
public class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
private String chronIDCheck;
#Override
protected void onPreExecute() {
super.onPreExecute();
oslist = new ArrayList<HashMap<String, String>>();
/*DELAY THIS TASK FOR THE SPLASH SCREEN TIME*/
//mediaPlayer = new WXYCMediaPlayer(streamURL, this.getActivity());
//HashMap<String, String> streamMap = new HashMap<String, String>(); //Add this to the media player method.
//streamMap.put(TAG_LAYOUT, "LiveStream");
//oslist.add(streamMap);
/*list = (ListView) rootView.findViewById(R.id.list);
adapter = new LiveAdapter(LiveStreamFragment.this.getActivity(), oslist, LiveStreamFragment.this, list);
list.setAdapter(adapter);*/
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(wxycUrl);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
playcuts = json.getJSONArray(TAG_PLAYCUTS);
talksets = json.getJSONArray(TAG_TALKSETS);
breakpoints = json.getJSONArray(TAG_BREAKPOINTS);
playcutArr = new Playcut[playcuts.length()];
talksetArr = new Talkset[talksets.length()];
breakpointArr = new Breakpoint[breakpoints.length()];
for(int i = 0; i < playcuts.length(); i++){
JSONObject playcut = playcuts.getJSONObject(i);
playcutArr[i] = new Playcut(
playcut.getString(TAG_SONG),
playcut.getString(TAG_ARTIST),
playcut.getString(TAG_ALBUM),
playcut.getInt(TAG_CHRONID));
}
for(int j = 0; j < talksets.length(); j++){
JSONObject talkset = talksets.getJSONObject(j);
talksetArr[j] = new Talkset(
talkset.getInt(TAG_CHRONID));
}
for(int k = 0; k < breakpoints.length(); k++){
JSONObject breakpoint = breakpoints.getJSONObject(k);
breakpointArr[k] = new Breakpoint(
breakpoint.getInt(TAG_CHRONID),
breakpoint.getLong(TAG_HOUR)
);
}
} catch (JSONException e) {
e.printStackTrace();
}
int playcutIndex = 0;
int talksetIndex = 0;
int breakpointIndex = 0;
int minID;
int i = 0;
/******** Algorithm to consolidate playcuts, breakpoints, and talksets into one arraylist by their chronological ID ********/
while(i < 30){
HashMap<String, String> map = new HashMap<String, String>();
minID = Math.max(
playcutArr[playcutIndex].chronID, (int) Math.max(
talksetArr[talksetIndex].chronID, breakpointArr[breakpointIndex].chronID
)
);
if(minID == playcutArr[playcutIndex].chronID) {
map.put(TAG_SONG, playcutArr[playcutIndex].song);
map.put(TAG_ARTIST, playcutArr[playcutIndex].artist);
map.put(TAG_ALBUM, playcutArr[playcutIndex].album);
map.put(TAG_LAYOUT, "Playcut");
map.put(TAG_CHRONID,""+playcutArr[playcutIndex].chronID);
StringBuilder stringBuilder = new StringBuilder("http://ws.audioscrobbler.com/2.0/");
stringBuilder.append("?method=album.getinfo");
stringBuilder.append("&api_key=");
stringBuilder.append("2ead17554acf667f27cf7dfd4c368f15");
String albumURL = null;
try {
stringBuilder.append("&artist=" + URLEncoder.encode(map.get(TAG_ARTIST), "UTF-8"));
stringBuilder.append("&album=" + URLEncoder.encode(map.get(TAG_ALBUM), "UTF-8"));
albumURL = new RetrieveAlbumArtUrlTask().execute(stringBuilder.toString()).get();
} catch (UnsupportedEncodingException e) {
albumURL = null;
} catch (InterruptedException e) {
albumURL = null;
} catch (ExecutionException e) {
albumURL = null;
} catch (IllegalArgumentException e) {
albumURL = null;
}
map.put("albumArtUrl", albumURL);
playcutIndex = playcutIndex + 1;
}
if(minID == talksetArr[talksetIndex].chronID) {
map.put(TAG_SONG, "Talkset");
map.put(TAG_ARTIST, null);
map.put(TAG_LAYOUT, "Talkset");
map.put(TAG_CHRONID,""+talksetArr[talksetIndex].chronID);
talksetIndex = talksetIndex + 1;
}
if(minID == breakpointArr[breakpointIndex].chronID) {
map.put(TAG_SONG, "Breakpoint");
map.put(TAG_ARTIST, null);
map.put(TAG_LAYOUT, "Breakpoint");
map.put(TAG_HOUR, ""+breakpointArr[breakpointIndex].hour);
map.put(TAG_CHRONID,""+breakpointArr[breakpointIndex].chronID);
breakpointIndex = breakpointIndex + 1;
}
map.put("Clicked", "False");
oslist.add(map);
chronIDCheck = oslist.get(0).get(TAG_CHRONID);
i++;
}
/* If this is the first JSON Parse, we instantiate the adapter, otherwise we just update */
if(firstCall) {
list = (ListView) rootView.findViewById(R.id.list);
adapter = new LiveAdapter(LiveStreamFragment.this.getActivity(), oslist, LiveStreamFragment.this, list);
list.setAdapter(adapter);
firstCall = false;
} else {
if(!adapter.chronIdCheck().equals(oslist.get(0).get(TAG_CHRONID))) {
//adapter.updateDataList(oslist);
update_button.setVisibility(View.VISIBLE);
buttonActivated = true;
}
}
}
}
}
Here is my new doInBackground() Code:
#Override
protected Void doInBackground(String... args) {
jParser = new JSONParser();
json = jParser.getJSONFromUrl(wxycUrl);
Log.v("TEST","BACKGROUND");
try {
playcuts = json.getJSONArray(TAG_PLAYCUTS);
talksets = json.getJSONArray(TAG_TALKSETS);
breakpoints = json.getJSONArray(TAG_BREAKPOINTS);
playcutArr = new Playcut[playcuts.length()];
talksetArr = new Talkset[talksets.length()];
breakpointArr = new Breakpoint[breakpoints.length()];
for(int i = 0; i < playcuts.length(); i++){
JSONObject playcut = playcuts.getJSONObject(i);
playcutArr[i] = new Playcut(
playcut.getString(TAG_SONG),
playcut.getString(TAG_ARTIST),
playcut.getString(TAG_ALBUM),
playcut.getInt(TAG_CHRONID));
}
for(int j = 0; j < talksets.length(); j++){
JSONObject talkset = talksets.getJSONObject(j);
talksetArr[j] = new Talkset(
talkset.getInt(TAG_CHRONID));
}
for(int k = 0; k < breakpoints.length(); k++){
JSONObject breakpoint = breakpoints.getJSONObject(k);
breakpointArr[k] = new Breakpoint(
breakpoint.getInt(TAG_CHRONID),
breakpoint.getLong(TAG_HOUR)
);
}
} catch (JSONException e) {
e.printStackTrace();
}
int playcutIndex = 0;
int talksetIndex = 0;
int breakpointIndex = 0;
int minID;
int i = 0;
/******** Algorithm to consolidate playcuts, breakpoints, and talksets into one arraylist by their chronological ID ********/
while(i < 30){
HashMap<String, String> map = new HashMap<String, String>();
minID = Math.max(
playcutArr[playcutIndex].chronID, (int) Math.max(
talksetArr[talksetIndex].chronID, breakpointArr[breakpointIndex].chronID
)
);
if(minID == playcutArr[playcutIndex].chronID) {
map.put(TAG_SONG, playcutArr[playcutIndex].song);
map.put(TAG_ARTIST, playcutArr[playcutIndex].artist);
map.put(TAG_ALBUM, playcutArr[playcutIndex].album);
map.put(TAG_LAYOUT, "Playcut");
map.put(TAG_CHRONID,""+playcutArr[playcutIndex].chronID);
StringBuilder stringBuilder = new StringBuilder("http://ws.audioscrobbler.com/2.0/");
stringBuilder.append("?method=album.getinfo");
stringBuilder.append("&api_key=");
stringBuilder.append("2ead17554acf667f27cf7dfd4c368f15");
String albumURL = null;
try {
stringBuilder.append("&artist=" + URLEncoder.encode(map.get(TAG_ARTIST), "UTF-8"));
stringBuilder.append("&album=" + URLEncoder.encode(map.get(TAG_ALBUM), "UTF-8"));
albumURL = new RetrieveAlbumArtUrlTask().execute(stringBuilder.toString()).get();
} catch (UnsupportedEncodingException e) {
albumURL = null;
} catch (InterruptedException e) {
albumURL = null;
} catch (ExecutionException e) {
albumURL = null;
} catch (IllegalArgumentException e) {
albumURL = null;
}
map.put("albumArtUrl", albumURL);
playcutIndex = playcutIndex + 1;
}
if(minID == talksetArr[talksetIndex].chronID) {
map.put(TAG_SONG, "Talkset");
map.put(TAG_ARTIST, null);
map.put(TAG_LAYOUT, "Talkset");
map.put(TAG_CHRONID,""+talksetArr[talksetIndex].chronID);
talksetIndex = talksetIndex + 1;
}
if(minID == breakpointArr[breakpointIndex].chronID) {
map.put(TAG_SONG, "Breakpoint");
map.put(TAG_ARTIST, null);
map.put(TAG_LAYOUT, "Breakpoint");
map.put(TAG_HOUR, ""+breakpointArr[breakpointIndex].hour);
map.put(TAG_CHRONID,""+breakpointArr[breakpointIndex].chronID);
breakpointIndex = breakpointIndex + 1;
}
map.put("Clicked", "False");
oslist.add(map);
chronIDCheck = oslist.get(0).get(TAG_CHRONID);
i++;
}
Log.v("Test", "Background 2");
return null;
}
#Override
protected void onPostExecute(Void args) {
Log.v("TEST","POST");
/* If this is the first JSON Parse, we instantiate the adapter, otherwise we just update */
if(firstCall) {
list = (ListView) rootView.findViewById(R.id.list);
adapter = new LiveAdapter(LiveStreamFragment.this.getActivity(), oslist, LiveStreamFragment.this, list);
list.setAdapter(adapter);
firstCall = false;
} else {
if(!adapter.chronIdCheck().equals(oslist.get(0).get(TAG_CHRONID))) {
//adapter.updateDataList(oslist);
update_button.setVisibility(View.VISIBLE);
buttonActivated = true;
}
}
}
}

The method onPostExecute is called on the UI thread, and you are doing a lot of things in it. Try keeping the code as from if(firstCall) in onPostExecute, because that is where you need to access the UI. The rest of the code above can be moved to doInBackground, which is invoked on a background thread.
From the docs :
doInBackground(Params...), invoked on the background thread
immediately after onPreExecute() finishes executing.
onPostExecute(Result), invoked on the UI thread after the background
computation finishes.

Related

addView is not displaying the items

I am trying to fetch JSON object from an Api and display it on a checkList on a LinearLayout. Even though I am adding the checklist View to the container it is not showing. Is it the case that I have to use notifyDataSetChanged(), If so how can I implement it in LinearLayout.
Thank you . I do apologize for my english.
public class NasilYapilir extends Fragment {
int index;
private CheckBox checkBox;
private CheckBox[] checkBoxes;
List<Reciep> reciepList = new ArrayList<>();
LinearLayout linearLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_nasil_yapilir, container, false);
index = getArguments().getInt(DetailViewPager.KEY_INDEX_TAG);
load_data(index);
linearLayout = (LinearLayout) view.findViewById(R.id.linearLayout);
checkBoxes = new CheckBox[reciepList.size()];
populateDirections(reciepList,linearLayout);
Log.i("we are in nasil yaplir",index + "");
return view;
}
public void populateDirections(List<Reciep> reciep, ViewGroup container){
int i = 0;
for(Reciep recieps : reciep){
checkBoxes[i] = new CheckBox(getActivity());
// checkBoxes[i].setPadding(8,16,8,16);
checkBoxes[i].setText(recieps.getQuantity()+ " "+ recieps.getUnit_ad()+ " "+ recieps.getIngredients_ad());
reciep.size();
container.addView(checkBoxes[i]);
i++;
}
}
public void load_data(int index) {
task.execute("http://yemekapp.kuarkdijital.com.tr/v_recipe.php?id=" + index);
}
AsyncTask<String, Void, String> task = new AsyncTask<String, Void, String>() {
#Override
protected String doInBackground(String... params) {
URL url;
HttpURLConnection URLConnection = null;
String current = "";
try {
url = new URL(params[0]);
URLConnection = (HttpURLConnection) url.openConnection();
URLConnection.connect();
InputStream inputStream = URLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
current += (char) data;
data = reader.read();
}
JSONObject itemObject = null;
JSONObject quantityObject = null;
// JSONObject popularObject = null;
JSONObject jsonObject = new JSONObject(current);
String item = jsonObject.getString("item");
JSONArray itemArray = new JSONArray(item);
// JSONArray popularArray = new JSONArray(popular);
for (int i = 0; i < itemArray.length(); i++) {
itemObject = itemArray.getJSONObject(i);
String itemsQuantity = itemObject.getString("items");
JSONArray quantityArray = new JSONArray(itemsQuantity);
for(int j = 0; j<quantityArray.length() ;j++){
quantityObject = quantityArray.getJSONObject(i);
Reciep reciep = new Reciep(quantityObject.getString("Quantity"),quantityObject.getString("unit_ad"),quantityObject.getString("ingredient_ad"));
reciepList.add(reciep);
Log.i("quatityArray",quantityArray.get(j).toString());
}
// popularObject = popularArray.getJSONObject(i);
// DailyData DailyData = new DailyData(dailyObject.getInt("id"), dailyObject.getString("Servings"), dailyObject.getString("Title"), dailyObject.getString("CookTime"), dailyObject.getString("Image"));
// DailyData PopularData = new DailyData(popularObject.getInt("id"), popularObject.getString("Servings"), popularObject.getString("Title"), popularObject.getString("CookTime"), popularObject.getString("Image"));
// daily_data_list.add(DailyData);
// popular_data_list.add(PopularData);
}
}
catch (JSONException e) {
e.printStackTrace();
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// notifyDataSetChanged();
}
};
}
Try this code
public class NasilYapilir extends Fragment {
int index;
private CheckBox checkBox;
private CheckBox[] checkBoxes;
List<Reciep> reciepList = new ArrayList<>();
LinearLayout linearLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_nasil_yapilir, container, false);
index = getArguments().getInt(DetailViewPager.KEY_INDEX_TAG);
linearLayout = (LinearLayout) view.findViewById(R.id.linearLayout);
checkBoxes = new CheckBox[reciepList.size()];
load_data(index);
//populateDirections(reciepList,linearLayout);
Log.i("we are in nasil yaplir",index + "");
return view;
}
public void populateDirections(List<Reciep> reciep, ViewGroup container){
int i = 0;
for(Reciep recieps : reciep){
checkBoxes[i] = new CheckBox(getActivity());
// checkBoxes[i].setPadding(8,16,8,16);
checkBoxes[i].setText(recieps.getQuantity()+ " "+
recieps.getUnit_ad()+ " "+ recieps.getIngredients_ad());
reciep.size();
container.addView(checkBoxes[i]);
i++;
}
}
public void load_data(int index) {
task.execute("http://yemekapp.kuarkdijital.com.tr/v_recipe.php?id=" + index);
}
AsyncTask<String, Void, String> task = new AsyncTask<String, Void, String>() {
#Override
protected String doInBackground(String... params) {
URL url;
HttpURLConnection URLConnection = null;
String current = "";
try {
url = new URL(params[0]);
URLConnection = (HttpURLConnection) url.openConnection();
URLConnection.connect();
InputStream inputStream = URLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
current += (char) data;
data = reader.read();
}
}
catch (JSONException e) {
e.printStackTrace();
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(String current) {
super.onPostExecute(current);
if(current.isEmpty())
return;
JSONObject itemObject = null;
JSONObject quantityObject = null;
JSONObject jsonObject = new JSONObject(current);
String item = jsonObject.getString("item");
JSONArray itemArray = new JSONArray(item);
for (int i = 0; i < itemArray.length(); i++) {
itemObject = itemArray.getJSONObject(i);
String itemsQuantity = itemObject.getString("items");
JSONArray quantityArray = new JSONArray(itemsQuantity);
for(int j = 0; j<quantityArray.length() ;j++){
quantityObject = quantityArray.getJSONObject(i);
Reciep reciep = new Reciep(quantityObject.getString("Quantity"),quantityObject.getString("unit_ad"),quantityObject.getString("ingredient_ad"));
reciepList.add(reciep);
Log.i("quatityArray",quantityArray.get(j).toString());
}
}
populateDirections(reciepList,linearLayout);
}
}
}

Android: white screen while onCreate

I have an app that at launch inside onCreate method copies data from assets folder. It does it in three for cycles, each with activity indicator and the problem is that when first two cycles run white screen shows and only when third loop starts i can seen activity screen with indicator on it.
The code is following
Realm realm;
ListView list;
int[] imageidsm = {R.drawable.fon_sovety350, R.drawable.fon_german350, R.drawable.fon_usa350, R.drawable.fon_uk350, R.drawable.fon_fr_it200, R.drawable.fon_japan_china200, R.drawable.fon_history200};
String[] itemname = {"СССР", "ГЕРМАНИЯ", "США", "ВЕЛИКОБРИТАНИЯ", "ФРАНЦИЯ И ИТАЛИЯ", "ЯПОНИЯ И КИТАЙ", "ИСТОРИЯ"};
Boolean firstLaunch = false;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
MainAdapter adapter = new MainAdapter(this, itemname, imageidsm, height, width);
list = (ListView) findViewById(R.id.mainListView);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 2) {
Intent toSssr = new Intent(MainActivity.this, TankListActivity.class);
toSssr.putExtra("category", "СССР");
startActivity(toSssr);
} else if (position == 3) {
Intent listActivity = new Intent(MainActivity.this, ArticleListActivity.class);
startActivity(listActivity);
}
}
});
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
.name("db.realm")
.build();
realm.setDefaultConfiguration(realmConfiguration);
realm = Realm.getDefaultInstance();
preferences = getApplicationContext().getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
firstLaunch = preferences.getBoolean("firstLaunch", false);
if (firstLaunch == false) {
firstLaunch();
}
}
public void firstLaunch() {
String[] arrayOfCatLists = {"00f.json", "01f.json", "02f.json", "10f.json"};
String[] arrayOfArticles = {"32.json", "34.json", "44.json", "51.json", "33.json", "40.json", "41.json", "42.json", "52.json", "45.json", "37.json", "46.json", "36.json", "54.json", "35.json", "43.json", "47.json", "50.json", "49.json", "48.json", "56.json", "58.json", "53.json", "59.json" , "55.json", "60.json", "61.json"};
String[] arrayOfUsssr = {"62.json", "74.json", "75.json", "76.json", "63.json", "78.json", "79.json", "77.json", "81.json", "80.json"};
for (int i = 0; i < arrayOfCatLists.length; i++) {
new GetArticlesListFromDisk(arrayOfCatLists[i], i).execute();
}
for (int i = 0; i < arrayOfArticles.length; i++) {
new GetArticleFromDisk(arrayOfArticles[i]).execute();
}
for (int i = 0; i < arrayOfUsssr.length; i++) {
new GetTanksFromDisk(arrayOfUsssr[i]).execute();
}
firstLaunch = true;
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("firstLaunch", firstLaunch);
editor.apply();
}
private class GetArticlesListFromDisk extends AsyncTask<String, Void, String> {
private String id;
private int index;
String[] arrayOfCatLists = {"00f.json", "01f.json", "02f.json"};
private GetArticlesListFromDisk(String id, int index) {
this.id = id;
this.index = index;
}
ProgressDialog pd = new ProgressDialog(MainActivity.this);
#Override
protected String doInBackground(String... params) {
String json = null;
try {
InputStream input = getApplicationContext().getAssets().open(id);
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setCancelable(false);
pd.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
pd.setMessage("Минуточку, загружаемся");
pd.show();
}
#Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
pd.dismiss();
JSONObject dataJsonObj = null;
String category = "";
try {
dataJsonObj = new JSONObject(strJson);
JSONArray listing = dataJsonObj.getJSONArray("listing");
for (int i = 0; i < listing.length(); i++) {
JSONObject object = listing.getJSONObject(i);
String id = object.getString("id");
String title = object.getString("title");
String subtitle = object.getString("subtitle");
String image = object.getString("image");
InputStream inputStream =null;
Bitmap bitmap = null;
try {
inputStream = getAssets().open(image);
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
Log.d("getArticleFromDisk", "Saved article " + title);
ImageStorage.saveToSdCard(bitmap, image, getApplicationContext());
if (index == 0) {
category = "Танковые сражения";
} else if (index == 1) {
category = "Справочник танкиста";
} else if (index == 2) {
category = "Танковые асы";
} else if (index == 3) {
category = "СССР";
} else if (index == 4) {
category = "Германия";
} else if (index == 5) {
category = "США";
} else if (index == 6) {
category = "Великобритания";
}
realm.beginTransaction();
ArticleList articleList = realm.createObject(ArticleList.class);
articleList.setId(id);
articleList.setTitle(title);
articleList.setSubtitle(subtitle);
articleList.setImage(image);
articleList.setCategory(category);
realm.commitTransaction();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class GetArticleFromDisk extends AsyncTask<String, Void, String> {
private String id;
private int categoryIndex;
private GetArticleFromDisk(String id) {
this.id = id;
}
public String LOG_TAG = "GetArticleFromDisk";
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String resultJson = "";
ProgressDialog pd = new ProgressDialog(MainActivity.this);
#Override
protected String doInBackground(String... params) {
String json = null;
try {
InputStream input = getApplicationContext().getAssets().open(id);
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setCancelable(false);
pd.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
pd.setMessage("Минуточку, загружаемся");
pd.show();
}
#Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
pd.dismiss();
JSONObject dataJsonObj = null;
String category = "";
try {
dataJsonObj = new JSONObject(strJson);
JSONArray listing = dataJsonObj.getJSONArray("article");
for (int i = 0; i < listing.length(); i++) {
JSONObject object = listing.getJSONObject(i);
String id = object.getString("id");
String title = object.getString("title");
String subtitle = object.getString("subtitle");
String body = object.getString("body");
String hash = object.getString("content_version");
Log.d(LOG_TAG, "Saved article with id " + id);
realm.beginTransaction();
Article article = realm.createObject(Article.class);
article.setId(id);
article.setTitle(title);
article.setSubtitle(subtitle);
article.setBody(body);
article.setHash(hash);
realm.commitTransaction();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class GetTanksFromDisk extends AsyncTask<String, Void, Tank> {
private String id;
private int categoryIndex;
private GetTanksFromDisk(String id) {
this.id = id;
}
public String LOG_TAG = "GetTankFromDisk";
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String resultJson = "";
ProgressDialog pd = new ProgressDialog(MainActivity.this);
Tank tank = new Tank();
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d(LOG_TAG, "Entered preExecute");
pd.setCancelable(false);
pd.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
pd.setMessage("Минуточку, загружаемся");
pd.show();
}
#Override
protected Tank doInBackground(String... params) {
String json = null;
try {
InputStream input = getApplicationContext().getAssets().open(id);
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
JSONObject dataJsonObj = null;
String category = "";
try {
dataJsonObj = new JSONObject(json);
JSONArray listing = dataJsonObj.getJSONArray("article");
for (int i = 0; i < listing.length(); i++) {
JSONObject object = listing.getJSONObject(i);
String id = object.getString("id");
String title = object.getString("title");
JSONArray signatures = object.getJSONArray("signatures");
ArrayList<String> signatures_list = new ArrayList<String>();
for (int j = 0; j < signatures.length(); j++) {
signatures_list.add(signatures.get(j).toString());
}
String signatures_string = Joiner.on(",").join(signatures_list);
String body = object.getString("body");
String construction = object.getString("construction");
String modification = object.getString("modification");
String ttx = object.getString("ttx");
JSONObject images = object.getJSONObject("images");
JSONArray tank_slider = images.getJSONArray("tank_slider");
ArrayList<String> tank_slider_list = new ArrayList<String>();
for (int k = 0; k < tank_slider.length(); k++) {
InputStream inputStream =null;
Bitmap bitmap = null;
try {
inputStream = getAssets().open(tank_slider.getString(k));
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
ImageStorage.saveToSdCard(bitmap, tank_slider.getString(k), getApplicationContext());
tank_slider_list.add(tank_slider.getString(k));
}
String tank_slider_string = Joiner.on(",").join(tank_slider_list);
String hash = object.getString("content_version");
Log.d(LOG_TAG, "Imported from assets tank with id " + id);
tank.setId(id);
tank.setTitle(title);
tank.setSignatures(signatures_string);
tank.setBody(body);
tank.setConstruction(construction);
tank.setModification(modification);
tank.setTtx(ttx);
tank.setTank_slider(tank_slider_string);
tank.setHash(hash);
}
} catch (JSONException e) {
e.printStackTrace();
}
return tank;
}
#Override
protected void onPostExecute(Tank tank) {
super.onPostExecute(tank);
pd.dismiss();
realm.beginTransaction();
Tank newTank = realm.createObject(Tank.class);
newTank.setId(tank.getId());
newTank.setTitle(tank.getTitle());
newTank.setSignatures(tank.getSignatures());
newTank.setBody(tank.getBody());
newTank.setConstruction(tank.getConstruction());
newTank.setModification(tank.getModification());
newTank.setTtx(tank.getTtx());
newTank.setTank_slider(tank.getTank_slider());
newTank.setHash(tank.getHash());
realm.commitTransaction();
}
}
What Im I doing wrong ?

Send data to Fragment(Not Activity) from AsyncTask

I have taken the jsonresponse array data to the onPostExecute, now i want to pass the jsonresponse to main fragment. but when I try it gives an error as shown in the image. I have follow this answer(android asynctask sending callbacks to ui), any help will be great.
asynctask class
public class PizzaMenuAsyncTask extends AsyncTask<String, Integer, JSONArray> {
private OnTaskCompleted listener;
private JSONArray responseJson = null;
private Context contxt;
private Activity activity;
String email;
public PizzaMenuAsyncTask(Context context) {
// API = apiURL;
this.contxt = context;
}
public PizzaMenuAsyncTask(OnTaskCompleted listener) {
this.listener = listener;
}
// async task to accept string array from context array
#Override
protected JSONArray doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the email and password
try {
path = "xxxxxxxxx/ItemService.svc/ProductDetails";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("CetegoryCode"), "PIZ");
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONArray(response);
// System.out.println("*****JARRAY*****" + responseJson.length());
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONArray(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONArray result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
listener.onTaskCompleted(responseJson);
}
}
I have this interface
public interface OnTaskCompleted {
void onTaskCompleted(JSONArray responseJson);
}
fragment class
public class PizzaFragment extends ListFragment implements OnTaskCompleted {
private QuickReturnListView mListView;
private TextView mQuickReturnView;
private TextView mQuickReturnView1;
private TextView mQuickReturnView2;
private int mQuickReturnHeight;
private static final int STATE_ONSCREEN = 0;
private static final int STATE_OFFSCREEN = 1;
private static final int STATE_RETURNING = 2;
private int mState = STATE_ONSCREEN;
private int mScrollY;
private int mMinRawY = 0;
private TranslateAnimation anim;
GridView grid;
String[] web = { "Pizza1", "Pizza2", "Pizza3", "Pizza4", "Pizza5",
"Pizza6", "Pizza7", "Pizza8", "Pizza9", "Pizza10", "Pizza11",
"Pizza12", "Pizza13", "Pizza14", "Pizza15"
};
int[] imageId = { R.drawable.image1, R.drawable.image2, R.drawable.image3,
R.drawable.image4, R.drawable.image5, R.drawable.image6,
R.drawable.image7, R.drawable.image8, R.drawable.image9,
R.drawable.image10, R.drawable.image11, R.drawable.image12,
R.drawable.image13, R.drawable.image14, R.drawable.image15
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.menu_grid_main, container, false);
new PizzaMenuAsyncTask(getActivity()).execute();
mQuickReturnView = (TextView) view.findViewById(R.id.footer);
mQuickReturnView1 = (TextView) view.findViewById(R.id.footer1);
mQuickReturnView2 = (TextView) view.findViewById(R.id.footer2);
CustomGrid adapter = new CustomGrid(getActivity(), web, imageId);
grid = (GridView) view.findViewById(R.id.grid);
grid.setAdapter(adapter);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mListView = (QuickReturnListView) getListView();
String[] array = new String[] { "Android1", "Android2", "Android",
"Android", "Android", "Android", "Android", "Android",
"Android", "Android", "Android", "Android", "Android",
"Android", "Android", "Android5" };
// setListAdapter(new ArrayAdapter<String>(getActivity(),
// R.layout.menu_list_item, R.id.text1, array));
mListView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
mQuickReturnHeight = mQuickReturnView.getHeight();
mQuickReturnHeight = mQuickReturnView1.getHeight();
mQuickReturnHeight = mQuickReturnView2.getHeight();
mListView.computeScroll();
// mListView.computeScrollY();
}
});
mListView.setOnScrollListener(new OnScrollListener() {
#SuppressLint("NewApi")
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
mScrollY = 0;
int translationY = 0;
if (mListView.scrollYIsComputed()) {
mScrollY = mListView.getComputedScrollY();
}
int rawY = mScrollY;
switch (mState) {
case STATE_OFFSCREEN:
if (rawY >= mMinRawY) {
mMinRawY = rawY;
} else {
mState = STATE_RETURNING;
}
translationY = rawY;
break;
case STATE_ONSCREEN:
if (rawY > mQuickReturnHeight) {
mState = STATE_OFFSCREEN;
mMinRawY = rawY;
}
translationY = rawY;
break;
case STATE_RETURNING:
translationY = (rawY - mMinRawY) + mQuickReturnHeight;
System.out.println(translationY);
if (translationY < 0) {
translationY = 0;
mMinRawY = rawY + mQuickReturnHeight;
}
if (rawY == 0) {
mState = STATE_ONSCREEN;
translationY = 0;
}
if (translationY > mQuickReturnHeight) {
mState = STATE_OFFSCREEN;
mMinRawY = rawY;
}
break;
}
/** this can be used if the build is below honeycomb **/
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB) {
anim = new TranslateAnimation(0, 0, translationY,
translationY);
anim.setFillAfter(true);
anim.setDuration(0);
mQuickReturnView.startAnimation(anim);
mQuickReturnView1.startAnimation(anim);
mQuickReturnView2.startAnimation(anim);
} else {
mQuickReturnView.setTranslationY(translationY);
mQuickReturnView1.setTranslationY(translationY);
mQuickReturnView2.setTranslationY(translationY);
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
});
}
#Override
public void onTaskCompleted(JSONArray responseJson) {
// TODO Auto-generated method stub
try {
for (int n = 0; n < responseJson.length(); n++) {
JSONObject object = responseJson.getJSONObject(n);
if ((object.getString("MainCategoryID")).equals("1")) {
Log.i("MainCategoryID ", object.getString("ItemCode"));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
this is the error i get when i run the application. what have I missed in this
Notice that you have two constructor, if you call the first one to get an instance of your PizzaMenuAsyncTask, your listener will be null when you call listener.onTaskCompleted(result); in your onPostExecute(JSONArray result) method.
Update:
The solution is changing your first constructor as following:
public PizzaMenuAsyncTask(Context context, OnTaskCompleted listener) {
// API = apiURL;
this.contxt = context;
this.listener = listener;
}
And change the line:
new PizzaMenuAsyncTask(getActivity()).execute();
to:
new PizzaMenuAsyncTask(getActivity(), this).execute();
It should be
#Override
protected void onPostExecute(JSONArray result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
listener.onTaskCompleted(result);
}
The JSONArray being returned by the doInBackground is passed to the onPostExecute as its JSONArray result.

Stop creating fragmnet view until i have parsed all data from Json.

I receive a null pointer exeception when trying to populate the interface beacuse I have no data in my instance object.
I am using a login button and call a service, i receive a json and after I parse it i have a status handler...login ok... Here I want to start an asynk task to get some photo data
public void StatusHandlerLogin(String status, Activity currentActivity) {
if (status.equals("0")) {
new GetPhotoDataTask(currentActivity).execute();
Intent intent = new Intent(currentActivity,
NavigationActivity.class);
currentActivity.startActivity(intent);
}
//}
The asynk task is like this
public class GetPhotoDataTask extends
AsyncTask<Void, Void, List<PhotoData>> {
Activity activity;
public GetPhotoDataTask(Activity activity) {
this.activity = activity;
}
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
Log.d("GetPhotoDataTask onPreExecute",
"GetPhotoDataTask onPreExecute");
super.onPreExecute();
progressDialog = ProgressDialog.show(activity, "Preluare Date",
"Va rugam asteptati!");
}
#Override
protected List<PhotoData> doInBackground(Void... params) {
Log.d("GetPhotoDataTask doInBackground",
"GetPhotoDataTask doInBackground");
MyStyleApi myStyleApi = new MyStyleApi();
List<PhotoData> photoData = null;
try {
photoData = myStyleApi.getPhotoDataWithDispatch();
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
List<String> photoStr = new ArrayList<String>();
for (int i = 0; i < photoData.size(); i++) {
photoStr.add(photoData.get(i).getPhotoURL());
}
String[] photoUrls = new String[photoStr.size()];
photoUrls = photoStr.toArray(photoUrls);
for (int i = 0; i < photoUrls.length; i++) {
if (photoUrls[i].contains("\"")) {
photoUrls[i] = photoUrls[i].replace("\"", "");
}
}
AppManager.getInstance().setphotoUrls(photoUrls);
List<PhotoData> photoDataS = AppManager.getInstance().setPhotoData(
photoData);
return photoData;
}
protected void onProgressUpdate(Integer... percent) {
progressDialog = ProgressDialog.show(activity, "Preluare Date",
"Va rugam asteptati!");
}
protected void onPostExecute(List<PhotoData> photoData) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
on do in background i have a method that call other service
get PhotoData with userId as param
public List<PhotoData> getPhotoDataWithDispatch() throws JSONException,
ClientProtocolException, IOException {
Log.d("getPhotoDataWithDispatch ", "getPhotoDataWithDispatch ");
UserData data = AppManager.getInstance().getUserData();
String userID = data.getUserID();
if (userID.contains("\"")) {
userID = userID.replace("\"", "");
}
Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("userID", userID);
JsonArray response = WebServiceApi.PostToServiceWithStringResponse(
"images/get_images_data", params);
List<PhotoData> photoDataList = new ArrayList<PhotoData>();
if (response != null) {
photoDataList = parseJsonArrayForFotoData(response);
}
return photoDataList;
}
and if response is not null i parse it
public static List<PhotoData> parseJsonArrayForFotoData(JsonArray jsonArray) {
List<PhotoData> photoDataList = new ArrayList<PhotoData>();
for (int i = 0; i < jsonArray.size(); i++) {
Log.d("getPhotoDataWithDispatch ", "getPhotoDataWithDispatch ");
JsonElement photoID = ((JsonObject) jsonArray.get(i)).get("pozaID");
JsonElement photoUrl = ((JsonObject) jsonArray.get(i))
.get("pozaURL");
JsonElement thumbURL = ((JsonObject) jsonArray.get(i))
.get("thumbURL");
JsonElement tags = ((JsonObject) jsonArray.get(i)).get("tags");
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(tags.toString()).getAsJsonArray();
List<Tags> tagsList = new ArrayList<Tags>();
for (int j = 0; j < array.size(); j++) {
JsonElement tagId = ((JsonObject) array.get(j)).get("tagID");
JsonElement coordX = ((JsonObject) array.get(j)).get("coordX");
JsonElement coordY = ((JsonObject) array.get(j)).get("coordY");
JsonElement productId = ((JsonObject) array.get(j))
.get("productID");
Tags tagPData = new Tags(tagId.toString(), coordX.toString(),
coordY.toString(), productId.toString());
tagsList.add(tagPData);
}
PhotoData photoData = new PhotoData(photoID.toString(),
photoUrl.toString(), thumbURL.toString(), null, tagsList);
photoDataList.add(photoData);
}
return photoDataList;
}
ok in GetPhotoDataTaskFb do in background i set the instance of the photos object
AppManager.getInstance().setphotoUrls(photoUrls);
and in fragmnet
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.ac_image_pager, container,
false);
// Dummy code
if (counter == 0) {
for (int i = 0; i <= 20; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
counter++;
String[] imageUrls = AppManager.getInstance().getphotoUrls();
//here is where i get the null.. i tried some dummy code to delay and receive data but it is not working
How can I manage to stop create view until all data is parsed?

my llistview load multiple time same data on screen

my listview repeat data some time which click on buttons fastly what do i do please help me see this images http://imgur.com/ed5uDtp after some time is show like this http://imgur.com/jAt4yn7
is show correctly data on listview but some time when click fastly buttons is load duplicate data how i will fixed this? plaa help me
public class thirdstep extends Activity implements View.OnClickListener {
int count = 0;
String id;
String title;
String tmpString, finaldate;
String valll;
ProgressBar prgLoading;
TextView txtAlert;
int IOConnect = 0;
String mVal9;
Button e01;
Button e02;
Button e03;
Button e04;
Button e05;
String SelectMenuAPI;
String url;
String URL;
String URL2, URL3, URL4;
String menu_title;
JSONArray school;
ListView listCategory;
String status;
String School_ID;
String Menu_ID;
String School_name;
String Meal_groupid;
String _response;
String _response2;
String CategoryAPI;
String SelectMenuAPI2;
TextView menu_nametxt;
thirdstepAdapter cla;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> school_name = new ArrayList<String>();
static ArrayList<String> menu_name = new ArrayList<String>();
static ArrayList<String> dish_name = new ArrayList<String>();
static ArrayList<String> dish_ID = new ArrayList<String>();
static ArrayList<String> day = new ArrayList<String>();
static ArrayList<Long> Vacation_ID = new ArrayList<Long>();
static ArrayList<String> Vacation_name = new ArrayList<String>();
static ArrayList<String> Vacation_Date = new ArrayList<String>();
String mydate;
String mode;
String s2;
ArrayList<String> myList,myList2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list2);
listCategory = (ListView) findViewById(R.id.thirdscreenlist);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
e01 = (Button) findViewById(R.id.e01);
e02 = (Button) findViewById(R.id.e02);
e03 = (Button) findViewById(R.id.e03);
e04 = (Button) findViewById(R.id.e04);
e05 = (Button) findViewById(R.id.e05);
e01.setOnClickListener(this);
e02.setOnClickListener(this);
e03.setOnClickListener(this);
e04.setOnClickListener(this);
e05.setOnClickListener(this);
cla = new thirdstepAdapter(thirdstep.this);
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(thirdstep.this, fifthscreen.class);
startActivity(intent);
}
});
new getDataTask().execute();
}
void clearData() {
Category_ID.clear();
school_name.clear();
menu_name.clear();
dish_name.clear();
dish_ID.clear();
day.clear();
Vacation_ID.clear();
Vacation_name.clear();
Vacation_Date.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void> {
getDataTask() {
if (!prgLoading.isShown()) {
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
prgLoading.setVisibility(8);
if ((Category_ID.size() > 0) || IOConnect == 0) {
listCategory.setAdapter(cla);
cla.notifyDataSetChanged() ;
listCategory.invalidateViews();
} else {
txtAlert.setVisibility(0);
menu_nametxt.setText("");
listCategory.setVisibility(View.GONE);
}
}
}
public void parseJSONData() {
clearData();
SelectMenuAPI="";
SelectMenuAPI = Utils.Schoolmenu +Menu_ID+"&sid="+School_ID+"&lid=" +
SchoolLevelId+"&mealid="+Meal_groupid;
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
Log.i("url",""+URL2);
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
HttpEntity resEntity = response.getEntity();
_response=EntityUtils.toString(resEntity);
JSONObject json5 = new JSONObject(_response);
status = json5.getString("status");
if (status.equals("1")) {
JSONArray school5 = json5.getJSONArray("data");
}
}
else {
}
SelectMenuAPI2="";
SelectMenuAPI2 = Utils.SchoolVacation+mVal9;
// clearData();
URL3 = SelectMenuAPI2;
URL4 = URL3.replace(" ", "%20");
Log.i("url",""+URL4);
JSONObject json2 = new JSONObject(_response);
status = json2.getString("status");
if (status.equals("1")) {
if (Vacation_Date.contains(mydate)) {
message = "holiday";
JSONObject json4 = new JSONObject(str2);
status = json4.getString("status");
if (status.equals("1")) {
school = json4.getJSONArray("data");
for (int k = 0; k < school.length(); k++) {
JSONObject jb = (JSONObject) school .getJSONObject(k);
Vacation_ID.add((long) k);
String[] mVal = new String[school.length()];
if(school.getJSONObject(k).getString("date").equals(mydate))
{
mVal[k] = school.getJSONObject(k).getString("title");
mVal3 = mVal[k];
}
}
}
} else {
JSONArray school = json2.getJSONArray("data");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
if (object.getString("Schedule").equals("weekly")) {
if (object.getString("day").equals(Todayday)) {
Category_ID.add((long) i);
school_name
.add(object.getString("school_name"));
dish_ID.add(object.getString("dish_id"));
dish_name.add(object.getString("dish_name"));
menu_name.add(object.getString("menu_title"));
day.add(object.getString("day"));
count = count + 1;
String[] mVal = new String[school.length()];
for (int k = 0; k < school.length(); k++) {
mVal[k] = school.getJSONObject(k).getString("menu_title");
message = "weekly";
mVal2 = mVal[0];
}
}
if(dish_name != null &&
!dish_name.isEmpty())
{
message = "weekly";
}
else {
message = "error";
}
}
else {
message = "error";
}
}
}
}
else {
message = "error";
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.e01:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e02:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e03:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e04:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e05:
listCategory.setVisibility(View.GONE);
// do stuff;
new getDataTask().execute();
break;
}
}
}
You are calling asynctask twice and that is making all parts twice, I mean you are cleaning twice before filling and fill arrays twice. You should control your async task for do not execute before last one finished.
1-Create a boolean value
2-Put condition on onClicks:
if(yourBoolean){
new getDataTask().execute();}
3- in your asyncTask's onPreExecute make yourBoolean=false and onPostExecute make yourBoolean=true again.
Try this..
Just remove the below line and try it..
listCategory.invalidateViews();
because
ListView.invalidateViews() is used to tell the ListView to invalidate all its child item views (redraw them). Note that there not need to be an equal number of views than items. That's because a ListView recycles its item views and moves them around the screen in a smart way while you scroll.

Categories

Resources