gpt4 book ai didi

java - 使用异步任务 (Json) 更新 ListView

转载 作者:行者123 更新时间:2023-12-01 14:44:52 26 4
gpt4 key购买 nike

我在尝试使用异步任务更新 ListView 时遇到问题。asynctask 似乎没有连接到数据库...

我一直在寻找,但找不到解决方案......

感谢您的帮助!

这是源代码:

@SuppressLint("NewApi")
public class Resultats extends Activity {

private PullToRefreshListView lv1;

private ImageView refresh = null; // to refresh

private ArrayList<Match_ItemDetails> image_details;
private Resultats_ListBaseAdapter adapter;
private ArrayList<Match_ItemDetails> results;

/** Called when the activity is first created. */

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

results = new ArrayList<Match_ItemDetails>();

// first construction

image_details = GetSearchResults();
adapter = new Resultats_ListBaseAdapter(this, image_details);

// Définition de la liste
lv1 = (PullToRefreshListView) findViewById(R.id.liste);

// to refresh

refresh = (ImageView)findViewById(R.id.resultats_refresh);
refresh.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
refresh(GetSearchResults());
}
});
lv1.setAdapter(new Resultats_ListBaseAdapter(this, image_details));

//Listener that will be invoked when it has been tap or it has been pull and released
lv1.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh() {

new GetDataTask().execute();

}
});
}

// refresh
private void refresh(ArrayList<Match_ItemDetails> arrayList){
lv1.setAdapter(new Resultats_ListBaseAdapter(this, arrayList));

}

// asynctask which isn t working


private class GetDataTask extends AsyncTask<Void, Void, ArrayList<Match_ItemDetails>> {
ArrayList<Match_ItemDetails> tableau;

@Override
protected ArrayList<Match_ItemDetails> doInBackground(Void... params) {
Log.i(MainActivity.class.getName(),"doinBackground");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
tableau = GetSearchResults();
System.out.println("pouet");
return tableau;
}

@Override
protected void onPostExecute(ArrayList<Match_ItemDetails> result) {
refresh(result);
lv1.onRefreshComplete();

}
}


// construction of the arraylist

private ArrayList<Match_ItemDetails> GetSearchResults(){

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

String lireResultats = lireResultats();

try {
JSONArray jsonArray = new JSONArray(lireResultats);
Log.i(MainActivity.class.getName(),
"Number of entries " + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Match_ItemDetails item_details = new Match_ItemDetails();
item_details.setNameTeam1(jsonObject.getString("equipe1"));
item_details.setNameTeam2(jsonObject.getString("equipe2"));
item_details.setDate(jsonObject.getString("date"));
item_details.setScoreTeam1(jsonObject.getInt("scoreEquipe1"));
item_details.setScoreTeam2(jsonObject.getInt("scoreEquipe2"));
item_details.setEstFini(jsonObject.getInt("estFini"));
item_details.setDrapeauEquipe1(jsonObject.getString("drapeauEquipe1"));
item_details.setDrapeauEquipe2(jsonObject.getString("drapeauEquipe2"));
if (!existe(item_details.getDrapeauEquipe1())){
enregistrer(item_details.getDrapeauEquipe2());
}
if (!existe(item_details.getDrapeauEquipe2())){
enregistrer(item_details.getDrapeauEquipe2());
}
item_details.setDrapeau1(getImage(item_details.getDrapeauEquipe1()));
item_details.setDrapeau2(getImage(item_details.getDrapeauEquipe2()));

results.add(item_details);
}
} catch (Exception e) {
e.printStackTrace();
}

return results;
}


// get data

public String lireResultats() {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("****/resultats.php");
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e(MainActivity.class.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}

// test if the file exists

public boolean existe(String nom){
File tmp = new File(this.getFilesDir() + File.separator + nom);
return tmp.exists();
}

// return a pict
public Bitmap getImage(String nom){
Bitmap drawable = BitmapFactory.decodeFile(this.getFilesDir() + File.separator + nom);
return drawable;
}

// save a pict
public void enregistrer(String nom){
try
{
URL u = new URL("http://www.centrale7.com/paris/android/drapeaux48/" + nom + ".png");
URLConnection conn = u.openConnection();
conn.connect();
InputStream is = new BufferedInputStream(conn.getInputStream());
Bitmap bm1 = BitmapFactory.decodeStream(is);
// Bitmap bm1 = BitmapFactory.decodeResource(getResources(), R.drawable.test);
FileOutputStream fout = openFileOutput(nom, Context.MODE_PRIVATE);
bm1.compress(Bitmap.CompressFormat.PNG, 100, fout);
}
catch(Exception e){
System.out.println("ca marche pas");
System.out.println(e);
e.printStackTrace();
}
}
}

最佳答案

首先,由于您使用的是 AsyncTask,因此无需调用

strictMode.ThreadPolicy

你不应该调用它。只需执行 JSON 解析

tableau = GetSearchResults();
return tableau;

然后在为适配器设置新数据源后,在刷新方法中需要调用

adapter.notifyDataSetChanged();

适配器不知道您何时更改数据源,并且不会自行刷新。您需要通过调用上面提到的方法来确保它。

关于java - 使用异步任务 (Json) 更新 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15535630/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com