有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java调用异步任务类不起作用

我肯定我做错了什么,Android新手,我已经将URL存储在for循环中的字符串中,需要使用AsyncTask从该URL获取图像。对安卓系统来说很陌生,所以我遇到了一些问题。感谢您的帮助

二等舱。爪哇

package edu.colum.iam.JSON;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import 安卓.app.Activity;
import 安卓.os.Bundle;
import 安卓.widget.TextView;
import 安卓.widget.Toast;

public class SecondClass extends Activity {
private TextView first, second, third;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);

        first = (TextView)findViewById(R.id.firsttv);
        second = (TextView)findViewById(R.id.secondtv);
        third = (TextView)findViewById(R.id.thirdtv);

        String id = getIntent().getStringExtra("id");
        System.out.println(id);

        String response = readBuilding(id.trim());
        System.out.println(response);

        try {
            JSONObject jsonObj = new JSONObject(response);
            if(jsonObj.length()>0)
            {
                String CourseName = jsonObj.getString("CourseName");
                String CourseNumber = jsonObj.getString("CourseNumber");
                String CourseDescription = jsonObj.getString("CourseDescription");
                JSONArray arrayOfImages = jsonObj.getJSONArray("Images");
                String theImage = arrayOfImages.get(0).toString(); //getting first image in the array and returning the link as a string


                int arrSize = arrayOfImages.length();

                List<String> urlOfImage = new ArrayList<String>(arrSize);

                first.setText("CourseName:- "+CourseName);
                second.setText("CourseNumber:- "+CourseNumber);
                third.setText("CourseDescription:- "+CourseDescription);
                for(int i = 0; i < arrayOfImages.length(); ++i)
                {
                    theImage = arrayOfImages.get(i).toString();
                    urlOfImage.add(theImage);
                    ImageDownloadTask(theImage);
                }


            }
        } catch (Exception e){
            e.printStackTrace();
        }


    }

    public String readBuilding(String id)
    {
        return postJSON("http://iam.colum.edu/portfolio/api/course/"+id+"?json=True");

    }

    private String postJSON(String stringURL) {
        StringBuilder builder = new StringBuilder();
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();

        HttpGet httpget = new HttpGet(stringURL);

        try {

            httpget.addHeader("Content-Type","application/json; charset=utf-8");


            HttpResponse response = httpclient.execute(httpget);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return builder.toString();
    }
}

图像下载任务。爪哇

package edu.colum.iam.JSON;

import java.io.InputStream;
import java.lang.ref.WeakReference;

import 安卓.graphics.Bitmap;
import 安卓.graphics.BitmapFactory;
import 安卓.os.AsyncTask;
import 安卓.util.Log;
import 安卓.widget.ImageView;

public class ImageDownloadTask extends AsyncTask<String, Void, Bitmap> {

    /** The url from where to download the image. */
    private String url;

    /** Reference to the view which should receive the image */
    private final WeakReference<ImageView> imageRef;

    /**
     * Constructor.
     * 
     * @param imageView
     *            The ImageView which will receive the image.
     */
    public ImageDownloadTask(ImageView imageView) {
        imageRef = new WeakReference<ImageView>(imageView);
    }

    /**
     * This function will be executed to download the image in a background
     * process.
     * 
     */
    @Override
    protected Bitmap doInBackground(String... params) {
        try {
            InputStream in = new java.net.URL(url).openStream();
            Bitmap bitmap = BitmapFactory.decodeStream(in);
            return bitmap;
        } catch (Exception e) {
            Log.e("ImageDownload", e.getMessage());
        }
        return null;
    }

    /**
     * This function will be called after the image download and attaches
     * the bitmap to the ImageView.
     * 
     */
    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (isCancelled()) {
            bitmap = null;
        }

        if (imageRef != null) {
            ImageView imageView = imageRef.get();
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
    }

}

共 (2) 个答案

  1. # 1 楼答案

    对于通过URL下载图像,我建议使用第三方库。例如毕加索。 要下载图像,您只需编写以下内容:

    Picasso.with(SecondClass.this).load(url).into(imageView);

  2. # 2 楼答案

    这里可能会有更多问题(比如可能在主线程上访问网络?),但是这个ImageDownloadTask(theImage);实际上不会执行你的AsyncTask。它甚至不应该编译。你会想要new ImageDownloadTask(theImage).execute();