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.
Related
I have an app that connects to server sends sql request and get JSON answer as JsonArray.
Its Asynktask in seperate class (HTTPRequest.java is my AsyncTask class, Responce.java its my callback interface class) and it works correct.
when I use it in OrderActivity.java like below
#Override //my interface class function
public void onPostExecute(JSONArray Result) {
load(Result);
}
private void load(JSONArray json) {
for(int i=0;i<json.length();i++){
try {
JSONObject jo = json.getJSONObject(i);
Product p = new Product(
jo.getInt("ID"),
jo.getInt("parent"),
jo.getInt("category"),
jo.getString("Item"),
jo.getDouble("Price")
);
products.add(p);
} catch (JSONException e) {
e.printStackTrace();
}
}
it does work and fills product with data, but when I assign to my class variable JSONArray json
JSONArray json = new JSONArray;
.
.
.
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
json is null
//HTTPRequest.java
public class HTTPRequest extends AsyncTask<String, Void, Integer> {
private Context context;
private Responce responce;
JSONArray json;
public HTTPRequest(Context context){
this.context = context;
responce = (Responce)context;
}
#Override
protected Integer doInBackground(String... params) {
OutputStream output;
InputStream inputStream = null;
HttpURLConnection connection = null;
String charset = "UTF-8";
Integer result = 0;
try {
URL uri = new URL(params[0]);
connection = (HttpURLConnection) uri.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "text/plain; charset=" + charset);
output = connection.getOutputStream();
output.write(params[1].getBytes(charset));
output.close();
int statusCode = connection.getResponseCode();
if (statusCode == 200) {
inputStream = new BufferedInputStream(connection.getInputStream());
json = new JSONArray(getJSON(inputStream));
result = 1;
}
} catch (Exception e) {
e.getLocalizedMessage();
}
return result;
}
#Override
protected void onPostExecute(Integer i) {
super.onPostExecute(i);
if(i == 1) {
responce.onPostExecute(json);
} else {
responce.onPostExecute(null);
}
}
private String getJSON(InputStream inputStream) throws IOException, JSONException {
StringBuffer stringBuffer = new StringBuffer();
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = null;
while((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line.toString());
}
result = stringBuffer.toString();
if(null!=inputStream){
inputStream.close();
}
return result;
}
}
//Responce.java
public interface Responce {
public void onPostExecute(JSONArray Result);
}
//OrderActivity.java
public class OrderActivity extends Activity implements Responce{
ArrayList<Product> products = new ArrayList<Product>();
ProductAdapter productAdapter;
OrderItemAdapter orderItemAdapter;
ListView orderlist;
JSONArray ja;
Button btnBack;
Button btnTakeOrder;
ListView picklist;
HTTPRequest httpRequest;
String url = "http://192.168.3.125:8888/data/";
String query = "select * from vwitems order by category desc";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
orderlist =(ListView)findViewById(R.id.orderlist);
orderItemAdapter = new OrderItemAdapter(OrderActivity.this);
btnBack = (Button)findViewById(R.id.btnBack);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productAdapter.filter(0);
}
});
btnTakeOrder = (Button)findViewById(R.id.btnTakeOrder);
btnTakeOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer oid = 0;
Order order = new Order(OrderActivity.this);
oid = order.NewOrder(1, 2, 3);
Toast.makeText(OrderActivity.this," " + order.getCount(), LENGTH_SHORT).show();
}
});
orderlist.setAdapter(orderItemAdapter);
picklist = (ListView) findViewById(R.id.picklist);
picklist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int pid = 0;
if (productAdapter.getItem(position).isCategory()) {
pid = productAdapter.getItem(position).getId();
productAdapter.filter(pid);
} else {
OrderItem oi = new OrderItem();
oi.setItemId(productAdapter.getItem(position).getId());
oi.setItem(productAdapter.getItem(position).getItem());
oi.setPrice(productAdapter.getItem(position).getPrice());
search(oi);
}
}
});
httpRequest = new HTTPRequest(this);
httpRequest.execute(url, query);
}
private boolean search(OrderItem oi){
int size = orderItemAdapter.getCount();
int i = 0;
if(size != 0)
for(OrderItem o : orderItemAdapter.getAll()){
if(o.getItemId() == oi.getItemId()){
orderItemAdapter.getItem(i).setQuantity(orderItemAdapter.getItem(i).getQuantity() + 1);
orderItemAdapter.notifyDataSetChanged();
return true;
}
i++;
}
orderItemAdapter.addItem(oi);
orderItemAdapter.notifyDataSetChanged();
return false;
}
private void load(JSONArray json) {
for(int i=0;i<json.length();i++){
try {
JSONObject jo = json.getJSONObject(i);
Product p = new Product(
jo.getInt("ID"),
jo.getInt("parent"),
jo.getInt("category"),
jo.getString("Item"),
jo.getDouble("Price")
);
products.add(p);
} catch (JSONException e) {
e.printStackTrace();
}
}
productAdapter = new ProductAdapter(OrderActivity.this, products);
picklist.setAdapter(productAdapter);
productAdapter.filter(0);
}
#Override
public void onPostExecute(JSONArray Result) {
load(Result);
}
/*
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
**/
}
sorry i forgot include this one
//Order.java
public class Order implements Responce{
private Context context;
private JSONArray json = new JSONArray();
private HTTPRequest httpRequest;
private int OrderID;
private Date OrderDate;
private int OrderTable;
private int Waiter;
private byte OrderStatus;
private List<OrderItem> orderItems;
public Order(Context context){
this.context = context;
}
//some code here...
public Integer NewOrder(Integer guests, Integer waiter, Integer ordertable){
String query = "insert into orders(orderdate, guests, waiter, ordertable) VALUES(NOW()," + guests + ", " + waiter + ", " + ordertable + "); SELECT LAST_INSERT_ID() as ID;";
Integer result = 0;
Connect(query);
try {
JSONObject jo = json.getJSONObject(0);
result = jo.getInt("ID");
} catch (JSONException e) {
e.printStackTrace();
}
return result; //here i got 0 if i init result to 0, null or what ever i init my
}
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
private void Connect (String query){
httpRequest = new HTTPRequest(context);
httpRequest.execute("http://192.168.3.125:8888/data/", query);
}
}
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.
Hi I don't know asking proper question or not but i want to develop Like Comment on Facebook post, Update comment and Delete Comment.
When i will add comment it will send request to server and it will give response with new values to fill in listadapter and that change may appear on my listview after click on enter or add button, and on delete it will send request to server and in response fill my listAdapter. and change may appear on my listview without refreshing listview. how can i perform this operation .
Thank You in Adavance.
Here is my Class.
public class CommmentActivity extends Activity{
DatabaseHandler db = new DatabaseHandler(this);
List<CommentListInfo> list_CommentInfo = new ArrayList<CommentListInfo>();
List<String> SuggetionList;
AutoCompleteTextView aCompletView;
EditText etComment;
String strComment;
ArrayAdapter<String> mentionList;
ListCommentAdapter commentAdapter;
ImageView IvAddComment;
ListView CommentList;
SessionCreator m_session;
boolean m = false;
boolean mBuzy;
int FirstPosition;
int ItemCounted;
int CurrentScrollState;
int TotalItemCount;
String UserId;
String VidoId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.commentvideo_main);
SuggetionList = new ArrayList<String>();
String Curl = GlobalMethod.TokenGenerator() + "&action=getCommentsVideo";
Intent data = getIntent();
UserId = data.getStringExtra("userId");
VidoId = data.getStringExtra("videoId");
init();
String strfriendsSyncDate = m_session.getfriendsSyncDate();
Log.d("mData", strfriendsSyncDate);
new CommentsDetail().execute(UserId,VidoId,strfriendsSyncDate,Curl,"1");
commentAdapter = new ListCommentAdapter(getApplicationContext(), list_CommentInfo);
CommentList.setAdapter(commentAdapter);
CommentList.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
switch (scrollState) {
case OnScrollListener.SCROLL_STATE_IDLE:{
commentAdapter.notifyDataSetChanged();
//ManipulateVisibleView(view);
break;
}
case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
{
mBuzy = true;
break;
}
case OnScrollListener.SCROLL_STATE_FLING:{
mBuzy = true;
break;
}
default:
break;
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
FirstPosition = firstVisibleItem;
ItemCounted = visibleItemCount;
TotalItemCount = totalItemCount;
int LastPosition = view.getLastVisiblePosition();
Log.d("First Position", ""+FirstPosition);
Log.d("ItemCountes",""+ItemCounted);
Log.d("totalItemCount",""+TotalItemCount);
Log.d("LastPosition",""+LastPosition);
if(visibleItemCount!=0 && ((firstVisibleItem+visibleItemCount)>=(totalItemCount))){
Log.d("mCalled", "call");
}
isScrollCompleted();
}
});
IvAddComment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
strComment = etComment.getText().toString();
etComment.getText().clear();
String strUrl = GlobalMethod.TokenGenerator() + "&action=addCommentsVideo";
new CommentsDetail().execute(UserId,VidoId,strComment,strUrl,"0");
commentAdapter.notifyDataSetChanged();
}
});
}
private void isScrollCompleted(){
if(this.ItemCounted >0 && this.CurrentScrollState == OnScrollListener.SCROLL_STATE_IDLE){
Log.d("ItemCounted",""+ItemCounted);
Log.d("CurrentScrollState",""+CurrentScrollState);
}
}
private void init() {
// TODO Auto-generated method stub
m_session = new SessionCreator(getApplicationContext());
etComment = (EditText)findViewById(R.id.etComments);
CommentList = (ListView)findViewById(R.id.lvLatestComments);
IvAddComment = (ImageView)findViewById(R.id.addComment);
}
public class CommentsDetail extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ServiceHandler serviceClient;
String mJsonString;
try{
String userId = (String)params[0];
String vId = (String)params[1];
if(params[4].equals("0")){
String comment = (String)params[2];
String strUrl = (String)params[3];
List<NameValuePair> paramsNameValuePairs = new ArrayList<NameValuePair>();
paramsNameValuePairs.add(new BasicNameValuePair("userId", userId));
paramsNameValuePairs.add(new BasicNameValuePair("videoId", vId));
paramsNameValuePairs.add(new BasicNameValuePair("commentText", comment));
serviceClient = new ServiceHandler();
mJsonString = serviceClient.makeServiceCall(strUrl,
ServiceHandler.POST, paramsNameValuePairs);
Log.i("---->>>>>>>>>>", paramsNameValuePairs + "");
}else{
String syncdate = (String)params[2];
String strUrl = (String)params[3];
List<NameValuePair> paramsNameValuePairs = new ArrayList<NameValuePair>();
paramsNameValuePairs.add(new BasicNameValuePair("userId", userId));
paramsNameValuePairs.add(new BasicNameValuePair("videoId", vId));
paramsNameValuePairs.add(new BasicNameValuePair("friendsSyncDate", syncdate));
serviceClient = new ServiceHandler();
mJsonString = serviceClient.makeServiceCall(strUrl,
ServiceHandler.POST, paramsNameValuePairs);
Log.i("---->>>>>>>>>>", paramsNameValuePairs + "");
}
Log.d("Response Json-----------------------",mJsonString );
return mJsonString;
}catch (Exception e) {
e.getStackTrace();
}
return null;
}
#SuppressWarnings({ "unchecked", "unchecked", "unchecked" })
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try{
if (result != null) {
JSONObject responsJsonObj = new JSONObject(result);
JSONObject jsonObj = (JSONObject) responsJsonObj
.optJSONObject("data");
try {
String str = jsonObj.getString("error");
if ( str != null || str.length() != 0) {
// error
//Toast.makeText(NewsfeedActivity.this, jsonObj.getString("error"),Toast.LENGTH_LONG).show();
return;
}
} catch (JSONException je) {
Log.d("jex ------>", "" + je.getMessage());
try {
String str = jsonObj.getString("message");
Log.d("message=", "" + str);
if ( str != null || str.length() != 0) {
// VALID RESPONSE, NOW PARSE IT
if (jsonObj.has("comments")) {
JSONArray colArray = jsonObj.getJSONArray("comments");
Log.d("Colunm Array", ""+colArray);
int nComments = colArray.length();
Log.d("# comments", "" + nComments);
for(int i=0; i<nComments; i++){
JSONObject obj = colArray.getJSONObject(i);
Gson Comments = new Gson();
String strComments = Comments.toJson(obj);
Log.d("# obj=", "" + obj.toString());
CommentListInfo cmtInfo = new CommentListInfo();
cmtInfo.c_userId = obj.getString("userId");
cmtInfo.c_name = obj.getString("name");
cmtInfo.DateAdded = obj.getString("dateAdded");
cmtInfo.CommentId = obj.getString("commentId");
cmtInfo.CommentText = obj.getString("text");
cmtInfo.ImageUrl = obj.getString("imageLink");
list_CommentInfo.add(cmtInfo);
}
}
}
if ( str != null || str.length() != 0) {
// VALID RESPONSE, NOW PARSE IT
if (jsonObj.has("addPosition")) {
Log.d("# obj=", "" + jsonObj.toString());
Log.d("Add Position", jsonObj.getString("addPosition"));
}
}
//
if ( str != null || str.length() != 0) {
// VALID RESPONSE, NOW PARSE IT
if (jsonObj.has("friendsSyncDate")) {
Log.d("# friendsDeleted", "" + jsonObj);
Log.d("# obj=", "" + jsonObj.toString());
String myString = m_session.getfriendsSyncDate();
Log.d("myString", myString);
m_session.putfriendsSyncDate(jsonObj.getString("friendsSyncDate"));
Log.d("Sync Date "," "+jsonObj.getString("friendsSyncDate"));
}
}
} catch (JSONException je2) {
je2.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Here is my Adapter Class.
public class ListCommentAdapter extends BaseAdapter{
private Context mContext;
private List<CommentListInfo> CommentsInfo;
private LayoutInflater inflater;
private String szUserId;
private String szVideoID;
private boolean mBuzy = false;
public ListCommentAdapter(Context context, List<CommentListInfo> cmtInfo) {
// TODO Auto-generated constructor stub
mContext = context;
CommentsInfo = cmtInfo;
AppData mmap = (AppData)this.mContext.getApplicationContext();
szUserId = mmap.getUserId();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return CommentsInfo.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return CommentsInfo.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder = new Holder();
CommentListInfo c = CommentsInfo.get(position);
try{
Log.i("nUserId", c.c_userId);
Log.i("nName", c.c_name);
Log.i("nCommentId", c.CommentId);
Log.i("nCommnet", c.CommentText);
Log.i("nImageUrl",c.ImageUrl);
}catch(Exception e){
Log.e("Erore is",""+e);
}
try{
if(inflater==null){
inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if(convertView==null){
convertView = inflater.inflate(R.layout.comment_list_item, null);
holder.ciProfileImage = (CircleImageView)convertView.findViewById(R.id.civCFLeftPic);
holder.tvComments = (TextView)convertView.findViewById(R.id.tvCommentbox);
holder.tvCDate = (TextView)convertView.findViewById(R.id.tvCfNotifyDate);
holder.tvName = (TextView)convertView.findViewById(R.id.tvCommentName);
convertView.setTag(holder);
}else{
holder = (Holder)convertView.getTag();
}
if(!mBuzy){
RemoteImageLoader task = new RemoteImageLoader();
task.setImageView(holder.ciProfileImage);
task.execute(c.ImageUrl);
Log.d("ImagerUrl", c.ImageUrl);
if(c.ImageUrl!=null){
Picasso.with(mContext)
.load(R.drawable.world1)
.placeholder(R.drawable.world1)
.error(R.drawable.world1)
.into(holder.ciProfileImage);
}else{
Picasso.with(mContext)
.load(R.drawable.world1)
.placeholder(R.drawable.world1)
.error(R.drawable.world1)
.into(holder.ciProfileImage);
}
holder.tvComments.setText(c.CommentText);
holder.tvCDate.setText(c.DateAdded);
holder.tvName.setText(c.c_name);
holder.tvComments.setTag(null);
}else{
holder.tvComments.setText("Loading...");
holder.tvComments.setTag(this);
}
return convertView;
}catch(Exception e){
System.out.println("Error IS :- "+ e);
}
return convertView;
}
private static class Holder{
private TextView tvName,tvComments,tvCDate;
private CircleImageView ciProfileImage;
}
}
You might have solved this already but I was working on a different app in Java and came across something similar. Mine was a bit simpler because I am using a local database but ~same thing. In your CommmentActivity's onCreate method pull out the commentAdapter declaration and the CommentList.setOnScrollListener and put them in their own method. Then call your newly defined commentAdapter method in onCreate and after you parse through the response.
Something like this
public void myAdaperMethod(Context context, List<CommentListInfo> list_CommentInfo){
commentAdapter = new ListCommentAdapter(this, list_CommentInfo);
CommentList.setAdapter(commentAdapter);
CommentList.setOnScrollListener(new OnScrollListener(){...}
}
onCreate{
myAdapterMethod(...);
}
post{...}
get{myAdapterMethod(...);}
Hope that helps.
You just need to re-bind your control after the listadapter has the new dataset.
CommentList.DataBind();
I have a list where for each item i need to display a image. I am downloading the image from a link and displaying it but with i am facing problems to display them as the list gets populated by text first and then downloads the images later.Also another problem is whenever i go up or down in the list image disappears and download again so the images are gone when i come to to the top the list items
EventTask
public RecieveEventsTask(EventListActivity c, String critiria) {
appContext = c;
session = new SessionManager(appContext);
HashMap<String, String> user = session.getUserDetails();
String id = user.get(SessionManager.KEY_ID);
url = "http://bioscopebd.com/mobileappand/geteventlist?user_id=" + id;
}
public RecieveEventsTask(MyEventList c, String critiria) {
my_appContext = c;
session = new SessionManager(my_appContext);
HashMap<String, String> user = session.getUserDetails();
// id
String id = user.get(SessionManager.KEY_ID);
url = "http://bioscopebd.com/mobileappand/getmyeventlist?user_id=" + id;
}
protected void onPreExecute() {
dialog = new ProgressDialog(appContext == null ? my_appContext
: appContext);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Loading Events...");
dialog.show();
super.onPreExecute();
}
String filterResponseString(String r) {
return r.replace("\r\n", "");
}
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute(new HttpGet(url));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
responseString = filterResponseString(responseString);
} else {
// Closes the connection.
response.getEntity().getContent().close();
Utility.showMessage(appContext, "Cannot Connect To Internet");
}
} catch (Exception e) {
// TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
if (responseString != null) {
ArrayList<EventModel> eventsList = new ArrayList<EventModel>();
;
JSONArray jsonArr;
try {
// Log.v("json", responseString);
jsonArr = new JSONArray(responseString);
// jsonArr = events.getJSONArray("events");
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
EventModel event = new EventModel();
event.setTitle(jsonObj.getString("event_info_title"));
event.setDescription(jsonObj.getString("event_info_desc"));
// Log.v("logo data "+i, jsonObj.getString("image_logo"));
event.setBanner(jsonObj.getString("image_banner"));
event.setLogo(jsonObj.getString("image_logo"));
// event.setDescription(jsonObj.getString("event_info_desc"));
event.setCategory(jsonObj.getString("event_cat_title"));
event.setStartDate(jsonObj
.getString("event_info_start_date"));
event.setEndDate(jsonObj.getString("event_info_end_date"));
event.setStartTime(jsonObj
.getString("event_info_start_time"));
event.setEndTime(jsonObj.getString("event_info_end_time"));
event.setEventId(jsonObj.getString("event_info_id"));
event.setPhone(jsonObj.getString("event_info_mobile"));
event.setEmail(jsonObj.getString("event_info_email"));
event.setWeblink(jsonObj.getString("event_info_web"));
//
// logoDownloader = new ImageDownloader(event.getLogoBitmap());
// logoDownloader.execute(event.getLogo());
//
// bannerDownloader = new ImageDownloader(event.getBannerBitmap());
// bannerDownloader.execute(event.getBanner());
//
eventsList.add(event);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (appContext != null) {
appContext.showEventsDataLoaded(eventsList);
}
if (my_appContext != null) {
my_appContext.showEventsDataLoaded(eventsList);
}
// else
// {
// Log.v("check:","null");
//
// }
//
} else {
if(appContext!=null)
{
Utility.showMessage(appContext, "Cannot Connect To Internet");
}
else {
Utility.showMessage(my_appContext, "Cannot Connect To Internet");
}
//
}
super.onPostExecute(result);
// Do anything with response..
}
i get the image link in my setlogo and setbanner method
Adapter class
private final Activity context;
private final ArrayList<EventModel> events;
ImageDownloader imgDownloader;
Bitmap bitmap;
ImageView icon;
public EventsListAdapter(Activity context, ArrayList<EventModel> events) {
super(context, com.bioscope.R.layout.event_listitem, events);
this.context = context;
this.events = events;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(com.bioscope.R.layout.event_listitem,
null, true);
TextView title = (TextView) rowView
.findViewById(com.bioscope.R.id.title);
title.setText(events.get(position).getTitle());
TextView description = (TextView) rowView
.findViewById(com.bioscope.R.id.description);
description.setText(events.get(position).getDescription());
TextView category = (TextView) rowView
.findViewById(com.bioscope.R.id.category);
category.setText(events.get(position).getCategory());
Log.v("logo", events.get(position).getLogo());
icon = (ImageView) rowView
.findViewById(com.bioscope.R.id.event_icon);
//imgDownloader = new ImageDownloader(icon);
new LoadImage().execute(events.get(position).getLogo());
//ImageLoader.displayImage(events.get(position).getLogo().toString(), icon);
return rowView;
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// pDialog = new ProgressDialog(MainActivity.this);
// pDialog.setMessage("Loading Image ....");
// pDialog.show();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
icon.setImageBitmap(image);
//pDialog.dismiss();
}else{
//pDialog.dismiss();
// Toast.makeText(EventListActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
// icon.set
}
}
}
}
i am setting the image in my icon of list items
Activity class
private ListView list;
private MenuItem myActionMenuItem;
private EditText myActionEditText;
private TextView myActionTextView;
private AutoCompleteTextView actv;
// private Spinner spinner;
private Button liveEvent;
private ArrayList<EventModel> eventsList;
private static final String[] paths = { "All", "Favourites" };
private ArrayList<String> array_sort;
int textlength = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.bioscope.R.layout.eventlist);
RecieveEventsTask task = new RecieveEventsTask(this, "all");
task.execute();
}
public void showEventsDataLoaded(ArrayList<EventModel> eventsList) {
this.eventsList = eventsList;
// for(EventModel e:eventsList )
// {
// Log.v("title", e.getTitle());
// }
EventsListAdapter adapter = new EventsListAdapter(
EventListActivity.this, eventsList);
list = (ListView) findViewById(com.bioscope.R.id.listView1);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// Toast.makeText(EventList.this, "You Clicked an item ",
// Toast.LENGTH_SHORT).show();
showEventInformaion(position);
}
});
// RecieveCategoriesTask task = new RecieveCategoriesTask(this, "all");
// task.execute();
liveEvent = (Button) findViewById(R.id.liveEvent);
liveEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(EventListActivity.this,
LiveEventActivity.class);
startActivity(i);
}
});
}
public void showCategoryListDataLoaded(String response) {
Utility.showMessage(this, response);
}
Then in my activity i called the async reciver task to load all the data along with link and gave set them in my model class.
You haveto set ResponseCache in your Main class while downloading bitmap:
Like this:
try {
File httpCacheDir = new File(getApplicationContext().getCacheDir(), "http");
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (IOException e) { }
and
connection.setUseCaches(true);
http://practicaldroid.blogspot.com/2013/01/utilizing-http-response-cache.html
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.