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();
}
Related
My Activity Code: Note this is not my main activity, right now i am using a button to fetch images from the database but instead I need to fetch all the images when the app load.
public class QuotesPictures extends Activity implements View.OnClickListener {
private String imagesJSON;
private static final String JSON_ARRAY = "result";
private static final String IMAGE_URL = "url";
private JSONArray arrayImages = null;
private int TRACK = 0;
private Button buttonMoveNext;
private Button buttonMovePrevious;
private ImageView imageView;
private static final String IMAGES_URL = "http://stressreliefapp.esy.es/getAllImages.php";
private Button buttonFetchImages;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quotes_pictures);
//Defining all the buttons
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
}
//Using AsyncTask to load the data in the background thread and then publishing on the UI thread
private void getImage(String urlToImage) {
class GetImage extends AsyncTask<String, Void, Bitmap> {
ProgressDialog loading;
#Override
protected Bitmap doInBackground(String... params) {
URL url = null;
Bitmap image = null;
String urlToImage = params[0];
try {
url = new URL(urlToImage);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(QuotesPictures.this, "Loading Images...", "Please wait...", true, true);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
loading.dismiss();
imageView.setImageBitmap(bitmap);
}
}
GetImage gi = new GetImage();
gi.execute(urlToImage);
}
// Method used to get all the images from the database using AsyncTask
public void getAllImages() {
class GetAllImages extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(QuotesPictures.this, "Loading Images...", "Please wait...", true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
imagesJSON = s;
extractJSON();
showImage();
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetAllImages gai = new GetAllImages();
gai.execute(IMAGES_URL);
}
private void extractJSON() {
try {
JSONObject jsonObject = new JSONObject(imagesJSON);
arrayImages = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showImage() {
try {
JSONObject jsonObject = arrayImages.getJSONObject(TRACK);
getImage(jsonObject.getString(IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext() {
if (TRACK < arrayImages.length()) {
TRACK++;
showImage();
}
}
private void movePrevious() {
if (TRACK > 0) {
TRACK--;
showImage();
}
}
#Override
public void onClick(View v) {
if (v == buttonFetchImages) {
getAllImages();
}
if (v == buttonMoveNext) {
moveNext();
}
if (v == buttonMovePrevious) {
movePrevious();
}
}
}
Just execute your download method in onCreate method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quotes_pictures);
//Defining all the buttons
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
getImage("your image url");
}
Move your code at onclicklistener to onResume.
public void onResume()
{
super.onResume();
/* your code at OnClickListener */
}
I want to add item into listview using async task, so in doinbackgroud it will process and get the data one by one and then display it on listview one by one .
But for my app doinbackground process all the data and then it will display into listview.
public class NewGetContacts extends AsyncTask<String[], Void, Void> {
private static final String TAG_TX = "txid";
private static final String TAG_FEE = "fees";
MyCustomAdapter mAdapter=new MyCustomAdapter();
ListView listViewHandle1 = (ListView) findViewById(R.id.listView2);
#Override
protected Void doInBackground(String[]... params) {
// TODO Auto-generated method stub
int len = params[0].length;
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
// String jsonStr;
mAdapter.addSeparatorItem("Transaction ...");
for(int i=0;i<len ;i++){
String turl = "https://coin/api/tx/"+params[0][i];
try {
String jsonStr1 = sh.makeServiceCall(turl, ServiceHandler.GET);
JSONObject jsonObj2 = new JSONObject(jsonStr1);
txtid = jsonObj2.getString(TAG_TX);
mAdapter.addItem("Transaction ID : "+txtid);
publishProgress();
}catch(Exception e){
Log.d("Exception In TXID -- >",e.getMessage());
}
}
return null;
}
protected void onProgressUpdate(Void... r) {
super.onProgressUpdate(r);
Log.d("Txid 14546465 ","--->");
mAdapter.notifyDataSetChanged();
listViewHandle1.requestLayout();
super.onProgressUpdate(r);
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
listViewHandle1.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
}
Call this in oncreate on your activity/fragment
Class TestActivity extends Activty {
MyCustomAdapter mAdapter ;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mAdapter=new MyCustomAdapter();
ListView listViewHandle1 = (ListView) findViewById(R.id.listView2);
listViewHandle1.setAdapter(mAdapter);
(new NewGetContacts()).execute();
}
}
Then do following in your AsyncTask class
protected Void doInBackground(String[]... params) { //Same as yours
// TODO Auto-generated method stub
int len = params[0].length;
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
// String jsonStr;
mAdapter.addSeparatorItem("Transaction ...");
for(int i=0;i<len ;i++){
String turl = "https://coin/api/tx/"+params[0][i];
try {
String jsonStr1 = sh.makeServiceCall(turl, ServiceHandler.GET);
JSONObject jsonObj2 = new JSONObject(jsonStr1);
txtid = jsonObj2.getString(TAG_TX);
mAdapter.addItem("Transaction ID : "+txtid);
publishProgress();
}catch(Exception e){
Log.d("Exception In TXID -- >",e.getMessage());
}
}
return null;
}
protected void onProgressUpdate(Void... r) {
super.onProgressUpdate(r);
mAdapter.notifyDataSetChanged();
Log.d("Txid 14546465 ","--->");
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Removed set adapter from here
mAdapter.notifyDataSetChanged();
}
I have a list fragment. When I run the app, I see an empty listView.
I don't know what the problem is. Maybe I should use a library?
public class MyEmployeFragment extends ListFragment {
private static final String ATTRIBUTE_ID = "p_id";
private static final String ATTRIBUTE_NAME = "p_name";
private static final String ATTRIBUTE_LAST_NAME = "p_last_name";
ArrayList<spr_item> ret_data;
MyTask task;
SimpleAdapter sAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
task = new MyTask();
task.execute();
return inflater.inflate(R.layout.my_employe, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ret_data = new ArrayList<spr_item>();
ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>(
ret_data.size());
Map<String, Object> m;
for (int i = 0; i < ret_data.size(); i++) {
m = new HashMap<String, Object>();
m.put(ATTRIBUTE_ID, ret_data.get(i).getId());
m.put(ATTRIBUTE_NAME, ret_data.get(i).getName());
m.put(ATTRIBUTE_LAST_NAME, ret_data.get(i).getLastName());
data.add(m);
}
// массив имен атрибутов, из которых будут читаться данные
String[] from = {ATTRIBUTE_ID, ATTRIBUTE_NAME, ATTRIBUTE_LAST_NAME};
// массив ID View-компонентов, в которые будут вставлять данные
int[] to = {R.id.tw_employe_id, R.id.tw_employe_name, R.id.tw_employe_last_name};
// создаем адаптер
sAdapter = new SimpleAdapter(getActivity(), data, R.layout.list_item_employee,
from, to);
// определяем список и присваиваем ему адаптер
ListView lvSimple = (ListView) getView().findViewById(android.R.id.list);
lvSimple.setAdapter(sAdapter);
}
class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
String s = "5ACACEC6-752B-4EFF-AA50-EEBE58A52113";
// String user_guid = myPrefs.getString("guid", "");
HttpActivity _http = new HttpActivity("192.168.10.11", "80");
_http.set_addr_protocol("/WebSite/P/spr/spr.aspx/");
_http.add_param("query", "spr_employee_get");
// _http.add_param("p_guid", user_guid.toString().trim());
_http.add_param("p_guid", s);
_http.send();
List<spr_item> tempList = _http.getArrayParamValue();
for(int i = 0; i < tempList.size(); i++)
ret_data.add(tempList.get(i));
//employer_name = _http.getArrayParamValue("p_name");
//employer_id = _http.getArrayParamValue("p_id");
//employer_last_name = _http.getArrayParamValue("p_last_name");
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
sAdapter.notifyDataSetChanged();
}
}
}
With the above code apart from the Empty list you may have the null pointer exception too if the task is too quick to load. Here onCreate is called first onCreateView next and onActvityCreated next. So it is better to initialise adapter in onCreate set the adapter to listView in onCreateView and set listView listeners in onActvityCreated using getListView() method.
Apart from this if you are using local database to retrieve data you need to use cursorADapter to fetch the data
The adapter's data references (ArrayList, array, etc.), tend to get lost pretty easily. In that case the notfiyDataSetChanged() method will not work. If you are adamant on using this method I suggest you check the references to the adapter's source again. If that is not the case this is the approach I've used in my project. A small warning in advance, the formatting and the closing of brackets is poorly executed, but the approach is still clear enough.
public class MyFragment extends ListFragment {
// For populating the list view.
SomeAdapter adapter;
public MyFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] parameters = {"url for request"};
new GetRequestTask().execute(parameters);
}
// The async task to make the HTTP GET requests.
class GetRequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
Log.e("GetRequestTask", "Client protocol exception.");
e.printStackTrace();
} catch (IOException e) {
Log.e("GetRequestTask", "IO exception.");
e.printStackTrace();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Update UI with the new response.
new UpdateUITask().execute(result);
}
}
}
// The async task to update the UI.
class UpdateUITask extends AsyncTask<String, String, ArrayList<Something>>{
#Override
protected ArrayList<Something> doInBackground(String... input) {
ArrayList<Something> someArray = new ArrayList<Something>();
try{
// Do some JSON magic to parse the data.
}
catch(JSONException je){
Log.e("UpdateUITask", "JSON parsing error occured.");
je.printStackTrace();
}
return someArray;
}
#Override
protected void onPostExecute(ArrayList<Something> result) {
super.onPostExecute(result);
Log.i("UpdateUITask", "Updating UI.");
adapter = new SomeAdapter(getActivity(), R.layout.some_list_item, restOfTheParameters);
setListAdapter(adapter);
}
}
}
}
When I skip second activity class from first activity class, I will start imageprocessing on certain image in second activity and then until new image comes to screen I wnt to start progress bar and then finish when the new image comes to screen. How can I do this ?
Use ProgreaaDialog and AsyncTask. you wil get your soultion
Use AsyncTask in doBackInGroundProcess do image processing. and in doPostExecute() exit or cancel the progress dialog
have a look on the sample code.
To start AsyncTsk use new ProgressTask().execute(null); from the activity where you want to do image processing.
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
List<Message> titles;
private ListActivity activity;
//private List<Message> messages;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
List<Message> titles = new ArrayList<Message>(messages.size());
for (Message msg : messages){
titles.add(msg);
}
MessageListAdapter adapter = new MessageListAdapter(activity, titles);
activity.setListAdapter(adapter);
adapter.notifyDataSetChanged();
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
}
}
protected Boolean doInBackground(final String... args) {
try{
BaseFeedParser parser = new BaseFeedParser();
messages = parser.parse();
return true;
} catch (Exception e){
Log.e("tag", "error", e);
return false;
}
}
}
}
Have a look here
Try using Async task as shown below:
try{
class test extends AsyncTask{
TextView tv_per;
int mprogress;
Dialog UpdateDialog = new Dialog(ClassContext);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
mprogress = 0;
UpdateDialog.setTitle(getResources().getString(R.string.app_name));
UpdateDialog.setContentView(R.layout.horizontalprogressdialog);
TextView dialog_message = (TextView)UpdateDialog.findViewById(R.id.titleTvLeft);
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
dialog_message.setText(getResources().getString(R.string.dialog_retrieving_data));
dialog_message.setGravity(Gravity.RIGHT);
UpdateDialog.setCancelable(false);
UpdateDialog.show();
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Object... values) {
// TODO Auto-generated method stub
ProgressBar update = (ProgressBar)UpdateDialog.findViewById(R.id.horizontalProgressBar);
update.setProgress((Integer) values[0]);
int percent = (Integer) values[0];
if(percent>=100)
{
percent=100;
}
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
tv_per.setText(""+percent);
}
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
//your code
}
super.onPostExecute(result);
UpdateDialog.dismiss();
}
}
new test().execute(null);
}
catch(Exception e)
{
e.printStackTrace();
}
Here is a method which when called starts a progressbar
private void downloadText(String urlStr) {
final String url = urlStr;
progressDialog = ProgressDialog.show(this, "", "Trying to register...");
Log.i("First string", urlStr);
try{
new Thread () {
public void run() {
int BUFFER_SIZE = 2000;
InputStream in = null;
try{
msg = Message.obtain();
msg.what=1;
}catch(Exception e)
{
}
try {
in = openHttpConnection(url);
InputStreamReader isr = new InputStreamReader(in);
int charRead;
text = "";
char[] inputBuffer = new char[BUFFER_SIZE];
while ((charRead = isr.read(inputBuffer))>0)
{
//---convert the chars to a String---
String readString =
String.copyValueOf(inputBuffer, 0, charRead);
text += readString;
inputBuffer = new char[BUFFER_SIZE];
}
Bundle b = new Bundle();
b.putString("text", text);
msg.setData(b);
in.close();
}catch (Exception e) {
//////////////////////////////////////
e.printStackTrace();
}
try{
messageHandler.sendMessage(msg);
}catch(Exception e)
{
}
}
}.start();
}catch(Exception e)
{
}
}
and here is the handler code
private Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
try{
super.handleMessage(msg);
switch (msg.what) {
case 1:
{
break;
}
}
progressDialog.dismiss();
}catch(Exception e)
{
}
}
};
Try this way
first Intialize your ProgressDialog
progressDialog = ProgressDialog.show(this, "", "Trying to ...");
then start a new thread in which you can write your code which needs to be executed
and finally in the handler handle the code and end the progessDialog
I believe I'm doing this correctly, in my activity class I'm calling execute the alert dialog appears and then the data load but the alert dialog never goes away. Here is my AsyncTask code:
Followed by my activity code.
public class Worker extends AsyncTask<URL, Integer, Long>{
private Activity ne;
private ProgressDialog progressDialog;
private Handler handler;
public Worker(Handler handler, Activity ne){
this.handler = handler;
this.ne = ne;
}
protected void onPreExecute() {
progressDialog = ProgressDialog.show(ne,"", "Retrieving News Events", true);
}
protected void onProgressUpdate(Void... progress) {
}
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
/* (non-Javadoc)
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Long doInBackground(URL... urls) {
HttpClient client = new DefaultHttpClient();
HttpGet get;
try {
get = new HttpGet(urls[0].toURI());
ResponseHandler<String> response = new BasicResponseHandler();
String responseBody = client.execute(get, response);
String page = responseBody;
Bundle data = new Bundle();
data.putString("page",page);
Message msg = new Message();
msg.setData(data);
handler.sendMessage(msg);
}
catch (Throwable t) {
Log.d("UpdateNews", "PROBLEMS");
}
return null;
}
}
public class NewsEvents extends ListActivity{
private URL JSONNewsEvents;
private ArrayList<NewsEvent> neList;
private ArrayList<String> keyWordList;
private Worker worker;
private TextView selection;
private ProgressDialog progressDialog;
static final int PROGRESS_DIALOG = 0;
public static final String KEYWORDS = "keywords";
private NewsEvents ne;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsevents);
ne = this;
neList = new ArrayList<NewsEvent>();
selection=(TextView)findViewById(R.id.selection);
try {
JSONNewsEvents = new URL(getString(R.string.jsonnewsevents));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
worker = new Worker(handler, this);
setListAdapter(new IconicAdapter());
getKeywords();
worker.execute(JSONNewsEvents);
}
/**
* #return
*/
public ArrayList<String> getKeywords(){
try {
InputStream fi = openFileInput(KEYWORDS);
if (fi!=null) {
ObjectInputStream in = new ObjectInputStream(fi);
keyWordList = (ArrayList<String>) in.readObject();
in.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
if(keyWordList == null){
keyWordList = new ArrayList<String>();
return keyWordList;
}
return keyWordList;
}
public void onListItemClick(ListView parent, View v,
int position, long id) {
startFullNewsEvent(neList.get(position));
}
/**
* #param newsEvent
*/
public void startFullNewsEvent(NewsEvent ne) {
Intent intent = new Intent(this, FullNewsEvent.class);
intent.putExtra("ne", ne);
this.startActivity(intent);
finish();
}
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
String page = msg.getData().getString("page");
try {
JSONArray parseArray = new JSONArray(page);
for (int i = 0; i < parseArray.length(); i++) {
JSONObject jo = parseArray.getJSONObject(i);
String title = jo.getString("title");
String body =jo.getString("body");
String pd = jo.getString("postDate");
String id = jo.getString("id");
NewsEvent ne = new NewsEvent(title, pd , body, id);
boolean unique = true;
for(NewsEvent ne0 : neList){
if(ne.getId().equals(ne0.getId())){
unique = false;
}else{
unique = true;
}
}
if(unique == true){
neList.add(ne);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ne.setListAdapter(new IconicAdapter());
}
};
public class IconicAdapter extends ArrayAdapter<NewsEvent> {
IconicAdapter() {
super(NewsEvents.this, R.layout.rownews, neList);
}
public View getView(int position, View convertView,ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.rownews, parent, false);
TextView label=(TextView)row.findViewById(R.id.label);
ImageView image= (ImageView)row.findViewById(R.id.icon);
String body = neList.get(position).getBody();
body.replaceAll("\\<.*?>", "");
String title = neList.get(position).getTitle();
for(String s : keyWordList){
if(body.contains(s) || body.contains(s.toLowerCase()) ||
title.contains(s) || title.contains(s.toLowerCase())){
neList.get(position).setInterested(true);
}
}
if(neList.get(position).isInterested() == true){
image.setImageResource(R.drawable.star);
}
label.setText(neList.get(position).getTitle());
return(row);
}
}
}
First of all change your onPostExecute to include the #Override:
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
In your class definition include this:
public class Worker extends AsyncTask<Void, Void, Void>
The first parameter is the type of input to the doInBackground method, the second is the type of the input to the onProgressUpdate and the third is the type of the input to the onPostExecute and the result from doInBackground.
It does not look like you are using the input parameter to the doInBackground method, so just change that to Void... and change the return type as well:
protected Void doInBackground(Void... paramArrayOfParams) { ... }
Does this help?
Edit:
I saw you had changed your code to use the parameter of the doInBackground, so the first parameter in your class definition is correct. However, try putting Void as the two last parameters. And change the return type of the doInBackground to Void too.
Like this:
public class Worker extends AsyncTask<URL, Void, Void>{
private Activity ne;
private ProgressDialog progressDialog;
private Handler handler;
public Worker(Handler handler, Activity ne){
this.handler = handler;
this.ne = ne;
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(ne,"", "Retrieving News Events", true);
}
protected void onProgressUpdate(Void... progress) {
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
/* (non-Javadoc)
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Void doInBackground(URL... urls) {
HttpClient client = new DefaultHttpClient();
HttpGet get;
try {
get = new HttpGet(urls[0].toURI());
ResponseHandler<String> response = new BasicResponseHandler();
String responseBody = client.execute(get, response);
String page = responseBody;
Bundle data = new Bundle();
data.putString("page",page);
Message msg = new Message();
msg.setData(data);
handler.sendMessage(msg);
}
catch (Throwable t) {
Log.d("UpdateNews", "PROBLEMS");
}
return null;
}
You're not overriding the asynctask method correctly. Take a look at an example
http://developer.android.com/reference/android/os/AsyncTask.html
and note now they declare their asynctask
extends AsyncTask<URL, Integer, Long>