Reputation: 33
I'm having problem to display the loading progress bar on my apps. I had tried to search for few days but still no any good progress. Could anyone help me to view my code and give me any comment. My problem is when i open the page, it will directly show error on my eclipse and force me to close. The error page opened in my Debug tab - "ThreadPoolExecutor.java"
Please anyone help me...
class DownloadMsg extends AsyncTask<Void, String, Void> {
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(ViewMsgMain.this);
progressDialog.setMessage("Loading. Please wait...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
protected Void doInBackground(Void... params) {
try{
//http post
HttpClient httpclient = new DefaultHttpClient();
//===================================================
// Get member id from local database
sp_memberid = getSharedPreferences(memberid, MODE_PRIVATE);
if(sp_memberid.contains("memberid")==true)
{memid = sp_memberid.getInt("memberid", 0);}
Log.e("view message member id == ", "~ "+memid);
//===================================================
HttpPost httppost = new HttpPost("http://localhost/project/viewmessage.php?memberid="+memid);
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); //encode a list of NameValuePair objects suitable for HTTP calls
HttpResponse response = httpclient.execute(httppost); // to make an HTTPPOST call with the HttpClient
HttpEntity entity = response.getEntity();
inputstream = entity.getContent();
//Convert response to string
BufferedReader reader = new BufferedReader(new InputStreamReader(inputstream,"UTF-8"));
stringbuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringbuilder.append(line + "\n");
}
inputstream.close();
result = stringbuilder.toString();
}
catch(Exception e){
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
}
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
if(jArray.length() == 0)
{
}
else
{
setContentView(R.layout.viewmsglist);
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
content_type = content_type + json_data.getString("uploadedcontenttype")+",";
content_path = content_path+"http:/localhost/project/"+(String) json_data.getString("contentpath")+",";
imageAudio_image = imageAudio_image + json_data.getString("imageaudiopath")+",";
//r.add(json_data.getString("member_id") + json_data.getString("member_name") + json_data.getString("member_usernamepath"));
content_id = content_id + json_data.getString("contentid")+",";
imageaudio_id = imageaudio_id + json_data.getString("imageaudioid")+",";
content_date = content_date + json_data.getString("contentdate")+",";
over_contentid = over_contentid + json_data.getString("overallid")+",";
uploaded_content_id = uploaded_content_id + json_data.getString("uploadedcontentid")+",";
sender_id = sender_id + json_data.getString("senderid")+",";
receiver_id = receiver_id + json_data.getString("receiverid")+",";
read_status =read_status + json_data.getString("readstatus")+",";
sender_member_image = sender_member_image + "http://localhost/project/www/"+json_data.getString("memberimage")+",";
}
// Split the data retrieved from database
content_type_split = content_type.split(",");
content_path_split = content_path.split(",");
content_id_split = content_id.split(",");
content_date_split = content_date.split(",");
sender_member_image_split = sender_member_image.split(",");
uploaded_content_id_split = uploaded_content_id.split(",");
imageAudio_image_split = imageAudio_image.split(",");
over_contentid_split = over_contentid.split(",");
mInflater = (LayoutInflater) getSystemService(
Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
Log.e("content_type_split.length","~ "+content_type_split.length);
for(int i=0;i<content_type_split.length;i++){
try {
rd = new RowData(i,content_type_split[i],content_date_split[i]);
} catch (ParseException e) {
e.printStackTrace();
}
data.add(rd);
}
Log.e("finish here","finish" + data);
//getListView().setTextFilterEnabled(true);*/
Log.e("finish there","t finish");
//new DownloadMsg().execute();
Log.e("retrieved ", "~ "+content_type + "@ " + content_type + " # "+ content_path + " $ "+ sender_id);
/**
* Updating parsed JSON data into ListView
* */
CustomAdapter adapter = new CustomAdapter(ViewMsgMain.this, R.layout.list,R.id.title, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
}
catch(JSONException e1){
Toast.makeText(getApplicationContext(), "Tiada mesej", Toast.LENGTH_SHORT).show();
//Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
}
return null;
}
protected void onProgressUpdate(Integer... statusCode) {
switch (statusCode[0]) {
case CANCELED:
removeDialog(PROGRESSDIALOG_ID);
Toast.makeText(getApplicationContext(),
getString(R.string.CanceledMessage),
Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
break;
case OTHER_INTERNAL_ERROR:
removeDialog(PROGRESSDIALOG_ID);
Toast.makeText(getApplicationContext(),
getString(R.string.internal_exception_message),
Toast.LENGTH_LONG).show();
break;
case SECURITY_ERROR:
removeDialog(PROGRESSDIALOG_ID);
Toast.makeText(getApplicationContext(),
getString(R.string.security_exception_message),
Toast.LENGTH_LONG).show();
break;
case SERVER_STATUS_UPLOADED:
if(!uploadFlag)
uploadFlag = true;
default:
progressDialog.setProgress(uploadCounter);
adapter.notifyDataSetChanged();
}
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all tb_cafe
progressDialog.dismiss();
// updating UI from Background Thread
}//end of onPostExecute
Updated Question
public class DisplayDiary extends ListActivity{
// Retrieve member id from local database
String memberid = FypGeneral.LOGINMEMBERID;
SharedPreferences sp_memberid;
int memid;
// Retrieve diary details from database
private String numRows="";
private String diary_id="";
private String diary_image_msgpath="";
private String diary_audio_msgpath="";
private String diary_created_date="";
private String member_id="";
private InputStream inputstream;
private StringBuilder stringbuilder;
private String result="";
// Split the retreived result
private String diary_id_split[];
private String diary_image_msgpath_split[];
private String diary_audio_msgpath_split[];
private String diary_created_date_split[];
private String member_id_split[];
// Custom List View
private LayoutInflater mInflater;
private Bitmap bitmap;
private Vector<RowData> data;
RowData rd;
private ProgressDialog pDialog;
private CustomAdapter adapter;
// Progress Bar
private static final int CANCELED = -4;
private static final int OTHER_INTERNAL_ERROR = -3; //part of internal error
private static final int SECURITY_ERROR = -2; //part of internal error
private static final int SERVER_STATUS_FAILED = -1; //server side failed
private static final int SERVER_STATUS_UPLOADED = 1; //success
private SSLSocketFactory defaultSSLSocketFactory = null;
private HostnameVerifier defaultHostnameVerifier = null;
private int uploadCounter;
private boolean uploadFlag;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//===================================================
// Get member id from local database
sp_memberid = getSharedPreferences(memberid, MODE_PRIVATE);
if(sp_memberid.contains("memberid")==true)
{memid = sp_memberid.getInt("memberid", 0);}
Log.e("view message member id == ", "~ "+memid);
//===================================================
setContentView(R.layout.view_diary_list);
mInflater = (LayoutInflater) getSystemService(
Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
new LoadDiary().execute();
}
public void onListItemClick(ListView parent, View v, int position,
long id) {
Toast.makeText(getApplicationContext(), "You clicked "+diary_image_msgpath_split[position], Toast.LENGTH_SHORT).show();
}
class LoadDiary extends AsyncTask<Void, Integer, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DisplayDiary.this);
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(Void... params) {
try{
Log.e("puvlis", "3");
//http post
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/project/display_diary.php?memberid="+memid);
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); //encode a list of NameValuePair objects suitable for HTTP calls
HttpResponse response = httpclient.execute(httppost); // to make an HTTPPOST call with the HttpClient
HttpEntity entity = response.getEntity();
inputstream = entity.getContent();
}
catch(Exception e){
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
}
//Convert response to string
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(inputstream,"UTF-8"));
stringbuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringbuilder.append(line + "\n");
}
inputstream.close();
result = stringbuilder.toString();
}
catch(Exception e)
{
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
}
//END Convert response to string
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
numRows = json_data.getString("diaryrow");
if(numRows.equals("0"))
{
Toast.makeText(getApplicationContext(), "Tiada diary", Toast.LENGTH_SHORT);
}
else
{
diary_id = diary_id + json_data.getString("diary_id")+",";
diary_image_msgpath = diary_image_msgpath + "http://localhost/project/"+json_data.getString("diary_image_msgpath")+",";
diary_audio_msgpath = diary_audio_msgpath + "http://localhost/project/"+json_data.getString("diary_audio_msgpath")+",";
diary_created_date = diary_created_date + json_data.getString("diary_created_date")+",";
}
//username_path = username_path+"http://omega.fcsit.unimas.my/project/www/"+(String) json_data.getString("member_usernamepath")+",";
//r.add(json_data.getString("member_id") + json_data.getString("member_name") + json_data.getString("member_usernamepath"));
member_id = member_id + json_data.getString("member_id")+",";
}
diary_id_split = diary_id.split(",");
diary_image_msgpath_split = diary_image_msgpath.split(",");
diary_audio_msgpath_split = diary_audio_msgpath.split(",");
diary_created_date_split = diary_created_date.split(",");
data = new Vector<RowData>();
Log.e("content_type_split.length","~ "+diary_image_msgpath_split.length);
for(int i=0;i<diary_image_msgpath_split.length;i++){
try {
rd = new RowData(i,diary_id_split[i],diary_created_date_split[i]);
} catch (ParseException e) {
e.printStackTrace();
}
data.add(rd);
}
Log.e("finish here","finish" + data);
HttpURLConnection conn = null;
DataOutputStream dos = null;
boolean trustEveryone = true;
URL url = null;
try{
switch (conn.getResponseCode()) {
case 200:
publishProgress(SERVER_STATUS_UPLOADED);
break;
case 500:
default:
}
} catch (Exception e) {
e.printStackTrace();
//failed on server side, continue with rest of the items
publishProgress(SERVER_STATUS_FAILED);
}
uploadCounter++;
publishProgress(SERVER_STATUS_UPLOADED);
}
catch(JSONException e1){
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
}
adapter = new CustomAdapter(DisplayDiary.this, R.layout.diary_list,
R.id.title, data);
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all tb_cafe
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
});
/**
* Updating parsed JSON data into ListView
* */
}
}
private class RowData {
protected int mId;
protected String mTitle;
protected String mDetail;
RowData(int id,String title,String detail){
mId=id;
mTitle = title;
mDetail=detail;
}
@Override
public String toString() {
return mId+" "+mTitle+" "+mDetail;
}
}
/**
*
* @author choonsee
* CustomAdapter
* Description: Adapter created to customize the list layout
* image(type of message)-text(date)-image(message sender)
*
*/
public class CustomAdapter extends ArrayAdapter<RowData> {
public CustomAdapter(Context context, int resource,
int textViewResourceId, List<RowData> objects) {
super(context, resource, textViewResourceId, objects);
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
TextView title = null;
TextView detail = null;
ImageView i11=null;
ImageView i112=null;
RowData rowData= getItem(position);
if(null == convertView){
convertView = mInflater.inflate(R.layout.diary_list, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
title = holder.gettitle();
title.setText(rowData.mTitle);
detail = holder.getdetail();
detail.setText(rowData.mDetail);
i11=holder.getImage();
i11.setImageResource(R.drawable.imageicon2);
Log.e("urlpath ," , " ~ "+diary_image_msgpath_split[rowData.mId]);
i112=holder.getImage2();
try {
Log.e("enter bitmap ", "yes");
bitmap = BitmapFactory.decodeStream((InputStream)new URL(diary_image_msgpath_split[rowData.mId]).getContent());
i112.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
//e.printStackTrace();
} catch (IOException e) {
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
//e.printStackTrace();
}
return convertView;
}
}
/**
* ViewHolder initial the value and define the variable
* @author choonsee
*
*/
public class ViewHolder {
private View mRow;
private TextView title = null;
private TextView detail = null;
private ImageView i11=null;
private ImageView i112=null;
public ViewHolder(View row) {
mRow = row;
}
public TextView gettitle() {
if(null == title){
title = (TextView) mRow.findViewById(R.id.title);
}
return title;
}
public TextView getdetail() {
if(null == detail){
detail = (TextView) mRow.findViewById(R.id.detail);
}
return detail;
}
public ImageView getImage() {
if(null == i11){
i11 = (ImageView) mRow.findViewById(R.id.img);
}
return i11;
}
public ImageView getImage2() {
if(null == i112){
i112 = (ImageView) mRow.findViewById(R.id.img2);
}
return i112;
}
}
}
Upvotes: 1
Views: 1475
Reputation: 6545
The AsyncTask
is segmented such that the doInBackground
is run in the background, and while you are in the backgroud, you CAN NOT touch the UI. A doInBackground
operation should return a result, and that result will be passed to the onPostExecute
. The onPostExecute
is run on the UI thread and it is here that you can update any UI elements, which includes setting a new list adapater.
So, in your case, you might have the doInBackground
return a custom Object that includes a status and an adapter, so something like...
public class Reply {
public int status;
public String message;
public Vector<RowData> data;
}
Then in your AsynReply implementation...
public Reply doInBackground() {
// do your time consuming work
Reply reply = new Reply();
// if error, create reply, and set the error status
// reply.error=CANCELLED
// if no error, you have data, then set data
// reply.data = data
return reply;
}
public void onPostExecute(Reply reply) {
if (reply.data !=null) {
// create CustomAdapter using reply.data and set in listview
} else {
// Make a toast with the reply.message or reply.error
// do any other error clean up that is required on the UI
}
}
BTW, all the code that you have in the onProgressUpdate
, you'd probably put in the onPostExecute
. The onProgressUpdate
is used to incrementally update your progress on a long operation. You would call publishProgress
from your background thread so that eventually onProgressUpdate is called on the UI thread. But since your operation is a blocking http request, then using onProgressUpdate
is probably pointless here, and that logic should become part of the onPostExecute
.
Upvotes: 1
Reputation: 3937
u are setting setcontentview in doin background thread.u can not set any UI related codes in doin background.Its a background thread.it has no relation with the UI thread. only u can do the UI change in preexecute or post execute.Other option is calling onProgressUpdate() in doin Background.
Note That onProgressUpdate() is used to operate progress of async operations via this method. Note the param with datatype Integer. This corresponds to the second parameter in the class definition. This callback can be triggered from within the body of the doInBackground() method by calling publishProgress().
Upvotes: 0