2017-04-04 221 views
0

我試圖下載我上傳到Firebase存儲上的JSON文件。我嘗試了一些東西,但沒有爲我工作。從Firebase存儲下載JSON文件

在代碼null總是被這個doInBackground()方法返回,這個方法無法進一步處理我的應用程序。

protected String doInBackground(String... strings) { 
     Log.e("Test", "DOINBG Working.."); 
     String storageUrl = "https://firebasestorage.googleapis.com/v0/b/frost-bird-1d290." + 
       "appspot.com/o/images.json?alt=media&token=b0a511d4-f0ea-4ee0-a063-69b7fd050f49"; 
     FirebaseStorage firebaseStorage = FirebaseStorage.getInstance(); 
     StorageReference reference = firebaseStorage.getReferenceFromUrl(storageUrl); 
     final File localFile; 
     try { 
      localFile = File.createTempFile("images", "json"); 
      reference.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() { 
       @Override 
       public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) { 
        Toast.makeText(getContext(), "File downloaded successfully.", Toast.LENGTH_SHORT).show(); 
        try { 
         BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(localFile))); 
         StringBuilder result = new StringBuilder(); 
         String line = null; 
         while((line.concat(String.valueOf(reader.read()))) != null){ 
          Log.e("Test", "Result - "+ result); 
          result.append(line); 
         } 
         finalRes.concat(result.toString()); 
        } catch (FileNotFoundException e) { 
         e.printStackTrace(); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 

       } 
      }).addOnFailureListener(new OnFailureListener() { 
       @Override 
       public void onFailure(@NonNull Exception e) { 
        Log.e("Test", "Failed"); 
        Toast.makeText(getContext(), "File downloading failed.", Toast.LENGTH_LONG).show(); 
       } 
      }); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     Log.e("Test", "String Downloaded- "+finalRes); 
     return finalRes; 
    } 

protected void onPostExecute(String result) { 
     Log.e("Test", "onPostExecute Working.."+"\nString in onPostExecute Method-" +result); 
     progressDialog.dismiss(); 
     List<String> data = new ArrayList<>(); 
     progressDialog.dismiss(); 
     try{ 
      JSONArray jsonArray = new JSONArray(result); 

      for(int i=0;i<jsonArray.length();i++){ 
       JSONObject jObject = jsonArray.getJSONObject(i); 
       data.add(jObject.getString("ipl_image")); 
      } 

      recyclerViewGallery = (RecyclerView) getView().findViewById(R.id.recyclerviewgallery); 
      adapter = new GalleryPhotoAdapter(getContext()); 
      recyclerViewGallery.setAdapter(adapter); 
      recyclerViewGallery.setLayoutManager(new LinearLayoutManager(getContext())); 
     } 
     catch (JSONException e){ 
      Toast.makeText(getContext(),e.toString(), Toast.LENGTH_LONG).show(); 
     } 
    } 

另外我想告訴你它永遠不會執行onSuccess()方法。我不知道爲什麼。

錯誤日誌:

FATAL EXCEPTION: main Process: com.metrowebz.data.ipl2017, PID: 9526 
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference 
    at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116) 
    at org.json.JSONTokener.nextValue(JSONTokener.java:94) 
    at org.json.JSONArray.<init>(JSONArray.java:92) 
    at org.json.JSONArray.<init>(JSONArray.java:108) 
    at com.metrowebz.data.ipl2017.NavDFragments.GalleryFragment$AsyncFetch.onPostExecute(GalleryFragment.java:126) 
    at com.metrowebz.data.ipl2017.NavDFragments.GalleryFragment$AsyncFetch.onPostExecute(GalleryFragment.java:61) 
    at android.os.AsyncTask.finish(AsyncTask.java:651) 

誰能請幫助我如何解決這個問題?

+0

發佈您的錯誤日誌。 –

+0

你真的需要做這個程序嗎? –

+0

你有任何其他建議嗎? –

回答

0

您忽略了文件下載的異步性質。下載完成後,成功和失敗偵聽器纔會運行。當您從doInBackground()返回時,成功偵聽器尚未運行,因此finalRes的值尚未設置。

因爲您在後臺線程中執行此處理,您可以更改代碼以等待下載完成。像這樣:

@Override 
protected String doInBackground(String... params) { 
    Log.e("Test", "DOINBG Working.."); 
    String storageUrl = "https://firebasestorage.googleapis.com/v0/b/frost-bird-1d290." + 
      "appspot.com/o/images.json?alt=media&token=b0a511d4-f0ea-4ee0-a063-69b7fd050f49"; 
    FirebaseStorage firebaseStorage = FirebaseStorage.getInstance(); 
    StorageReference reference = firebaseStorage.getReferenceFromUrl(storageUrl); 
    final File localFile; 
    try { 
     localFile = File.createTempFile("images", "json"); 
     FileDownloadTask task = reference.getFile(localFile); 
     try { 
      Tasks.await(task); // or use await with timeout: Tasks.await(task, 30, TimeUnit.SECONDS) 
      if (task.isSuccessful()) { 
       Toast.makeText(getContext(), "File downloaded successfully.", Toast.LENGTH_SHORT).show(); 
       try { 
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(localFile))); 
        StringBuilder result = new StringBuilder(); 
        String line = null; 
        while((line.concat(String.valueOf(reader.read()))) != null){ 
         Log.e("Test", "Result - "+ result); 
         result.append(line); 
        } 
        finalRes.concat(result.toString()); 
       } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } else { 
       Log.e("Test", "Failed: " + task.getException().getMessage()); 
       Toast.makeText(getContext(), "File downloading failed", Toast.LENGTH_LONG).show(); 
      } 
     } catch (ExecutionException e) { 
      e.printStackTrace(); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    Log.e("Test", "String Downloaded- "+finalRes); 
    return finalRes; 
} 
+0

它仍然沒有下載任何東西,並返回null –

+0

好吧現在它的工作,我認爲在你的答案是問題是與行BufferedReader讀取器=新的BufferedReader(新的InputStreamReader new FileInputStream(localFile)));'所以我用'InputStream inputStream = new FileInputStream(file);'替換了它,並且它開始讀取並返回所需的json字符串。 –