开发者

Crash while downloading file with AsyncTask

I'm developing an app for Android to download the pic from all the friends. I successfully made my app logging in. Now, I need to parse a JSON and download some of the pics. Here the sources:

FacebookPicDownloader (asynctask to download all the pics):

public class FacebookPicDownloader extends AsyncTask <String, Integer, Integer>{
    Context context;
    private final int MAX_BUFFER_SIZE = 2048;
    String id;
    int length;

    public FacebookPicDownloader (Context context){
        this.context = context;
    }

    //http://graph.facebook.com/ + userid + /picture?type=large to download the photos
    @Override
    protected Integer doInBackground(String... params) {
        for (int i=0; i<params.length; i++){
        try {
            URL mUrl = new URL("http://graph.facebook.com/" + params[i] + "/picture?type=large");
            HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection();
            connection.connect();
            length = connection.getContentLength();
            int downloaded = 0;
            File file = new File ("/sdcard/syncro/");
            if (!file.exists() || !file.isDirectory()){
                file.mkdir();
            }
            id = params[0];
            file = new File ("/sdcard/syncro/" + id);
            FileOutputStream fos = new FileOutputStream (file);
            //Start downloading
            InputStream stream = connection.getInputStream();
            byte [] buffer = new byte [(length < MAX_BUFFER_SIZE) ? length : MAX_BUFFER_SIZE];
            int read;
            while ((read=stream.read(buffer)) != -1){
                fos.write(buffer, 0, read);
                downloaded += read;
            }
            fos.close();
        } catch (Exception e){
            return 2;
        }
        }
        return 1;
    }

Manager.java, another AsyncTask that calls FacebookPicDownloader

import java.util.ArrayList;

import org.json.*;
import com.gnufabio.syncro.util.Util;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.util.Log;

import com.facebook.android.*;
import com.gnufabio.syncro.util.*;

public class Manager extends AsyncTask<String, Integer, Integer>{
    Context context; 
    Facebook facebook;
    ProgressDialog dialog;

    public void doStuff(Facebook facebook, Context context, String ... params){
        this.context = context;
        this.facebook = facebook;
        this.execute(params);
    }

    @Override 
    protected void onPreExecute(){
        dialog = ProgressDialog.show(context, "Wait" , " Loading. Please wait ... ", true);
        dialog.setCancelable(false);
    }

    @Override
    protected Integer doInBackground(String... params) {
        String friendlist;
        try {
            friendlist = facebook.request("me/friends");
            FileWriterThread filewriter = new FileWriterThread();
            filewriter.writeFile(friendlist, "/sdcard/syncro/friends");
        } catch (Exception e) {
            friendlist = "";
        }

        String previous = "[NONE]";
        ArrayList validContacts = new ArrayList<String>();
        Cursor nameCur = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, ContactsContract.Data.MIMETYPE + " = ?", new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE }, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
        while (nameCur.moveToNext()) {
            String display = nameCur.getS开发者_JAVA百科tring(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
            if (display != null && !(display.contains(previous) || display.equalsIgnoreCase(previous)) && display.contains(" ")){
                Log.d("SYNCRO", "Valid contact found: " + display);
                validContacts.add(display);
                previous = display;
            }
        }
        nameCur.close();
        try {
            ArrayList idToDownload = new ArrayList <String>();
            JSONArray jFriendList = new JSONArray(new JSONObject(friendlist).getString("data"));
            for (int i = 0; i < jFriendList.length(); i++){
                JSONObject jFriend = jFriendList.getJSONObject(i);
                for (int y = 0; y < validContacts.toArray().length; y++){
                    if (jFriend.getString("name").equals((String)(validContacts.get(y)))){
                        String id = jFriend.getString("id");
                        Log.d("SYNCRO", "Adding pic for id \"" + id + "\"");
                        idToDowload.add(id);
                    }
                }
            }
            FacebookPicDownloader downloader = new FacebookPicDownloader(context);
            downloader.execute((String[]) idToDownload.toArray());

        } catch (JSONException e) {
            Log.d("SYNCRO", e.getMessage());
        }


        return null;
    }

    @Override
    protected void onPostExecute(Integer result){
        dialog.dismiss();
    }
}

The problem is that it downloads just the first pic, and then the app crashes...here the logcat:

D/szipinf ( 7785): Initializing inflate state 
E/AndroidRuntime( 7735): FATAL EXCEPTION: AsyncTask #1 
E/AndroidRuntime( 7735): java.lang.RuntimeException: An error occured while executing doInBackground() 
E/AndroidRuntime( 7735):    at android.os.AsyncTask$3.done(AsyncTask.java:200) 
E/AndroidRuntime( 7735):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274) 
E/AndroidRuntime( 7735):    at java.util.concurrent.FutureTask.setException(FutureTask.java:125) 
E/AndroidRuntime( 7735):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308) 
E/AndroidRuntime( 7735):    at java.util.concurrent.FutureTask.run(FutureTask.java:138) 
E/AndroidRuntime( 7735):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088) 
E/AndroidRuntime( 7735):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581) 
E/AndroidRuntime( 7735):    at java.lang.Thread.run(Thread.java:1019) 
E/AndroidRuntime( 7735): Caused by: java.lang.ClassCastException: [Ljava.lang.Object; 
E/AndroidRuntime( 7735):    at com.gnufabio.syncro.Manager.doInBackground(Manager.java:78) 
E/AndroidRuntime( 7735):    at com.gnufabio.syncro.Manager.doInBackground(Manager.java:1) 
E/AndroidRuntime( 7735):    at android.os.AsyncTask$2.call(AsyncTask.java:185) 
E/AndroidRuntime( 7735):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306) 
E/AndroidRuntime( 7735):    ... 4 more W/ActivityManager(  541):   Force finishing activity com.gnufabio.syncro/.SuperSyncronizerActivity D/szipinf ( 7797): Initializing inflate state D/szipinf ( 7797): Initializing zlib to inflate D/dalvikvm( 7797): GC_CONCURRENT freed 224K, 44% free 3519K/6215K, external 0K/0K, paused 3ms+3ms 
E/WindowManager( 7735): Activity com.gnufabio.syncro.SuperSyncronizerActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4051c538 that was originally added here 
E/WindowManager( 7735): android.view.WindowLeaked: Activity com.gnufabio.syncro.SuperSyncronizerActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4051c538 that was originally added here 
E/WindowManager( 7735):     at android.view.ViewRoot.<init>(ViewRoot.java:260) 
E/WindowManager( 7735):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148) 
E/WindowManager( 7735):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91) 
E/WindowManager( 7735):     at android.view.Window$LocalWindowManager.addView(Window.java:424) 
E/WindowManager( 7735):     at android.app.Dialog.show(Dialog.java:241) 
E/WindowManager( 7735):     at android.app.ProgressDialog.show(ProgressDialog.java:110) 
E/WindowManager( 7735):     at android.app.ProgressDialog.show(ProgressDialog.java:93) 
E/WindowManager( 7735):     at com.gnufabio.syncro.Manager.onPreExecute(Manager.java:36) 
E/WindowManager( 7735):     at android.os.AsyncTask.execute(AsyncTask.java:391) 
E/WindowManager( 7735):     at com.gnufabio.syncro.Manager.doStuff(Manager.java:31) 
E/WindowManager( 7735):     at com.gnufabio.syncro.SuperSyncronizerActivity$2.onClick(SuperSyncronizerActivity.java:73) 
E/WindowManager( 7735):     at android.view.View.performClick(View.java:2486) 
E/WindowManager( 7735):     at android.view.View$PerformClick.run(View.java:9130) 
E/WindowManager( 7735):     at android.os.Handler.handleCallback(Handler.java:587) 
E/WindowManager( 7735):     at android.os.Handler.dispatchMessage(Handler.java:92) 
E/WindowManager( 7735):     at android.os.Looper.loop(Looper.java:130) 
E/WindowManager( 7735):     at android.app.ActivityThread.main(ActivityThread.java:3694) 
E/WindowManager( 7735):     at java.lang.reflect.Method.invokeNative(Native Method) 
E/WindowManager( 7735):     at java.lang.reflect.Method.invoke(Method.java:507) 
E/WindowManager( 7735):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841) 
E/WindowManager( 7735):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599) 
E/WindowManager( 7735):     at dalvik.system.NativeStart.main(Native Method) D/dalvikvm( 7797): GC_CONCURRENT freed 171K, 41% free 3888K/6535K, external 0K/0K, paused 3ms+4ms

Thanks to anyone will help me.


The crash is caused by this code: (String[]) idToDownload.toArray().

Try creating a new String array instead of using the cast:

Replace the line downloader.execute((String[]) idToDownload.toArray());

By:

String[] stringArray= new String[idToDownload.size()];
idToDownload.toArray(stringArray);
downloader.execute(stringArray);

KR

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜