2

我正在開發Android應用程序,以便從所有朋友處下載圖片。我成功地讓我的應用程序登錄。現在,我需要解析一個JSON並下載一些圖片。這裏來源:使用AsyncTask下載文件時發生崩潰

FacebookPicDownloader(的AsyncTask下載所有圖片):

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,另一個的AsyncTask調用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.getString(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(); 
    } 
} 

的問題是,它只下載第一張照片,然後應用程序崩潰...在這裏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 [email protected] that was originally added here 
E/WindowManager(7735): android.view.WindowLeaked: Activity com.gnufabio.syncro.SuperSyncronizerActivity has leaked window com.android.internal.policy.impl.Phone[email protected] 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 

感謝任何人都會幫助我。

+1

你得到一個ClassCastException。嘗試調試並檢查。你可能會得到一個線索。引起:java.lang.ClassCastException:[Ljava.lang.Object; E/AndroidRuntime(7735):在com.gnufabio.syncro.Manager.doInBackground(Manager.java:78) –

+0

嗨, 這有點令人困惑,因爲你說它適用於第一張圖片。 也許這個ID有什麼問題? 你傳遞一個字符串數組來啓動facebook下載器,它包含一個ID列表 - 也許做一個快速調試器檢查,或者只是一個打印出來,看看所有的ID是否實際ID和一致? URL mUrl = new URL(「http://graph.facebook.com/」+ params [i] +「/ picture?type = large」); 有可能類轉換異常正在發生,因爲您試圖將輸入流轉換爲文件並將其保存,但輸入流並未給出您所期望的 – ryvianstyron

回答

0

崩潰是由以下代碼引起的:(String[]) idToDownload.toArray()

嘗試創建一個新的String數組,而不是使用演員:

替換行 downloader.execute((String[]) idToDownload.toArray());

通過:

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

KR