0

我在尝试使用异步任务更新列表视图时遇到问题。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();
  }
}
} 
4

1 回答 1

1

起初,由于您使用的是 AsyncTask ,因此无需调用

strictMode.ThreadPolicy

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

tableau = GetSearchResults();
return tableau;

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

adapter.notifyDataSetChanged();

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

于 2013-03-21T07:37:47.013 回答