Android ListView在活动更改时持续重新创建。
我有这个Android ListView在活动更改时持续重新创建。,android,listview,arraylist,android-activity,Android,Listview,Arraylist,Android Activity,我有这个列表视图;但是当我离开或返回到活动时,列表视图会不断地重新创建自己。这是什么原因造成的,我应该在下面的代码中寻找什么 public class Homepage extends ActionBarActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R
列表视图
;但是当我离开或返回到活动时,列表视图
会不断地重新创建自己。这是什么原因造成的,我应该在下面的代码中寻找什么
public class Homepage extends ActionBarActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
ImageView i = (ImageView) findViewById(R.id.imageView1);
Ion.with(i).placeholder(R.drawable.ic_launcher)
.error(R.drawable.ic_launcher)
.load("http://192.168.1.6/webservice/images/image1.jpg");
// Creating a new non-ui thread task to download json data
DownloadTask downloadTask = new DownloadTask();
// Starting the download process
downloadTask.execute(strUrl);
// Getting a reference to ListView of activity_main
mListView = (ListView) findViewById(R.id.myList);
startService(new Intent(this, NotificationService.class));
}
....
String strUrl = "http://192.168.1.6/webservice/events.php";
ListView mListView;
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
}
return data;
}
/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String> {
String data = null;
@Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result) {
// The parsing of the xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
// Start parsing xml data
listViewLoaderTask.execute(result);
}
}
/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends
AsyncTask<String, Void, SimpleAdapter> {
JSONObject jObject;
// Doing the parsing of xml data in a non-ui thread
@Override
protected SimpleAdapter doInBackground(String... strJson) {
try {
jObject = new JSONObject(strJson[0]);
JSONParser newJsonParser = new JSONParser();
newJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("JSON Exception1", e.toString());
}
// Instantiating json parser class
JSONParser newJsonParser = new JSONParser();
// A list object to store the parsed events list
List<HashMap<String, Object>> posts = null;
try {
// Getting the parsed data as a List construct
posts = newJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
// Keys used in Hashmap
String[] from = { "mytitle", "event_img", "mymessage", "mysponser",
"myevent_location", "myevent_whoinvited",
"myevent_dresscode", "myevent_time", "myevent_endtime" };
// Ids of views in listview_layout
int[] to = { R.id.title, R.id.event_pic, R.id.subTitle_single,
R.id.sponser, R.id.l, R.id.who, R.id.d, R.id.t, R.id.e };
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), posts,
R.layout.single_line, from, to);
return adapter;
}
....
/** Invoked by the Android on "doInBackground" is executed */
@Override
protected void onPostExecute(final SimpleAdapter adapter) {
// Setting adapter for the listview
mListView.setAdapter(adapter);
// //Attempting Onclick method \\\\
mListView.setOnItemClickListener(new OnItemClickListener() {
....
});
// //\\\\looks like this cycles through the image to the adapter
// using the ImageLoaderTask
for (int i = 0; i < adapter.getCount(); i++) {
HashMap<String, Object> hm = (HashMap<String, Object>) adapter
.getItem(i);
String imgUrl = (String) hm.get("event_img_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("event_img_path", imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in
// the listview
imageLoaderTask.execute(hm);
}
}
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends
AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>> {
@Override
protected HashMap<String, Object> doInBackground(
HashMap<String, Object>... hm) {
InputStream iStream = null;
String imgUrl = (String) hm[0].get("event_img_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"
+ position + ".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG, 100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
// Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position
// in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("event_img", tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position", position);
// Returning the HashMap object containing the image path and
// position
return hmBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("event_img");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter) mListView.getAdapter();
// Getting the hashmap object at the specified position of the
// listview
// @SuppressWarnings("unchecked")
HashMap<String, Object> hm = (HashMap<String, Object>) adapter
.getItem(position);
// Overwriting the existing path in the adapter
hm.put("event_img", path);
// Noticing listview about the dataset changes
adapter.notifyDataSetChanged();
}
}
}
公共类主页扩展了ActionBarActivity{
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
ImageView i=(ImageView)findViewById(R.id.imageView1);
带(i)占位符的离子(R.drawable.ic_启动器)
.错误(R.drawable.ic_启动器)
.加载(“http://192.168.1.6/webservice/images/image1.jpg");
//创建新的非ui线程任务以下载json数据
DownloadTask DownloadTask=新的DownloadTask();
//开始下载过程
下载任务。执行(strUrl);
//获取对活动“”的ListView的引用
mListView=(ListView)findViewById(R.id.myList);
startService(新意图(这个,NotificationService.class));
}
....
字符串strUrl=”http://192.168.1.6/webservice/events.php";
列表视图;
/**从url下载json数据的方法*/
私有字符串下载URL(字符串strUrl)引发IOException{
字符串数据=”;
InputStream iStream=null;
试一试{
URL=新URL(strUrl);
//创建http连接以与url通信
HttpURLConnection urlConnection=(HttpURLConnection)url
.openConnection();
//连接到url
urlConnection.connect();
//从url读取数据
iStream=urlConnection.getInputStream();
BufferedReader br=新的BufferedReader(新的InputStreamReader(
峡流);
StringBuffer sb=新的StringBuffer();
字符串行=”;
而((line=br.readLine())!=null){
某人附加(行);
}
data=sb.toString();
br.close();
}捕获(例外e){
Log.d(“下载url时出现异常”,例如toString());
}最后{
iStream.close();
}
返回数据;
}
/**AsyncTask下载json数据*/
私有类DownloadTask扩展了AsyncTask{
字符串数据=null;
@凌驾
受保护的字符串doInBackground(字符串…url){
试一试{
数据=下载url(url[0]);
}捕获(例外e){
Log.d(“后台任务”,例如toString());
}
返回数据;
}
@凌驾
受保护的void onPostExecute(字符串结果){
//xml数据的解析在非ui线程中完成
ListViewLoaderTask ListViewLoaderTask=新建ListViewLoaderTask();
//开始解析xml数据
listViewLoaderTask.execute(结果);
}
}
/**AsyncTask解析json数据并加载ListView*/
私有类ListViewLoaderTask扩展
异步任务{
JSONObject jObject;
//在非ui线程中解析xml数据
@凌驾
受保护的SimpleAdapter doInBackground(字符串…strJson){
试一试{
jObject=新的JSONObject(strJson[0]);
JSONParser newJsonParser=新JSONParser();
parse(jObject);
}捕获(例外e){
d(“JSON例外1”,例如toString());
}
//实例化json解析器类
JSONParser newJsonParser=新JSONParser();
//用于存储已解析事件列表的列表对象
列表帖子=null;
试一试{
//将解析后的数据作为列表构造获取
posts=newJsonParser.parse(jObject);
}捕获(例外e){
Log.d(“异常”,例如toString());
}
//Hashmap中使用的键
字符串[]from={“mytitle”、“event_img”、“mymessage”、“mysponser”,
“myevent_位置”、“myevent_位置”,
“myevent_dresscode”、“myevent_time”、“myevent_endtime”};
//listview\u布局中的视图ID
int[]to={R.id.title,R.id.event_pic,R.id.subTitle_single,
R.id.sponser,R.id.l,R.id.who,R.id.d,R.id.t,R.id.e};
//实例化适配器以存储每个项
//R.layout.listview\u布局定义每个项目的布局
SimpleAdapter=新SimpleAdapter(getBaseContext(),posts,
R.布局。单线,从,到);
返回适配器;
}
....
/**由Android在“doInBackground”上调用*/
@凌驾
受保护的void onPostExecute(最终SimpleAdapter适配器){
//设置listview的适配器
mListView.setAdapter(适配器);
////正在尝试Onclick方法\\\\
setOnItemClickListener(新的OnItemClickListener(){
....
});
////\\\看起来像是通过映像循环到适配器
//使用ImageLoaderTask
对于(inti=0;i public class EagerSingleton {
private ArrayList<MyClass> list = new ArrayList<MyClass>();;
private static volatile EagerSingleton instance = null;
// private constructor
private EagerSingleton() {
}
public static EagerSingleton getInstance() {
if (instance == null) {
synchronized (EagerSingleton.class) {
// Double check
if (instance == null) {
instance = new EagerSingleton();
}
}
}
return instance;
}
}