带json的android ListView-如何异步任务?
我是android新手。我想要一个ListView并从json获取数据。我找到了很多教程,但它们没有异步任务。 我不知道,如何将AsyncTask添加到代码中带json的android ListView-如何异步任务?,android,json,listview,android-asynctask,Android,Json,Listview,Android Asynctask,我是android新手。我想要一个ListView并从json获取数据。我找到了很多教程,但它们没有异步任务。 我不知道,如何将AsyncTask添加到代码中 package de.test.ListView; import java.util.ArrayList; import java.util.HashMap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; im
package de.test.ListView;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MeinListViewActivity extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = jsonFunctions.getJSONfromURL("http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=demo");
try{
JSONArray earthquakes = json.getJSONArray("earthquakes");
for(int i=0;i<earthquakes.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Earthquake name:" + e.getString("eqid"));
map.put("magnitude", "Magnitude: " + e.getString("magnitude"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
new String[] { "name", "magnitude" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
@SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(MeinListViewActivity.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
}
你可以使用我的代码通过Gson获取一些信息
public void executeHttpGet() throws Exception {
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(
"http://cardsplatform.appspot.com/cardeckplatform_details"));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String json = sb.toString();
System.out.println(json);
Gson gson = new Gson();
Type collectionType = new TypeToken<MyClass>() {
}.getType();
MyClass myclass= gson.fromJson(json, collectionType);
GameEnvironment.get().getHandler().post(new Runnable() {
@Override
public void run() {
addElementsToTableLayout();
}
});
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void executeHttpGet()引发异常{
BufferedReader in=null;
试一试{
HttpClient=new DefaultHttpClient();
HttpGet请求=新建HttpGet();
setURI(新的URI(
"http://cardsplatform.appspot.com/cardeckplatform_details"));
HttpResponse response=client.execute(请求);
in=new BufferedReader(新的InputStreamReader(response.getEntity())
.getContent());
StringBuffer sb=新的StringBuffer(“”);
字符串行=”;
字符串NL=System.getProperty(“line.separator”);
而((line=in.readLine())!=null){
sb.追加(行+NL);
}
in.close();
字符串json=sb.toString();
System.out.println(json);
Gson Gson=新的Gson();
Type collectionType=new-TypeToken(){
}.getType();
MyClass MyClass=gson.fromJson(json,collectionType);
GameEnvironment.get().getHandler().post(新的Runnable()){
@凌驾
公开募捐{
addElementsToTableLayout();
}
});
}最后{
if(in!=null){
试一试{
in.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
}
现在,如果您希望使用异步任务,那么您应该做的就是将它放在
背景法
比如说
private class DownloadFile extends
AsyncTask<PluginDetails, Integer, MyBoolean> {
MyBoolean downloaded;
ProgressDialog mProgressDialog;
boolean canceled=false;
public DownloadFile(MyBoolean downloaded) {
this.downloaded=downloaded;
}
@Override
protected MyBoolean doInBackground(PluginDetails... pluginDetail) {
try {
URL url = new URL("http://cardsplatform.appspot.com"
);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100%
// progress bar
long fileLength = getSize();
// download the file
InputStream input = new BufferedInputStream(
connection.getInputStream());
FileOutputStream output = StaticFunctions
.getPluginOutputStream(pluginDetail[0].getFilename());
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1 && !canceled) {
total += count;
System.out.println((int) (total * 100 / fileLength));
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
if(!canceled)
downloaded.setFlag(true);
else{//case its was canceled
}
} catch (Exception e) {
cannotMakeConnection();
e.printStackTrace();
}
return null;
}
enter code here
私有类下载文件扩展
异步任务{
MyBoolean下载;
进程对话框;
布尔值=假;
公共下载文件(MyBoolean下载){
this.download=下载;
}
@凌驾
受保护的MyBoolean doInBackground(PluginDetails…PluginDetails){
试一试{
URL=新URL(“http://cardsplatform.appspot.com"
);
URLConnection=url.openConnection();
connection.connect();
//这将非常有用,以便您可以显示典型的0-100%
//进度条
long fileLength=getSize();
//下载该文件
InputStream输入=新的BufferedInputStream(
connection.getInputStream());
FileOutputStream输出=静态函数
.getPluginOutputStream(pluginDetail[0].getFilename());
字节数据[]=新字节[4096];
长总计=0;
整数计数;
而((计数=输入.读取(数据))!=-1&&!已取消){
总数+=计数;
System.out.println((int)(总计*100/文件长度));
//发布进度。。。。
出版进度((整数)(总计*100/文件长度));
输出.写入(数据,0,计数);
}
output.flush();
output.close();
input.close();
如果(!取消)
下载的.setFlag(true);
否则{//其案例被取消
}
}捕获(例外e){
cannotMakeConnection();
e、 printStackTrace();
}
返回null;
}
在这里输入代码
您可以使用我的代码通过Gson获取一些信息
public void executeHttpGet() throws Exception {
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(
"http://cardsplatform.appspot.com/cardeckplatform_details"));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String json = sb.toString();
System.out.println(json);
Gson gson = new Gson();
Type collectionType = new TypeToken<MyClass>() {
}.getType();
MyClass myclass= gson.fromJson(json, collectionType);
GameEnvironment.get().getHandler().post(new Runnable() {
@Override
public void run() {
addElementsToTableLayout();
}
});
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void executeHttpGet()引发异常{
BufferedReader in=null;
试一试{
HttpClient=new DefaultHttpClient();
HttpGet请求=新建HttpGet();
setURI(新的URI(
"http://cardsplatform.appspot.com/cardeckplatform_details"));
HttpResponse response=client.execute(请求);
in=new BufferedReader(新的InputStreamReader(response.getEntity())
.getContent());
StringBuffer sb=新的StringBuffer(“”);
字符串行=”;
字符串NL=System.getProperty(“line.separator”);
而((line=in.readLine())!=null){
sb.追加(行+NL);
}
in.close();
字符串json=sb.toString();
System.out.println(json);
Gson Gson=新的Gson();
Type collectionType=new-TypeToken(){
}.getType();
MyClass MyClass=gson.fromJson(json,collectionType);
GameEnvironment.get().getHandler().post(新的Runnable()){
@凌驾
公开募捐{
addElementsToTableLayout();
}
});
}最后{
if(in!=null){
试一试{
in.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
}
现在,如果您希望使用异步任务,那么您应该做的就是将它放在
背景法
比如说
private class DownloadFile extends
AsyncTask<PluginDetails, Integer, MyBoolean> {
MyBoolean downloaded;
ProgressDialog mProgressDialog;
boolean canceled=false;
public DownloadFile(MyBoolean downloaded) {
this.downloaded=downloaded;
}
@Override
protected MyBoolean doInBackground(PluginDetails... pluginDetail) {
try {
URL url = new URL("http://cardsplatform.appspot.com"
);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100%
// progress bar
long fileLength = getSize();
// download the file
InputStream input = new BufferedInputStream(
connection.getInputStream());
FileOutputStream output = StaticFunctions
.getPluginOutputStream(pluginDetail[0].getFilename());
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1 && !canceled) {
total += count;
System.out.println((int) (total * 100 / fileLength));
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
if(!canceled)
downloaded.setFlag(true);
else{//case its was canceled
}
} catch (Exception e) {
cannotMakeConnection();
e.printStackTrace();
}
return null;
}
enter code here
私有类下载文件扩展
异步任务{
MyBoolean下载;
进程对话框;
布尔值=假;
公共下载文件(MyBoolean下载){
this.download=下载;
}
@凌驾
受保护的MyBoolean doInBackground(PluginDetails…PluginDetails){
试一试{
URL=新URL(“http://cardsplatform.appspot.com"
);
URLConnection=url.openConnection();
connection.connect();
//这将非常有用,以便您可以显示典型的0-100%
//进度条
long fileLength=getSize();
//下载该文件
InputStream输入=新的BufferedInputStream(
connection.getInputStream());
FileOutputStream输出=静态函数
.getPluginOutputStream(pluginDetail[0].getFilename());
字节数据[]