Shared data between Activities and threading
-
06-04-2021 - |
質問
I have an application called ListApp like this
public class ListApp extends Application {
public static RSmovies[] appRsMovie=new RSmovies[1];
public static ImageDownloader id =new ImageDownloader();
public static String cur=null;
public static String movieGetInfo="http://hive.tn/TMDb/test11.php?param=";
}
In my first activity i tried to make modification to the appRsMovie in a new thread, like this
new Thread(new Runnable() {
@Override
public void run() {
try {
InputStream source = retrieveStream("http://hive.tn/TMDb/test6.php");
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
ListApp.appRsMovie = gson.fromJson(reader, RSmovies[].class);
lv
.setAdapter(new LazyAdapter1(
ListControlActivity.this, z));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
Application crash and this is the exception that i got
12-26 17:21:55.643: W/dalvikvm(958): Exception Ljava/lang/RuntimeException; thrown during Lcom/test/list/ListApp;.<clinit>
正しい解決策はありません
他のヒント
Try this:
try moving the statement
lv.setAdapter(new LazyAdapter1(ListControlActivity.this, z));
from thread to Handler
create a Handler:
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
lv.setAdapter(new LazyAdapter1(ListControlActivity.this, z));
}
};
and replace the lv.setAdapter statement with handler's sendMessage
new Thread(new Runnable() {
@Override
public void run() {
try {
InputStream source = retrieveStream("http://hive.tn/TMDb/test6.php");
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
ListApp.appRsMovie = gson.fromJson(reader, RSmovies[].class);
handler.sendEmptyMessage(0);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
You can't update a listview (or any other view) from any Thread other than the UI thread. Use an AsyncTask instead of a plain thread, and make sure you update the listview in onPostExecute()
.
所属していません StackOverflow