how to refresh listview after asynctask android - android

I have one page timeline like Facebook (there are EditText and Button), it has 2 async task. The first one is used to send parameter to remote server, the second one to load data json from URL. Actually first time, program will load JSON on the listview with async, then if I wanna update status after click Button then it will insert to table on the remote server. Both of them work successfully. But I have a little problem : after click button (update status) I want to refresh my listview. I have added the code on event click button, and then added onPostExecute (Class TheTask). After I send parameter, listview does not reload contents again. Can somebody help me to solve this problem ?
my source code :
public class Timeline extends Activity {
private static String BaseUrl="";
private String status;
final int PROGRESS_DIALOG=1;
private ProgressBar pb;
ViewConnection connection;
ArrayList<URLPostClass> timelinelist=new ArrayList<URLPostClass>();
ArrayList<URLPostClass> arrtimeline=new ArrayList<URLPostClass>();
//ArrayList<String> arritemcategory;
ListView listview;
//ListViewAdapter ListViewAdapter;
#Override
protected Dialog onCreateDialog(int id) {
switch(id)
{
case PROGRESS_DIALOG:
ProgressDialog progress =new ProgressDialog(this);
progress.setMessage("Loading");
progress.setTitle("Memuat status");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setProgress(0);
progress.setMax(100);
return progress;
}
return super.onCreateDialog(id);
}
private class GetTimelineAyncTask extends AsyncTask<Hashtable<String,String>,Void,String> {
#Override
protected void onPreExecute() {
showDialog(PROGRESS_DIALOG);
super.onPreExecute();
}
#Override
protected String doInBackground(Hashtable<String, String>... params)
{
// TODO Auto-generated method stub
Hashtable ht=params[0];
String json=HelperHttp.getJSONResponseFromURL(BaseUrl, ht);
if(json!=null) {
parseJsonString(timelinelist,json);
}else{
return "No internet access";
}
return json;
}
protected void parseJsonString(ArrayList<URLPostClass> timelinelistjs,String json){
try {
JSONObject jsonObj = new JSONObject(json);
JSONArray array = jsonObj.getJSONArray("listtimeline");
URLPostClass.setlength(array.length());
for (int i=0;i<array.length();i++){
JSONObject js=array.getJSONObject(i);
URLPostClass timeline=new URLPostClass(js.getString("IdTimeline"),
js.getString("NamaSales"),
js.getString("JenisStatus"),
js.getString("Remark"),
js.getString("TgglInsert"),
js.getString("Path"));
timelinelistjs.add(timeline);
}
}catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result){
if(result=="SUCCESS")
{
}else{
DecimalFormat formatter = new DecimalFormat("#,###,###");
JSONObject jObject = null;
Context mContext = null;
try {
jObject = new JSONObject(result);
JSONArray jArray = jObject.getJSONArray("listtimeline");
for (int i=0; i < jArray.length(); i++)
{
JSONObject oneObject=jArray.getJSONObject(i);
URLPostClass timeline=new URLPostClass(oneObject.getString("IdTimeline"),
oneObject.getString("NamaSales"),
oneObject.getString("JenisStatus"),
oneObject.getString("Remark"),
oneObject.getString("TgglInsert"),
oneObject.getString("Path"));
arrtimeline.add(timeline);
}
listview = (ListView) findViewById(R.id.listtimeline);
listview.setAdapter(new ListViewTimelineAdapter(getBaseContext(), arrtimeline));
}catch (JSONException e) {
e.printStackTrace();
}
}
removeDialog(PROGRESS_DIALOG);
super.onPostExecute(result);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeline);
Global.Timeline=this;
final RadioButton rbtnlisting=(RadioButton)findViewById(R.id.rbtnlisting);
final RadioButton rbtnclosing=(RadioButton)findViewById(R.id.rbtnclosing);
final RadioButton rbtnprospek=(RadioButton)findViewById(R.id.rbtnprospek);
final EditText edtstatus=(EditText)findViewById(R.id.edtstatus);
Button btnpost=(Button)findViewById(R.id.btnpost);
edtstatus.setTextSize(TypedValue.COMPLEX_UNIT_PX, getBaseContext().getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
btnpost.setTextSize(TypedValue.COMPLEX_UNIT_PX, getBaseContext().getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
rbtnlisting.setTextSize(TypedValue.COMPLEX_UNIT_PX, getBaseContext().getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
rbtnclosing.setTextSize(TypedValue.COMPLEX_UNIT_PX, getBaseContext().getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
rbtnprospek.setTextSize(TypedValue.COMPLEX_UNIT_PX, getBaseContext().getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
listview = (ListView) findViewById(R.id.listtimeline);
pb=(ProgressBar)findViewById(R.id.progressBar1);
pb.setVisibility(View.GONE);
connection = new ViewConnection(getBaseContext());
if (connection.isConnectingToInternet())
{
btnpost.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (edtstatus.getText().length()>5) {
pb.setVisibility(View.VISIBLE);
TheTask async=new TheTask();
async.execute("ccc");
}else {
Toast.makeText(getBaseContext(), "Your status is too short", Toast.LENGTH_LONG).show();
}
}
});
BaseUrl="http://xxx.xxx.xxx.xxx/dummy/gettimeline.php";
executeAsyncTask();
}else {
// Internet connection is not present
LayoutInflater li = LayoutInflater.from(Timeline.this);
final View inputdialogcustom = li.inflate(R.layout.activity_confirm_connection, null);
AlertDialog.Builder alert = new AlertDialog.Builder(Timeline.this);
alert.setView(inputdialogcustom);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
alert.show();
}
}
class TheTask extends AsyncTask<String, Integer, Double>
{
#Override
protected Double doInBackground(String... params) {
postData(params[0]);
return null;
}
protected void onPostExecute(Double result) {
// TODO Auto-generated method stub
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Status telah diposting !", Toast.LENGTH_LONG).show();
BaseUrl="http://xxx.xxx.xxx.xxx/dummy/gettimeline.php"; // I PUT ON HERE
executeAsyncTask();
}
protected void onProgressUpdate(Integer... progress){
pb.setProgress(progress[0]);
}
public void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
RadioButton rbtnlisting=(RadioButton)findViewById(R.id.rbtnlisting);
RadioButton rbtnclosing=(RadioButton)findViewById(R.id.rbtnclosing);
RadioButton rbtnprospek=(RadioButton)findViewById(R.id.rbtnprospek);
EditText edtstatus=(EditText)findViewById(R.id.edtstatus);
if (edtstatus.getText().length()>5) {
RadioGroup radiotipe = (RadioGroup) findViewById(R.id.radiotipe);
int selectedId = radiotipe.getCheckedRadioButtonId();
RadioButton rbtnselected=(RadioButton) findViewById(selectedId);
status=rbtnselected.getText().toString();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxx.xxx.xxx.xxx/dummy/insert.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("idsales",OtherClass.getIdSales().toString()));
nameValuePairs.add(new BasicNameValuePair("jenis", status));
nameValuePairs.add(new BasicNameValuePair("remark", edtstatus.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("path", "coba coba"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response=httpclient.execute(httppost);
}
catch (ClientProtocolException e)
{
e.printStackTrace();
// TODO Auto-generated catch block
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
Toast.makeText(getBaseContext(), "Your status is too short", Toast.LENGTH_LONG).show();
}
}
}
private void executeAsyncTask(){
Hashtable<String,String> ht=new Hashtable<String,String>();
GetTimelineAyncTask async=new GetTimelineAyncTask();
Hashtable[] ht_array={ht};
async.execute(ht_array);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.tab_sport, menu);
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.menutimeline, menu);
return super.onCreateOptionsMenu(menu);
}
#SuppressLint("NewApi")
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.menulogout:
//Toast.makeText(getBaseContext(), "test", Toast.LENGTH_LONG).show();
//View view = item.getActionView();
//final EditText edtsearchitem=(EditText)view.findViewById(R.id.edtsearchitem);
OtherClass.setIdSales("");
Global.Timeline.finish();
Intent MyIntentDetailItem=new Intent(getBaseContext(), MainActivity.class);
startActivity(MyIntentDetailItem);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

Here you have to create global Adapter and call to notifydatasetchanged() using adapter
Declare globally
ListViewTimelineAdapter adapter=null;
and replace
listview = (ListView) findViewById(R.id.listtimeline);
listview.setAdapter(new ListViewTimelineAdapter(getBaseContext(), arrtimeline));
code with
listview = (ListView) findViewById(R.id.listtimeline);
adapter=new ListViewTimelineAdapter(getBaseContext(), arrtimeline);
listview.setAdapter(adapter);
adapter.NotifyDatasetChanged();
thats it...and when ever you want to refresh list just write
adapter.NotifyDatasetChanged();
and listview reloaded...

This may become handy in your situation:
myListView.invalidateViews();
Original answer with some other ways explained can be found here:
How to refresh Android listview?
Hope it helps.

Related

onResume Does Not Update ListView With New Data

I am trying to update a ListView on previous fragment after back button press. The onResume is called (verified with Toast) and the webservice runs (listView is displayed after it is cleared). The problem is that the ListView is still showing old values and not new value after accessWebService_getUsername is called. I verify the values from MySQL and even though the DB is updated, the ListView only returns old values.
#Override
public void onResume() {
Toast.makeText(getActivity(), "onResume", Toast.LENGTH_SHORT).show();
super.onResume();
adapter.clear();
getIMEI();
accessWebService_getUsername();
adapter.notifyDataSetChanged();
}
Update:
//ListView
ListView lv =(ListView)view.findViewById(R.id.listView);
adapter = new ContactsAdapter(getActivity(), arrRequest_Contact, arrRequest_NameSurname, arrRequest_MessageCount, arrRequest_Time, arrRequest_Image);
lv.setAdapter(adapter);
// Json
private class JsonGetUsername extends AsyncTask<String, Void, String> {
//Pending 01
private ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPreExecute() {
this.dialog.setMessage("Loading Contacts, Please Wait");
this.dialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getActivity(),"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
//Pending 02
if (dialog.isShowing()) {
dialog.dismiss();
}
adapter.notifyDataSetChanged();
try{
ListDrawer_getUsername(); //has ConnectionException (when it cannot reach server)
}catch (Exception e){
Toast.makeText(getActivity(), "Please check your connection..", Toast.LENGTH_LONG).show();
}
}
}// end async task
public void accessWebService_getUsername() {
JsonGetUsername task = new JsonGetUsername();
// passes values for the urls string array
task.execute(new String[] { "http://mywebsite/php/get_username.php?pIMEI="+IMEI});
}
// build hash set for list view
public void ListDrawer_getUsername() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("username_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
request_username = jsonChildNode.optString("Username");
}
accessWebService_getContacts();
} catch (JSONException e) {
System.out.println("Json Error Rooms" +e.toString());
//Toast.makeText(getApplicationContext(), "No Rooms To Load", Toast.LENGTH_SHORT).show();
}
}
UPDATE 2:
//ContactsAdpater
class ContactsAdapter extends ArrayAdapter<String>
{
Context context;
List<String> Request_Contact;
List<String> Request_NameSurname;
List<String> Request_MessageCount;
List<String> Request_Time;
List<String> Request_Image;
ContactsAdapter(Context c, List<String> Request_Contact, List<String> Request_NameSurname, List<String> Request_MessageCount, List<String> Request_Time, List<String> Request_Image)
{
super(c, R.layout.activity_contacts_single, R.id.textContact, Request_Contact);
this.context=c;
this.Request_Contact=Request_Contact;
this.Request_NameSurname=Request_NameSurname;
this.Request_MessageCount=Request_MessageCount;
this.Request_Time=Request_Time;
this.Request_Image=Request_Image;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row=convertView;
if(row==null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.activity_contacts_single, parent, false);
}
TextView txtContact = (TextView) row.findViewById(R.id.textContact);
TextView txtNameSurname = (TextView) row.findViewById(R.id.textNameSurname);
TextView txtMessageCount = (TextView) row.findViewById(R.id.textMessageCount);
TextView txtTime = (TextView) row.findViewById(R.id.textTime);
ImageView imageView = (ImageView) row.findViewById(R.id.imageView);
txtContact.setText(Request_Contact.get(position));
txtNameSurname.setText(Request_NameSurname.get(position));
txtMessageCount.setText(Request_MessageCount.get(position));
txtTime.setText(Request_Time.get(position));
Picasso.with(context).load(arrRequest_Image.get(position)).transform(new CircleTransform()).placeholder(R.drawable.ic_launcher).into(imageView);
return row;
}
}
You'll need to override the clear method in your ContactsAdapter to actually clear the lists you are storing your data in.
It looks like you'll need to clear all your lists, so if you add this to ContactsAdapter, your code should work as expected:
#Override
public void clear() {
super.clear();
Request_Contact.clear();
Request_NameSurname.clear();
Request_MessageCount.clear();
Request_Time.clear();
Request_Image.clear();
}

some times unable to fetch data from server in android with lattitude and longitude

public class MobileActivity extends Activity {
ArrayList<Actors> actorsList;
public String latti;
public String longi;
ActorAdapter adapter;
JSONParser jParser = new JSONParser();
private static String url_search = "http://10.0.2.2/AndroidApp/mobile1.php";
//String url_search = "http://10.0.2.2/AndroidApp/mobile1.php?lat="+lat+"&lon="+lon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.offer_activity);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute(url_search);
final ListView listview = (ListView)findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.icons, actorsList);
listview.setAdapter(adapter);
Intent myIntent = getIntent();
latti = myIntent.getStringExtra("lat");
longi = myIntent.getStringExtra("lon");
//Toast.makeText(this, latti, Toast.LENGTH_LONG).show();
//Toast.makeText(this, longi, Toast.LENGTH_LONG).show();
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), actorsList.get(position).getId(), Toast.LENGTH_LONG).show();
String pid=actorsList.get(position).getName();
Intent intent = new Intent(MobileActivity.this,ProductDetails.class);
intent.putExtra("keyid",pid.toString());
startActivity(intent);
//initiatePopupWindow();
/* LayoutInflater layoutInflater
= (LayoutInflater)getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(
popupView,
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
Button btnDismiss = (Button)popupView.findViewById(R.id.dismiss);
btnDismiss.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
popupWindow.dismiss();
}});
popupWindow.showAsDropDown(listview, 10, -400);
}*/}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
android.app.ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#20B2AA")));
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.hom:
Intent hom = new Intent(this, OpenApp.class);
startActivity(hom);
return true;
case R.id.grid:
// search action
Intent searchIntent1 = new Intent(this, MobileGrid.class);
searchIntent1.putExtra("lat",latti.toString());
searchIntent1.putExtra("lon",longi.toString());
startActivity(searchIntent1);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MobileActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("lat", latti));
params.add(new BasicNameValuePair("lon", longi));
//HttpGet httppost = new HttpGet(urls[0]);
//HttpClient httpclient = new DefaultHttpClient();
//HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
//int status = response.getStatusLine().getStatusCode();
//if (status == 200) {
//HttpEntity entity = response.getEntity();
//String data = EntityUtils.toString(entity);
JSONObject jsono = jParser.makeHttpRequest(url_search, "GET",params);
//JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("offer_reg");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("offer_id"));
actor.setDescription(object.getString("lat"));
//actor.setDob(object.getString("dob"));
actor.setCountry(object.getString("log"));
//actor.setHeight(object.getString("tag3"));
//actor.setSpouse(object.getString("tag4"));
//actor.setChildren(object.getString("tag1"));
actor.setImage(object.getString("offer_image"));
actorsList.add(actor);
}
return true;
//}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
unable to fetch data from server(PHP,mysql) in android,fetching image view with lattitude and longitude..sometime image view displayed...some times unable to fetch data from server

Downloading images from a link displaying them in a listview

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

Progress Dialog should spin till loading of gridview completed

I am working on one android app in which i want to display progress Dialog till loading of gridview completed. But my problem is progress dialog is spin for some intial time. Then it stops spinning.
Here is my code.
public class allsites extends Activity {
private final String url_select = "http://api.stackexchange.com/2.1/sites?filter=!RGB_Y51.*-(YX";
private GridView gview;
private ListViewCustomAdapter adapter;
private ArrayList<Object> itemList = new ArrayList<Object>();
private ItemBean bean;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.allsites);
//GridView gridview = (GridView) findViewById(R.id.gvAllSites);
gview = (GridView) findViewById(R.id.gvallsites);
new task().execute();
}
private class task extends AsyncTask<Void, Void, GZIPInputStream> {
private ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(allsites.this, "Loading", "Please Wait...");
}
#Override
protected GZIPInputStream doInBackground(Void... params) {
ServerData httpclient = new ServerData();
GZIPInputStream zis = httpclient.GetServerData(url_select);
return zis;
}
#Override
protected void onPostExecute(GZIPInputStream zis) {
ParseJSON(zis);
if(progress!=null && progress.isShowing()==true)
progress.dismiss();
}
}
private void ParseJSON(GZIPInputStream zis)
{
Gson gson = new Gson();
Reader reader = new InputStreamReader(zis);
Sites response = gson.fromJson(reader, Sites.class);
List<Items> items = response.getItems();
for (Items site : items) {
//Toast.makeText(allsites.this, site.getApi_site_parameter().toString(), Toast.LENGTH_SHORT).show();
AddObjectToList(site.getIcon_url(),site.getName());
}
adapter = new ListViewCustomAdapter(this, itemList);
gview.setAdapter(adapter);
}
public void AddObjectToList(String imageURL, String title)
{
bean = new ItemBean();
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
bean.setImage(bitmap);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bean.setTitle(title);
itemList.add(bean);
}
}
Please give me suggestion how i can make progress dialog spinning till gridview get loaded.
move ParseJSON function to doInBackground event
#Override
protected Boolean doInBackground(Void... params) {
ServerData httpclient = new ServerData();
GZIPInputStream zis = httpclient.GetServerData(url_select);
ParseJSON(zis);
return true;
}
#Override
protected void onPostExecute(Boolean zis) {
progress.dismiss();
}

Async Task android

I have a Login page where I want to authenticate the username and password from the database on the network. The problem is while doing the AsyncTask I want to return the username and password values. But this is not happening.
How do I return the values? Here is my login page code.
public class Login extends Activity {
Integer aaa=0;
Button b,b2;
RelativeLayout r;
TextView t, t2;
String str1, str2, username, password;
String A = null, B = null;
EditText et1, et2;
Dialog myDialog;
String FILENAME = "http://animsinc.com/query.php";
protected ProgressDialog dialog;
protected Handler h;
static InputStream in = null;
static JSONObject jObj = null;
static String json = "";
private static final String TAG_ID = "id";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_in);
Display display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight() / 4;
r = (RelativeLayout) findViewById(R.id.RL);
RelativeLayout.LayoutParams r = new RelativeLayout.LayoutParams(width,
height);
t = (TextView) findViewById(R.id.textView1);
t2 = (TextView) findViewById(R.id.textView2);
t.setOnClickListener(link);
t2.setOnClickListener(fgtpass);
et1 = (EditText) findViewById(R.id.editText1);
et2 = (EditText) findViewById(R.id.editText2);
b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(temp);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((et1.getText().length() == 0)
|| (et2.getText().length() == 0))
{
Toast.makeText(getApplicationContext(),
"Please enter correct details",Toast.LENGTH_LONG)
.show();
} else {
dialog = ProgressDialog.show(Login.this, "Loading",
"Please Wait...");
/* h = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
dialog.dismiss();
}
};
new Thread() {
#Override
public void run() {
super.run();
String st=startDownload();
try {
Thread.sleep(3000);
h.sendEmptyMessage(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();*/
Toast.makeText(getApplicationContext(),""+st,Toast.LENGTH_LONG).show();
String st=startDownload();
Toast.makeText(getApplicationContext(),"aaa="+aaa, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),""+st, Toast.LENGTH_LONG).show();
}
if ((et1.getText().toString().equals(username))&& (et2.getText().toString().equals(password)))
{
Intent openStartingPoint = new Intent(Login.this,
UserActivity.class);
startActivity(openStartingPoint);
}
}
});
}
private
String startDownload() {
String C = null;
new AppTask().execute(FILENAME);
aaa++;
return C;
}
private View.OnClickListener temp = new View.OnClickListener() {
public void onClick(View V) {
Intent openStartingPoint = new Intent(Login.this,
UserActivity.class);
startActivity(openStartingPoint);
}
};
private View.OnClickListener link = new View.OnClickListener() {
public void onClick(View V) {
Intent openStartingPoint = new Intent(Login.this,
ContactDetails.class);
startActivity(openStartingPoint);
}
};
private View.OnClickListener fgtpass = new View.OnClickListener() {
public void onClick(View V) {
myDialog = new Dialog(Login.this);
myDialog.setContentView(R.layout.emailpop);
myDialog.setTitle("Forgot Password");
myDialog.setCancelable(true);
// for save
Button ok = (Button) myDialog.findViewById(R.id.button1);
ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
myDialog.dismiss();
}
});
myDialog.show();
}
};
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
public class AppTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... params) {
String is = null;
str1 = et1.getText().toString();
str2 = et2.getText().toString();
if (str1.length() > 0 && str2.length() > 0) {
A = str1;
B = str2;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://animsinc.com/query.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("username", str1));
nameValuePairs.add(new BasicNameValuePair("password", str2));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = EntityUtils.toString(entity);
JSONArray jArray = new JSONArray(is);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
username = jObject.getString("username");
password = jObject.getString("password");
aaa++;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return username;
}
}
}
When an asynchronous task is executed, the task goes through 4 steps:
onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
So return value in doInBackground() , receive it in onPostExecute() and update ui accordingly.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeTest(MainActivity.this,result,1000).show();
//set result to textview
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// result is the value you return from doInBackground
String username = result;
}

Categories

Resources