2011-11-30 2 views
0

나는 내 채널에 대한 응용 프로그램을 짓고 있어요지우기 "캐시"들의 OnDestroy


수행하려고 무엇. Google에서 JSON을 통해 데이터를 가져 와서 SimpleAdapter를 통해 내 ListView에 채 웁니다.

내 SimpleAdapter에서 사진을 보여줄 수 있으므로 SDCard에 저장합니다. 문제는 이제 앱이 죽으면 강제 종료 오류가 발생합니다. 그 이유는 사진이 이미 있기 때문입니다.

질문


어떻게들의 OnDestroy 내 SDCard에의 "캐시"이미지를 delte 수()?

아래에서 앱 코드를 찾으십시오. 사전에 도와 주셔서 감사합니다! 사용자가 응용 프로그램을 제거

경우 외부 스토리지에

코드


ChannelActivity.java

package de.stepforward; 

import java.io.BufferedInputStream; 
import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.URI; 
import java.net.URL; 
import java.net.URLConnection; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.Map; 


import org.apache.http.util.ByteArrayBuffer; 
import org.json.JSONArray; 
import org.json.JSONObject; 

import de.stepforward.web.ShowVideo; 


import android.app.ListActivity; 
import android.content.Intent; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.drawable.BitmapDrawable; 
import android.graphics.drawable.Drawable; 
import android.os.Bundle; 
import android.os.Environment; 
import android.util.Log; 
import android.view.View; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.AdapterView; 
import android.widget.ImageView; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 



public class ChannelActivity extends ListActivity { 


    @Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    //Cache löschen wenn Applikation gekillt wird 


    String result = ""; 
    String line = null; 
    final ArrayList<HashMap<String, Object>> mylist = new ArrayList<HashMap<String, Object>>(); 


    //get the Data from URL 
    try{ 
    URL url = new URL("http://gdata.youtube.com/feeds/mobile/users/TheStepForward/uploads?alt=json&format=1"); 

    URLConnection conn = url.openConnection(); 
    StringBuilder sb = new StringBuilder(); 
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 

    //read d response till d end 
    while ((line = rd.readLine()) != null) { 
    sb.append(line + "\n"); 
    } 
    result = sb.toString(); 
    Log.v("log_tag", "Append String " + result); 
    } catch (Exception e) { 
    Log.e("log_tag", "Error converting result " + e.toString()); 
    } 

    try{ 
     JSONObject json = new JSONObject(result); 
     JSONObject feed = json.getJSONObject("feed"); 
     JSONArray entrylist = feed.getJSONArray("entry"); 

     for(int i=0;i<entrylist.length();i++){ 
      //Get Title 
      JSONObject movie = entrylist.getJSONObject(i); 
      JSONObject title = movie.getJSONObject("title"); 
      String txtTitle = title.getString("$t"); 
      Log.d("Title", txtTitle); 

      //Get Description 
      JSONObject content = movie.getJSONObject("content"); 
      String txtContent = content.getString("$t"); 
      Log.d("Content", txtContent); 

      //Get Link 
      JSONArray linklist = movie.getJSONArray("link"); 
      JSONObject link = linklist.getJSONObject(0); 
      String txtLink = link.getString("href"); 
      Log.d("Link", txtLink); 


      //Get Thumbnail 
      JSONObject medialist = movie.getJSONObject("media$group"); 
      JSONArray thumblist = medialist.getJSONArray("media$thumbnail"); 
      JSONObject thumb = thumblist.getJSONObject(2); 
      String txtThumb = thumb.getString("url"); 
      Log.d("Thumb", txtThumb.toString()); 

      //ImageLoader 

      String name = String.valueOf(i); 
      String test = loadImageFromWebOperations(txtThumb, "StepForward/Cache"+name); 


      //String Array daraus machen und in Hashmap füllen 
      HashMap<String, Object> map = new HashMap<String, Object>(); 
      map.put("Thumb", test); 
      map.put("Title", txtTitle); 
      map.put("Content", txtContent); 
      map.put("Link", txtLink); 
      mylist.add(map); 

     } 
     //ListView füllen 
     ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.lit, 
       new String[] { "Thumb","Title","Content","Link"}, 
       new int[] { R.id.img_video,R.id.txt_title,R.id.txt_subtitle});  
     setListAdapter(adapter); 


     //OnClickLister um Youtube-Video zu öffnen 
     final ListView lv = getListView(); 
      lv.setOnItemClickListener(new OnItemClickListener(){ 
       public void onItemClick(AdapterView<?> parent, View v, int position, long id) { 

        //Video-Link auslesen 
        Map<String, Object> map = mylist.get(position); 
        String link = (String) map.get("Link"); 
        Log.d("Link", link); 

        //Link übergeben, Activity starter 
        final Intent Showvideo = new Intent(ChannelActivity.this, ShowVideo.class); 
        Showvideo.putExtra("VideoLink", link); 
        startActivity(Showvideo); 


       } 
      }); 


    }catch (Exception e) { 
     Log.e("log_tag", "Error converting result " + e.toString()); 
     } 
    } 


    //Path-Loader 
    public static String loadImageFromWebOperations(String url, String path) { 
     try { 
      InputStream is = (InputStream) new URL(url).getContent(); 

      System.out.println(path); 
      File f = new File(Environment.getExternalStorageDirectory(), path); 

      f.createNewFile(); 
      FileOutputStream fos = new FileOutputStream(f); 
      try { 

       byte[] b = new byte[100]; 
       int l = 0; 
       while ((l = is.read(b)) != -1) 
        fos.write(b, 0, l); 

      } catch (Exception e) { 

      } 

      return f.getAbsolutePath(); 
     } catch (Exception e) { 
      System.out.println("Exc=" + e); 
      return null; 

     } 
    } 

} 
+0

, 그 이미지가 allready 종료하기 때문에, 그 ID가들의 OnDestroy에 chached 파일을 삭제하는 등 때문이다. – safari

+0

일부 이상한 ... – user370305

답변

2

액세스 파일은이 디렉토리의 모든 내용은 삭제됩니다.

API 레벨 8 이상 사용 외부 캐시 디렉토리에

:

+0

그래서 onDestroy가 정확히 캐시를 지우시겠습니까? 안드로이드가 응용 프로그램을 죽일 때 – safari

1

당신은 시간에서 onCreate에서 작업을 소모을 수행하지 않아야 위의 링크에서 API 레벨 7 이하를 사용에 대한 설명도 http://developer.android.com/guide/topics/data/data-storage.html#ExternalCache

있다 또는 onDestroy. 응용 프로그램이 응답하지 않는 오류에 대한 정보는 http://developer.android.com/guide/practices/design/responsiveness.html을 참조하십시오.

AsyncTask를 사용하면 파일을 삭제할 수 있습니다. 즉, onDestroy 메소드에서 파일 삭제 실행 만 시작하십시오. 또한 데이터를로드 할 때 AsyncTask를 사용해야합니다.

안드로이드에서 스레드와 프로세스에 대한 자세한 정보는 여기를 참조하십시오 : http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html는 필요하지

관련 문제