清除“缓存”销毁时
我尝试做的事情
我正在为我的频道构建一个应用程序。我通过 JSON 从 google 获取数据,然后通过 SimpleAdapter 将其填充到我的 ListView 中。
我可以在我的 SimpleAdapter 中显示图片,我将它们保存到我的 SDCard 上。现在的问题是,当应用程序被杀死时,我会收到强制关闭错误,因为图片已经在那里了。
问题
如何在 onDestroy() 上删除 SDCard 上的“缓存”图像?
您可以在此处找到应用程序的代码。提前感谢您的帮助!
代码
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;
}
}
}
What I try to do
I'm building a application for my Channel. I get the data over the JSON from google and fill that into my ListView over the SimpleAdapter.
That I can show the pictures in my SimpleAdapter, i save them onto my SDCard. The Problem is now, when the app gets killed I get a forceclose error because the pictures are allready there.
Question
How can I delte the "Cached" images on my SDCard on onDestroy()?
Down here you find the Code of the app. Thank you for your help in advance!
Code
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;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
访问外部存储上的文件
如果用户卸载您的应用程序,该目录及其所有内容都将被删除。
在 API 级别 8 或更高级别上,使用外部缓存目录: http:// /developer.android.com/guide/topics/data/data-storage.html#ExternalCache
上面的链接中还有使用 API 级别 7 及更低级别的说明
Accessing files on external storage
If the user uninstalls your application, this directory and all its contents will be deleted.
on API level 8 or greater use the external cache directory: http://developer.android.com/guide/topics/data/data-storage.html#ExternalCache
There is also an explanation for using API level 7 and lower in the above link
您不应该在 onCreate 或 onDestroy 中执行耗时的操作。请参阅http://developer.android.com/guide/practices/design/responsiveness。 html 有关应用程序未响应错误的信息。
使用AsyncTask删除文件,即仅在onDestroy方法中开始执行文件的删除。加载数据时还应该使用 AsyncTask。
有关 Android 中线程和进程的更多信息,请参阅此处:http:// /developer.android.com/guide/topics/fundamentals/processes-and-threads.html
You should not perform time consuming operations in onCreate or onDestroy. See http://developer.android.com/guide/practices/design/responsiveness.html for information on the App is not responding error.
Use an AsyncTask to delete the files, i.e. only start the execution of the deletion of the files in your onDestroy method. Also you should use an AsyncTask when loading the data.
See here for more information on Threads and processes in Android: http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html