Android上的ListView - 使用ArrayList填充

时间:2013-04-22 18:42:40

标签: android sql arraylist android-listview android-asynctask

我试图通过使用SQL语句和jTDS驱动程序,通过AsyncTask在Android上的ListView中显示行。

Articles.java:

package com.example.projectmanager;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;
import android.util.Log;


public class Articles extends AsyncTask <List<Articles>, Void, List> {

    int article_id;
    String title; 
    String body ;
    Date date;
    String username;
    List<Articles> posts = new ArrayList<Articles>();


    protected List<Articles> doInBackground(List... params) {

         Connection conn = null;
            try {   



            String driver = "net.sourceforge.jtds.jdbc.Driver";
            Class.forName(driver).newInstance();

            String connString = "jdbc:jtds:sqlserver://10.0.2.2/master_db;";
            String sqlusername = "admin";
            String sqlpassword = "root";

            conn = DriverManager.getConnection(connString, sqlusername, sqlpassword);
            Log.w("Connection","open");

            String articleQuery = "SELECT TOP 5 E.article_id,E.article_title,E.article_description,E.article_date,u.username FROM articles AS E INNER JOIN user_articles as A ON A.article_id = E.article_id INNER JOIN users as u ON A.user_id = u.user_id WHERE E.article_status = 1;"; 

            PreparedStatement stmt = conn.prepareStatement(articleQuery);

            ResultSet rs;

            rs = stmt.executeQuery();



            while (rs.next()) {

                Articles article = new Articles();
                article.article_id = rs.getInt("article_id");
                article.username = rs.getString("username");
                article.date = rs.getDate("article_date");
                article.title = rs.getString("article_title");
                article.body = rs.getString("article_description");
                posts.add(article);             


            }
            conn.close();

            } catch (Exception e)
            {
            Log.w(e.getMessage(), e);
            }


        return posts;



    }
    protected void onPostExecute(List posts) {
        // Result is here now, may be 6 different List type.
        this.posts = posts; 
    }




}

HomeActivity.java:

package com.example.projectmanager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class HomeActivity extends Activity {

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


        Articles a = new Articles();

        ListView lv = (ListView) findViewById(R.id.lvPosts);
        List postsList = null;

        try {
            postsList = new Articles().execute().get();
        } catch (InterruptedException e) {

            e.printStackTrace();

        } catch (ExecutionException e) {

            e.printStackTrace();
        }


        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, postsList);
        lv.setAdapter(arrayAdapter); 


    }


      }

每当我尝试运行代码时,我都会得到这个输出:

enter image description here

LogCat:http://pastebin.com/cjm1BNeZ

有谁能告诉我发生了什么事?

更新:填充广告

String articleQuery = "SELECT TOP 5 E.article_id,E.article_title,E.article_description,E.article_date,u.username FROM articles AS E INNER JOIN user_articles as A ON A.article_id = E.article_id INNER JOIN users as u ON A.user_id = u.user_id WHERE E.article_status = 1;"; 

            PreparedStatement stmt = conn.prepareStatement(articleQuery);

            ResultSet rs;

            rs = stmt.executeQuery();



            while (rs.next()) {

                Articles article = new Articles();
                article.article_id = rs.getInt("article_id");
                article.username = rs.getString("username");
                article.date = rs.getDate("article_date");
                article.title = rs.getString("article_title");
                article.body = rs.getString("article_description");
                posts.add(article);             


            }

4 个答案:

答案 0 :(得分:2)

将此添加到您的文章类:

        @Override
        public String toString() {
            return "id: "+article_id + "\n"
                   +"title : " + title 
                   +"body: "+body ;
        }

您希望用户看到的任何其他信息。
这是因为Android Framework将调用YOUROBJECT.toString();自动渲染列表中的对象。这就是你需要覆盖这个方法的原因。

更新:

Articles article = new Articles();
                article.article_id = rs.getInt("article_id");
                article.username = rs.getString("username");
                article.date = rs.getDate("article_date");
                article.title = rs.getString("article_title");
                article.body = rs.getString("article_description");

这是您弹出文章对象的代码。如果要在项列表中显示此对象的其他属性。只需在toString()方法中添加该字段即可。 例如:

  @Override
        public String toString() {
            return "id: "+article_id + "\n"
                   +"title : " + title 
                   +"body: "+body+" date"+date +"username: "+username ;
        }

答案 1 :(得分:1)

我认为你使用ArrayAdapter是错误的。 你输入的类型(String)不是你应该放的类型。

您需要创建新的自定义数组adaper,接受类型文章和 再来一次。

类似的东西:

    public class ListAdapter extends ArrayAdapter<Articles> {

public ListAdapter(Context context, int textViewResourceId) {
    super(context, textViewResourceId);
    // TODO Auto-generated constructor stub
}

private List<Articles> items;

public ListAdapter(Context context, int resource, List<Articles> items) {

    super(context, resource, items);

    this.items = items;

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View v = convertView;

    if (v == null) {

        LayoutInflater vi;
        vi = LayoutInflater.from(getContext());
        v = vi.inflate(R.layout.itemlistrow, null);

    }

    Item p = items.get(position);

    if (p != null) {

        TextView tt = (TextView) v.findViewById(R.id.id);
        TextView tt1 = (TextView) v.findViewById(R.id.categoryId);
        TextView tt3 = (TextView) v.findViewById(R.id.description);

        if (tt != null) {
            tt.setText(p.userName());
        }
        if (tt1 != null) {

            tt1.setText(p.getDate);
        }
        //and so on...
    }

    return v;

}

您应该将视图与文章对象相关联。查看属性。 这就是适配器所代表的含义。和字符串适配器仅用于字符串列表。

之后你应该这样做:

ListAdapter<Articles> arrayAdapter = new ListAdapter<Articles>(this,android.R.layout.simple_list_item_1, postsList);
    lv.setAdapter(arrayAdapter); 
希望它有所帮助。

答案 2 :(得分:1)

似乎Articles.execute().get()方法返回ListArticles个对象。 ArrayListAdapter调用这些对象的toString()方法。如果您不提供自己的toString()方法,则只需从Object继承默认值,即打印出对象的类名和哈希值。这就是输出显示的原因。

解决此问题的一种方法是覆盖toString()类中的Articles方法,以返回您希望在String中显示的数据的ListView表示

答案 3 :(得分:0)

Follow this instructions获取自定义适配器的示例。