1

我在我的应用程序上显示加载进度条时遇到问题。我试图搜索几天,但仍然没有任何好的进展。谁能帮我查看我的代码并给我任何评论。我的问题是当我打开页面时,它会直接在我的 Eclipse 上显示错误并强制我关闭。在我的调试选项卡中打开的错误页面 - “ThreadPoolExecutor.java”

请任何人帮助我...

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

更新的问题

 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;
    }
}

}

4

2 回答 2

1

AsyncTask分段以便doInBackground在后台运行,当你在后台时,你不能触摸 UI。一个doInBackground操作应该返回一个结果,该结果将被传递给onPostExecute. 在onPostExecuteUI 线程上运行,您可以在这里更新任何 UI 元素,包括设置新的列表适配器。

因此,在您的情况下,您可能会doInBackground返回一个包含状态和适配器的自定义对象,因此类似于...

public class Reply {
   public int status;
   public String message;
   public Vector<RowData> data;
}

然后在您的 AsynReply 实现中......

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
   }
}

顺便说一句,您onProgressUpdateonPostExecute. onProgressUpdate用于增量更新长时间操作的进度。您将从publishProgress后台线程调用,以便最终在 UI 线程上调用 onProgressUpdate。但是由于你的操作是一个阻塞的 http 请求,那么 usingonProgressUpdate在这里可能毫无意义,并且该逻辑应该成为onPostExecute.

于 2012-05-24T11:57:09.983 回答
0

你在doin后台线程中设置setcontentview。你不能在doin后台设置任何UI相关代码。它是一个后台线程。它与UI线程没有关系。只有你可以在执行前或执行后更改 UI。其他选项是在后台调用 onProgressUpdate()。

注意 onProgressUpdate() 用于通过该方法操作异步操作的进度。注意数据类型为 Integer 的参数。这对应于类定义中的第二个参数。可以通过调用 publishProgress() 从 doInBackground() 方法的主体内触发此回调。

于 2012-05-14T06:09:18.343 回答