线程退出时未捕获异常。从服务器加载图像

问题描述 投票:0回答:1

我正在尝试创建一个viewPager,从我使用XAMPP设置的服务器加载图像。但是每次我在三星Galaxy S3上运行应用程序时,只要我打开活动,应用程序就会在没有错误或ANR消息的情况下关闭,它会立即结束。在我的logCat中,它说的是:线程退出时带有未捕获的异常。以下是我的代码,请告诉我如何解决这个问题。我为凌乱的代码道歉。

活动

    package com.example.nowlpractice;

    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.Color;
    import android.graphics.drawable.Drawable;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentActivity;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentStatePagerAdapter;
    import android.support.v4.util.LruCache;
    import android.support.v4.view.ViewPager;
    import android.util.Log;
    import android.view.Display;
    import android.view.ViewGroup;
    import android.view.WindowManager;
    import android.widget.ImageView;

    public class ImageDetailActivity extends FragmentActivity {
    public static final String EXTRA_IMAGE = "extra_image";

    private ImagePagerAdapter mAdapter;
    private ViewPager mPager;
    ImageView mImageView;
    public static int width;
    public static int height;

    // A static dataset to back the ViewPager adapter
    public final static Integer[] imageResIds = new Integer[] {
            R.drawable.koala, R.drawable.img1, R.drawable.img2,
            R.drawable.img3, R.drawable.koala, R.drawable.img5, R.drawable.img6,
            R.drawable.img7, R.drawable.img8, R.drawable.img9, R.drawable.img10,   
    R.drawable.img11,
            R.drawable.img12, R.drawable.img13, R.drawable.img14, R.drawable.img15,
            R.drawable.img16, R.drawable.img17, R.drawable.img18, R.drawable.img19, 
    R.drawable.img20};

    public final static String[] imageUrl = new String[] {
   "img","img1","img2","img3","img4","img5","img6","img7","img8","img9","img10","img11",       
    "img13","img14",
        "img15","img16",
        "img17","img18","img19","img20"
    };



    public static String[] names = new String[] {
            "KYRI IOULIANOU", "THABANG MNGUNI", "YIANNI CREASE",
            "STEFANO CREASE", "CONSTANTINOS PRIMIKIRIOS", "MEGAN PATTERSON"
    };

    public static String[] clubsNames = new String[] {
        "KONG", "TABOO", "VELVET",
        "GREENSIDE", "BIG MAMAS HOUSE", "HOOTERS"

    };

    public static LruCache<String, Bitmap> mMemoryCache;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_detail); // Contains just a ViewPager

     // Get max available VM memory, exceeding this amount will throw an
        // OutOfMemory exception. Stored in kilobytes as LruCache takes an
        // int in its constructor.
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

        // Use 1/8th of the available memory for this memory cache.
        final int cacheSize = maxMemory / 8;

        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                // The cache size will be measured in kilobytes rather than
                // number of items.
                Log.d("Cache", "Inititated mem cache");
                return bitmap.getByteCount() / 1024;

            }

            @Override
            protected void entryRemoved( boolean evicted, String key, Bitmap oldValue,  
    Bitmap newValue ) {
              oldValue.recycle();
              Log.d("REMOVED FROM CACHE", "Bitmap removed from cache");
            }
        };

        Display myDisplay = ((WindowManager) 
    getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        width =myDisplay.getWidth();
        height=myDisplay.getHeight();

        mAdapter = new ImagePagerAdapter(getSupportFragmentManager(), Integer.MAX_VALUE);
        mPager = (ViewPager) findViewById(R.id.myviewpager);
        mPager.setAdapter(mAdapter);
        mPager.setOffscreenPageLimit(1);
        Log.d("ViewPager", "Launched PageAdapter");

        ScrollTextView scrolltext=(ScrollTextView) findViewById(R.id.scrolltext);
        scrolltext.setText("WELCOME TO NIGHT OWL");
        scrolltext.setTextColor(Color.BLACK);
        scrolltext.startScroll(width/2500.0, true);

    }

    public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (getBitmapFromMemCache(key) == null) {
            mMemoryCache.put(key, bitmap);
        }
    }

    public Bitmap getBitmapFromMemCache(String key) {
        return mMemoryCache.get(key);
    }

    public void loadBitmap(String resId, ImageView imageView) {
        Log.d("LoadBitmap", "LoadBitmapStarted");
        final String imageKey = resId;

        final Bitmap bitmap = getBitmapFromMemCache(imageKey);
        if (bitmap != null) {
            Drawable drawable = new RoundedCornersDrawable(getResources(), bitmap);
            imageView.setImageDrawable(drawable);
        } else {
            imageView.setImageResource(R.drawable.empty_photo);
            Log.d("Start Async", "About to start async task");
            BitmapWorkerTask task = new BitmapWorkerTask(imageView, getResources(), 
    ImageDetailActivity.this);
            task.execute(resId);
        }
    }

    public static class ImagePagerAdapter extends FragmentStatePagerAdapter {
        private final int mSize;
        int pos;

        public ImagePagerAdapter(FragmentManager fm, int size) {
            super(fm);
            mSize = size;
        }

        @Override
        public int getCount() {
            return mSize;
        }

        @Override
        public Fragment getItem(int position) {
            pos = position%21;
            Log.d("Just about to launch fragment", "yOU KNOW");
            return ImageDetailFragment.newInstance(pos);

            //return ImageDetailFragment.newInstance(position);
        }
    }
    }


    //************************************************************************************
    //************************************************************************************

碎片

package com.example.nowlpractice;

import android.R.color;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class ImageDetailFragment extends Fragment {
private static final String IMAGE_DATA_EXTRA = "resId";
private int mImageNum;
private ImageView mImageView;

static ImageDetailFragment newInstance(int imageNum) {
    final ImageDetailFragment f = new ImageDetailFragment();
    final Bundle args = new Bundle();
    args.putInt(IMAGE_DATA_EXTRA, imageNum);
    f.setArguments(args);
    return f;
}

// Empty constructor, required as per Fragment docs
public ImageDetailFragment() {}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mImageNum = getArguments() != null ? getArguments().getInt(IMAGE_DATA_EXTRA) : -1;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // image_detail_fragment.xml contains just an ImageView
    final View v = inflater.inflate(R.layout.image_detail_fragment, container, false);
    mImageView = (ImageView) v.findViewById(R.id.imageView1);

    //TextView tv = (TextView) v.findViewById(R.id.textView1);
    //tv.setText(ImageDetailActivity.names[mImageNum]);
    //tv.setTextColor(Color.YELLOW);
    //tv.setBackgroundColor(Color.BLACK);

    //TextView tv2 = (TextView) v.findViewById(R.id.textView2);
    //tv2.setText(ImageDetailActivity.clubsNames[mImageNum]);
    //tv2.setTextColor(Color.YELLOW);
    //tv2.setBackgroundColor(Color.BLACK);

    return v;   
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (ImageDetailActivity.class.isInstance(getActivity())) {



        final String resId = ImageDetailActivity.imageUrl[mImageNum];

        // Call out to ImageDetailActivity to load the bitmap in a background thread
        Log.d("Fragment", "About to launch loadBitmap");
        ((ImageDetailActivity) getActivity()).loadBitmap(resId, mImageView);
        //Call to Activity to get the textView text
        //((ImageDetailActivity) getActivity()).loadText(resId, tv);
    }

    //Bitmap bmp = BitmapFactory.decodeResource(getResources(),  
ImageDetailActivity.imageResIds[mImageNum]);
    //RoundedCornersDrawable drawable = new RoundedCornersDrawable(getResources(), 
bmp);
    //mImageView.setImageDrawable(drawable);

   // final int resId = ImageDetailActivity.imageResIds[mImageNum];
   // mImageView.setImageResource(resId); // Load image into ImageView
}
}

ASYNC任务

package com.example.nowlpractice;


import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

class BitmapWorkerTask extends AsyncTask<String, Void, Drawable> {
private final WeakReference<ImageView> imageViewReference;
private String data = "";
Resources res;
public static Context context;

public BitmapWorkerTask(ImageView imageView, Resources mRes, Context c) {
    // Use a WeakReference to ensure the ImageView can be garbage collected
    imageViewReference = new WeakReference<ImageView>(imageView);
    res = mRes;
    context = c;
}

// Decode image in background.
@Override
protected Drawable doInBackground(String... params) {
    data = "http://172.29.153.12:80/webservice/images/" + params[0];
    //TOOOOOOOOOODOOOOOOOOOOOOOOOOOOOOOOOO
    Bitmap bmp;
    try {
        Log.d("decode bitmap", "About to decode bitmap");
        bmp = decodeSampledBitmapFromResource(res, data, 400, 400);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        Log.d("Error", "MalformedUrlException");
        e.printStackTrace();
        bmp = BitmapFactory.decodeResource(res, R.drawable.empty_photo);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.d("Error", "IOException");
        e.printStackTrace();
        bmp = BitmapFactory.decodeResource(res, R.drawable.empty_photo);
    }
    //TODO ADJUST REQ DIMENSIONS ACCORDING TO SCREEN DENSITIY!!!!
    ImageDetailActivity.mMemoryCache.put(String.valueOf(params[0]), bmp);
    Log.d("ADDED TO CACHE", "Bitmap added to cache");
    Drawable drawable = new RoundedCornersDrawable(res, bmp);
    return drawable;
}

// Once complete, see if ImageView is still around and set bitmap.
@Override
protected void onPostExecute(Drawable bitmap) {
    if (imageViewReference != null && bitmap != null) {
        final ImageView imageView = imageViewReference.get();
        if (imageView != null) {
            imageView.setImageDrawable(bitmap);
            imageView.getLayoutParams().width = ImageDetailActivity.width;
            imageView.getLayoutParams().height = ImageDetailActivity.width;
        }
    }
}

public static Bitmap decodeSampledBitmapFromResource(Resources res, String resId,
        int reqWidth, int reqHeight) throws MalformedURLException, IOException {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;

    if(isConnectionAvailable(context)){
        Log.d("Connection", "Connection is available, launching ulrconn");
        URLConnection conn = new URL(resId).openConnection();
        conn.connect();
        Log.d("Decode", "About to decode");
        BitmapFactory.decodeStream(conn.getInputStream(),null, options);
        Log.d("Decode2", "Just decoded bitmap");


    //BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeStream(conn.getInputStream(),null, options);

    }



    if(!isConnectionAvailable(context)){
        Log.d("No connection", "No connection");
        return BitmapFactory.decodeResource(res, R.drawable.empty_photo);
    }
    return BitmapFactory.decodeResource(res, R.drawable.empty_photo);
    //else{ return BitmapFactory.decodeResource(res, R.drawable.empty_photo); }
    //return BitmapFactory.decodeResource(res, resId, options);
}

public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;

if (height > reqHeight || width >= reqWidth) {

    final int halfHeight = height/2;
    final int halfWidth = width/2;

    //Calculate the largest inSampleSize value that is a power of 2 and keeps both
    // height and width larger than the requested height and width.
    while ((halfHeight / inSampleSize) > reqHeight
            && (halfWidth / inSampleSize) > reqWidth) {
        inSampleSize *= 2;
    }
}

return inSampleSize;
}

public static boolean isConnectionAvailable(Context context) {

    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) {
        NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()
                && netInfo.isConnectedOrConnecting()
                && netInfo.isAvailable()) {
            return true;
        }
    }
    return false;
}

}    

LOGCAT

08-12 21:05:14.290: D/OpenGLRenderer(30029): Enabling debug mode 0
08-12 21:05:15.255: D/ViewPager(30029): Launched PageAdapter
08-12 21:05:15.275: D/Just about to launch fragment(30029): yOU KNOW
08-12 21:05:15.275: D/Just about to launch fragment(30029): yOU KNOW
08-12 21:05:15.280: D/Fragment(30029): About to launch loadBitmap
08-12 21:05:15.280: D/LoadBitmap(30029): LoadBitmapStarted
08-12 21:05:15.285: D/Start Async(30029): About to start async task
08-12 21:05:15.285: D/decode bitmap(30029): About to decode bitmap
08-12 21:05:15.285: D/Fragment(30029): About to launch loadBitmap
08-12 21:05:15.285: D/LoadBitmap(30029): LoadBitmapStarted
08-12 21:05:15.285: D/Start Async(30029): About to start async task
08-12 21:05:15.290: D/decode bitmap(30029): About to decode bitmap
08-12 21:05:15.290: W/dalvikvm(30029): threadid=11: thread exiting with uncaught  
exception  
(group=0x41f8c700)
08-12 21:05:15.290: W/dalvikvm(30029): threadid=12: thread exiting with uncaught   
exception   
(group=0x41f8c700)
08-12 21:05:15.290: I/Process(30029): Sending signal. PID: 30029 SIG: 9

我已经尝试使用日志来查找问题,但这没有帮助。我尝试了一切

android sql-server android-asynctask imageview inputstream
1个回答
1
投票

调查代码很难。我只是删除所有加载位图相关的代码,并替换为Picasso库。

该库可以很好地处理来自后台不同来源的图像。可以缓存图像,可以指定临时占位符,错误占位符等。

如果你不知道怎么做,就没有必要自己实施。

如果你真的必须自己做,那么先阅读Android Developers page。谷歌人员详细解释了如何实施它。

© www.soinside.com 2019 - 2024. All rights reserved.