Asynctask不起作用

时间:2017-06-16 16:42:17

标签: android android-asynctask

每当我拨打DownloadImage("picture_name")时,应用程序就会停止。 AsyncTask适用于此应用程序的另一个活动,但不适用于此应用程序。

这是我的代码:

public class ViewPostDetails extends Activity {

TextView user_nameTv2, timestamTv2,statusTv2,likeTv2,commentTv2,shareTv2,tvcomlist;
ImageView pro_picImg2, post_picImg2,privacy_picImg2,like_picImg2,comment_picImg2,share_picImg2;
ListView lvcom;
Button btnpost;
EditText etcom;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_post_details);

    intializeAll();

    int like_count = getIntent().getExtras().getInt("like");
    int comment_count = getIntent().getExtras().getInt("comment");
    int share_count = getIntent().getExtras().getInt("share");


    String pro_pic_name = getIntent().getExtras().getString("pro_pic_name");
    String post_pic_name = getIntent().getExtras().getString("post_pic_name");
    String user_name = getIntent().getExtras().getString("username");
    String post_time = getIntent().getExtras().getString("time");
    int privacy_pic = getIntent().getExtras().getInt("privacy_pic");

    String status = getIntent().getExtras().getString("status");

    user_nameTv2.setText(user_name);
    timestamTv2.setText(post_time);
    statusTv2.setText(status);
    privacy_picImg2.setImageResource(privacy_pic);
    likeTv2.setText(like_count+"");
    commentTv2.setText(comment_count+"");
    shareTv2.setText(share_count+"");

    new DownloadImage(pro_pic_name,1).execute();
    new DownloadImage("post_pic_name",2).execute();

    BackgroundTaskLike backgroundTaskLike = new BackgroundTaskLike(this);
    backgroundTaskLike.execute(like_count+"",user_name,post_time);
}

public void intializeAll() {
    pro_picImg2 = (ImageView)findViewById(R.id.image22);
    user_nameTv2 = (TextView)findViewById(R.id.name22);
    timestamTv2 = (TextView)findViewById(R.id.time22);
    statusTv2=(TextView)findViewById(R.id.status22);
    post_picImg2 = (ImageView)findViewById(R.id.postimg22);
    privacy_picImg2 = (ImageView)findViewById(R.id.privacyimg22);
    like_picImg2 = (ImageView) findViewById(R.id.likeimg22);
    comment_picImg2 = (ImageView) findViewById(R.id.commentimg22);
    share_picImg2 = (ImageView)findViewById(R.id.shareimg22);
    likeTv2=(TextView) findViewById(R.id.like22);
    commentTv2=(TextView) findViewById(R.id.comment22);
    shareTv2=(TextView) findViewById(R.id.share22);
    etcom = (EditText) findViewById(R.id.etcomment);
    tvcomlist = (TextView) findViewById(R.id.tvcommentlist);
    lvcom = (ListView) findViewById(R.id.lvcomment);
    btnpost = (Button) findViewById(R.id.btnpost);
}

public class BackgroundTaskLike extends AsyncTask<String, Void, Void> {



    Context ctx;


    public BackgroundTaskLike(Context context) {
        // TODO Auto-generated constructor stub
        this.ctx = context;
    }

    @Override
    protected Void doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        String insert_post_url = "http://accsectiondemo.site11.com/updateLikeCount.php";

            String Like = arg0[0];
            String username = arg0[1];
            String time = arg0[2];

            try {
                URL url = new URL(insert_post_url);
                //connect to URL
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                //sending data using POST method
                httpURLConnection.setRequestMethod("POST");
                //for sending some data to URL 
                httpURLConnection.setDoOutput(true);
                //to write information in buffered writer an output stream object need to be initialized
                OutputStream OS = httpURLConnection.getOutputStream();
                //to write information to URL
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
                String data = URLEncoder.encode("like", "UTF-8") + "="+ URLEncoder.encode(Like,"UTF-8") + "&" + 
                        URLEncoder.encode("username", "UTF-8") + "="+ URLEncoder.encode(username,"UTF-8") + "&" +
                        URLEncoder.encode("time", "UTF-8") + "="+ URLEncoder.encode(time,"UTF-8");
                 bufferedWriter.write(data);
                 bufferedWriter.flush();
                 bufferedWriter.close();
                 OS.close();
                 //get response from server
                 InputStream is = httpURLConnection.getInputStream();
                 is.close();

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }
}
private class DownloadImage extends AsyncTask<Void, Void, Bitmap> {

        String name;
        int count;

        public DownloadImage(String name,int cnt) {
            this.name=name;
            this.count=cnt;
        }

        @Override
        protected Bitmap doInBackground(Void... params) {
            String url = "http://accsectiondemo.site11.com/" + "pictures/" + name + ".jpg";

            try {
                URLConnection connection  = new URL(url).openConnection();
                connection.setConnectTimeout(1000*30);
                connection.setReadTimeout(1000*30);
                return BitmapFactory.decodeStream((InputStream) connection.getContent(),null,null);
            } catch (Exception e) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if(bitmap != null ) {
                if(count==1) {
                   pro_picImg2.setImageBitmap(bitmap);
                }
                else {
                    post_picImg2.setImageBitmap(bitmap);
                }
            }
        }

    }

}
它崩溃了.. 我也调用downloadImage并手动传递参数“pp.jpg”以忽略意图数据,(在服务器中有一张照片被命名为“pp.jpg”)。但这也行不通。

这是日志文件......

  

06-16 14:36:01.045:E / AndroidRuntime(1101):致命异常:主要   06-16 14:36:01.045:E / AndroidRuntime(1101):进程:com.example.finderror,PID:1101   06-16 14:36:01.045:E / AndroidRuntime(1101):java.lang.NullPointerException   06-16 14:36:01.045:E / AndroidRuntime(1101):at com.example.finderror.ViewAdapter $ 1.onClick(ViewAdapter.java:191)   06-16 14:36:01.045:E / AndroidRuntime(1101):在android.view.View.performClick(View.java:4438)   06-16 14:36:01.045:E / AndroidRuntime(1101):在android.view.View $ PerformClick.run(View.java:18422)   06-16 14:36:01.045:E / AndroidRuntime(1101):在android.os.Handler.handleCallback(Handler.java:733)   06-16 14:36:01.045:E / AndroidRuntime(1101):在android.os.Handler.dispatchMessage(Handler.java:95)   06-16 14:36:01.045:E / AndroidRuntime(1101):在android.os.Looper.loop(Looper.java:136)   06-16 14:36:01.045:E / AndroidRuntime(1101):在android.app.ActivityThread.main(ActivityThread.java:5017)   06-16 14:36:01.045:E / AndroidRuntime(1101):at java.lang.reflect.Method.invokeNative(Native Method)   06-16 14:36:01.045:E / AndroidRuntime(1101):at java.lang.reflect.Method.invoke(Method.java:515)   06-16 14:36:01.045:E / AndroidRuntime(1101):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:779)   06-16 14:36:01.045:E / AndroidRuntime(1101):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)   06-16 14:36:01.045:E / AndroidRuntime(1101):at dalvik.system.NativeStart.main(Native Method)

viewAdapter代码在这里......

  

当我不调用Asynctask DownloadImage时,代码正常工作,但我无法在imageView中设置所需的图片。但是,当我称这个应用程序崩溃时。

public class ViewAdapter extends ArrayAdapter {

private Context context;

List list = new ArrayList();

public ViewAdapter(Context context, int resource) {
    super(context, resource);
    this.context = context;
    // TODO Auto-generated constructor stub
}


public void add(ClassDorkar ob) {
    // TODO Auto-generated method stub
    super.add(ob);
    list.add(ob);
}


@Override
public int getCount() {
    // TODO Auto-generated method stub
    return this.list.size();
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return this.list.get(position);
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View row;
    final View intentView;

    row = convertView;
    intentView = row;

    if(row==null) {
        LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            row = layoutInflater.inflate(R.layout.testlayout2,parent,false);

            ImageView pro_picImg2 = (ImageView) row.findViewById(R.id.image2);
            TextView user_nameTv2 = (TextView) row.findViewById(R.id.name2);
            TextView timestamTv2 = (TextView) row.findViewById(R.id.time2);
            TextView statusTv2=(TextView) row.findViewById(R.id.status2);
            ImageView post_picImg2 = (ImageView) row.findViewById(R.id.postimg2);
            ImageView privacy_picImg2 = (ImageView) row.findViewById(R.id.privacyimg2);
            ImageView like_picImg2 = (ImageView) row.findViewById(R.id.likeimg2);
            ImageView comment_picImg2 = (ImageView) row.findViewById(R.id.commentimg2);
            ImageView share_picImg2 = (ImageView) row.findViewById(R.id.shareimg2);
            final TextView likeTv2=(TextView) row.findViewById(R.id.like2);
            TextView commentTv2=(TextView) row.findViewById(R.id.comment2);
            TextView shareTv2=(TextView) row.findViewById(R.id.share2);

            final ClassDorkar cd = (ClassDorkar) getItem(position);

            pro_picImg2.setImageBitmap(cd.getPro_pic());
            user_nameTv2.setText(cd.getUsername());
            timestamTv2.setText(cd.getTime());
            statusTv2.setText(cd.getStatus());
            post_picImg2.setImageBitmap(cd.getPost_pic());

            privacy_picImg2.setImageResource(cd.getPrivacy());

            String s = cd.getLike() + "";
            likeTv2.setText(s);
             s = cd.getComment() + "";
            commentTv2.setText(s);
            s = cd.getShare() + "";
            shareTv2.setText(s);

        like_picImg2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int like = cd.getLike();
                String user_name = cd.getUsername();
                String post_time = cd.getTime();
                like++;
                cd.setLike(like);
                String s = like + "";
                likeTv2.setText(s);

                Intent intent = new Intent(intentView.getContext(), ViewPostDetails.class);
                //intent.putExtra("pro_pic_name", cd.getPro_pic_name());
                //intent.putExtra("post_pic_name", cd.getPost_pic_name());
                intent.putExtra("like", like);
                intent.putExtra("comment", cd.getComment());
                intent.putExtra("share", cd.getShare());
                intent.putExtra("username", user_name);
                intent.putExtra("time", post_time);
                intent.putExtra("privacy_pic",cd.getPrivacy());
                intent.putExtra("status", cd.getStatus());
                context.startActivity(intent);
            }
        });

        return row;
}

}

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。虽然这是偶然的,但它确实有效。

  

我更改了Asynctask名称,应用程序正在运行。