使用自定义适配器的ListViewActivity不起作用

时间:2013-12-27 10:23:21

标签: java android eclipse listview baseadapter

亲爱的Stackoverflow Comunitiy,

我想让一个ListView被BackgroundTask填充。 这是我的实际代码

HomeActivity:

package com.example.instaemgnew;

import java.util.ArrayList;

import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;

import com.example.instaemgnew.classes.Beitrag;
import com.example.instaemgnew.classes.beitragLoader;
import com.example.instaemgnew.classes.listViewHomeActivitiyAdapter;

public class HomeActivity extends ListActivity {
    listViewHomeActivitiyAdapter adapter;
     ArrayList<Beitrag> beitraege = new ArrayList<Beitrag>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);


        adapter = new listViewHomeActivitiyAdapter(this, beitraege);
         setListAdapter(adapter);
         Log.e("TestPoint 1", "Adapter Set");

        new beitragLoader(this).execute();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_home, menu);
        return true;
    }

    public void addToListView(Beitrag toAddBeitrag){
        beitraege.add(toAddBeitrag);
        adapter.notifyDataSetChanged();
    }




}

BackgroundTask:

package com.example.instaemgnew.classes;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.instaemgnew.HomeActivity;

import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.ArrayAdapter;

public class beitragLoader extends AsyncTask<String, String, String>{

    //Array List für die Beiträge
    ArrayList<Beitrag> beitraege;

    //User Daten
    /*mail = userManager.getMail();
    grade = String.valueOf(userManager.getGrade());
    school = userManager.getSchool();*/
    String mail = "simon-frey@gmx.de";
    String grade = String.valueOf(334);
    String school = "EMG";

    //JSONParser
    JSONParser jsonParser = new JSONParser();

    //ArrayList mit Beitrag Objekten
    ArrayList<Beitrag> beitraegeList;

    // Onlinedaten
    private static final String SERVER_URL = "http://yooui.de/InstaEMGTest/";
    private static final String PASSWORD = "8615daf406f7e2b313494f0240";

    //Context
    private final HomeActivity homeActivity;

    //Konstruktor
    public beitragLoader(HomeActivity homeActivity){
        this.homeActivity = homeActivity;
         Log.e("TestPoint 2", "Created beitragLoader");

    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //TODO: Test for InternetConnection
         Log.e("TestPoint 3", "PreExectute");

    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        beitraegeList = new ArrayList<Beitrag>();
        String SQLUrl = SERVER_URL + "testBeiträgeAbrufen.php";
        String token = getMD5Hash("password" + "data");

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("token", token));
        //TODO: params.add(new BasicNameValuePair("page", skipBeitraege))    
        params.add(new BasicNameValuePair("grade", grade));
        params.add(new BasicNameValuePair("school", school));

        JSONObject json = jsonParser.makeHttpRequest(SQLUrl, "GET", params);


        if (json == null) {
            // Server offline

        }

         Log.e("TestPoint 3,5", "FetchedJSON");


        try {
            JSONArray beitraege = json.getJSONArray("beitraege");


             // looping through All Products
            for (int i = 0; i < beitraege.length(); i++) {
                Beitrag tempBeitrag = null;

                 Log.e("TestPoint 3,6", "StartLoop");

                JSONObject c = beitraege.getJSONObject(i);

                //HDImagesURLList ArrayList
                ArrayList<String> HDImagesURLList = new ArrayList<String>();

                // Storing each json item in variable
                String id = c.getString("ID");
                String url = c.getString("url");
                String titel = c.getString("titel");
                String tags = c.getString("tags");
                String onlineDate = c.getString("onlineDate");

                 Log.e("TestPoint 3,7", "Stored JSON Items");


                //Fetching previewImage
                try {
                     Log.e("TestPoint 3,8", "TryImageDownload");

                InputStream in = new java.net.URL(url).openStream();
                String fileName = "InstaEMG" + String.valueOf(System.currentTimeMillis())+".jpg";

                 Log.e("imageUri", url);
                 Log.e("fileName", fileName);


                FileOutputStream fileOutput = new FileOutputStream(new File(Environment.getExternalStorageDirectory(),fileName));

                byte[] buffer = new byte[1024];
                int bufferLength = 0;
                while ((bufferLength = in.read(buffer)) > 0 ) {
                      fileOutput.write(buffer, 0, bufferLength);
                      Log.e("File Output", String.valueOf(bufferLength));
                }


               //Fill HDImagesURLList
               //TODO


                // creating newBeitrag
               tempBeitrag = new Beitrag(Integer.parseInt(id), titel, onlineDate,  fileName, HDImagesURLList);




                // adding Beitrag to ArrayList
                beitraegeList.add(tempBeitrag);

             Log.e("TestPoint 4", "NewBeitragSet");

                } catch (MalformedURLException e) {

                     Log.e("Exceptrion", "URL Exception");

                } catch (IOException e) {
                     Log.e("Exceptrion", "IO Exception");

                }
                homeActivity.addToListView(tempBeitrag);

            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }        return null;       
    }

    /**
     * After completing background Safe to MainActivity
     * **/
    protected void onPostExecute() {
         Log.e("TestPoint 5", "PostExecutre");

        // homeActivity.updateListView(beitraegeList);

    }

    /**
     * Methode zum Errechnen eines MD5Hashs
     * 
     * @param string
     *            String welcher kodiert werden soll
     * @return MD5 Hash des Strings, bei Fehler der ursprüngliche String.
     */
    private String getMD5Hash(String string) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(string.getBytes());
            byte[] result = md5.digest();

            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < result.length; i++) {
                if ((0xff & result[i]) < 0x10) {
                    hexString.append("0" + Integer.toHexString((0xFF & result[i])));
                } else {
                    hexString.append(Integer.toHexString(0xFF & result[i]));
                }
            }
            string = hexString.toString();
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        }

        return string;
    };

}

和BaseAdapter:

package com.example.instaemgnew.classes;

import java.util.ArrayList;

import com.example.instaemgnew.R;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

      public class listViewHomeActivitiyAdapter extends BaseAdapter {
          private final Context context;
          private ArrayList<Beitrag> beitraege;
          private final LayoutInflater layoutInflater;

        public listViewHomeActivitiyAdapter(Context context,  ArrayList<Beitrag> beitraege) {

          super();
          this.beitraege = beitraege;
          this.context = context;
          this.layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        }


        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
        //Allgemeien Layout Vorgaben  
        LayoutInflater inflater = (LayoutInflater) context
              .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
          View rowView = inflater.inflate(R.layout.single_beitrag_row_layout, parent, false);

          if (convertView == null) {
              convertView = layoutInflater.inflate(R.layout.single_beitrag_row_layout, null);
          }

          //getViews
          TextView titelView = (TextView) rowView.findViewById(R.id.beitragTitel);
          ImageView beitragImageView = (ImageView) rowView.findViewById(R.id.beitragImg);
          /*
           * TODO: Tags anzeigen und suchen lassen (Wunschfunktion)
           * TextView tagsView = (TextView) rowView.findViewById(R.id.beitragTags);
           */



          //setTitel From Object
          titelView.setText(beitraege.get(position).getTitel());

          //setPreviewImage From Object
          beitragImageView.setImageBitmap(beitraege.get(position).getPreviewImage());
          //setOnClickListener on PreviewImage for PopOutGallery
          beitragImageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO: PopOut Gallery
            }
          });   

          return rowView;
        }


        @Override
        public int getCount() {
            return beitraege.size();
        }


        @Override
        public Object getItem(int position) {
            return beitraege.get(position);
        }


        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        } 




      }

在我看来,Bug必须在BaseAdapter中,但我不知道它可能在哪里。

真诚而感恩,

西蒙

2 个答案:

答案 0 :(得分:0)

要在doInBackground中填充listView,您需要使用Handler或runOnUiThread,因为这不是UI线程。

homeActivity.runOnUiThread(new Runnable() 
{ 
  public void run()
  { 
     homeActivity.addToListView(tempBeitrag); 
}});

答案 1 :(得分:0)

adapter = new listViewHomeActivitiyAdapter(this, beitraege);

beitraege未填充任何数据。

编辑:

而不是从doInbackground调用此内容。使用Interface作为对活动的回调,然后填充listview。

 public void addToListView(Beitrag toAddBeitrag){
        beitraege.add(toAddBeitrag);
        adapter.notifyDataSetChanged();
    }

How do I return a boolean from AsyncTask?

在你的情况下,而不是boolen值它的arraylist。

然后使用以下内容并将适配器设置为listview

adapter = new listViewHomeActivitiyAdapter(this, beitraege);