0

这是我的 SQLBlog 类,getDataFunc 是我从数据库获取结果的函数

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class SQLBlog {

    public static final String KEY_ROWID = "_id";
    public static final String KEY_NAME = "persons_name"; 
    public static final String KEY_BLOG = "persons_blog";

    private static final String DATABASE_NAME = "blog";
    private static final String DATABASE_TABLE = "admin_blog";
    private static final int DATABASE_VERSION = 1;

    private DBhelper ourhelper;
    private final Context ourcontext;
    private SQLiteDatabase ourdatabase;

    private static class DBhelper extends SQLiteOpenHelper{

        public DBhelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL("Create table "+ DATABASE_TABLE +" (" + KEY_ROWID + " Integer primary key autoincrement, "+
                        KEY_NAME +" text not null, "+
                        KEY_BLOG +" text not null);");

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            db.execSQL("drop table if exists "+ DATABASE_TABLE);
            onCreate(db);
        }

        }
    public SQLBlog(Context c){
        ourcontext=c;
    }

    public SQLBlog open() throws SQLException{
        ourhelper= new DBhelper(ourcontext);
        ourdatabase= ourhelper.getWritableDatabase();
        return this;

    }
    public void close(){

        ourhelper.close();
    }

    public long createEntry(String name, String blog) {
        // TODO Auto-generated method stub
        ContentValues cv = new ContentValues();
        cv.put(KEY_NAME, name);
        cv.put(KEY_BLOG, blog);
        return ourdatabase.insert(DATABASE_TABLE, null, cv);

    }

    public String getDataFunc() {
        // TODO Auto-generated method stub
        String columns[]= new String[]{KEY_ROWID, KEY_NAME, KEY_BLOG};
        Cursor c = ourdatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
        String result= "";
        int iRow = c.getColumnIndex(KEY_ROWID);
        int iName = c.getColumnIndex(KEY_NAME);
        int iBlog = c.getColumnIndex(KEY_BLOG);

        for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
         result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iBlog) + "\n";
        }
        return result;
    }


}

在这里,我使用该结果向我的用户显示博客

public class SQLLiteView extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sqlview);
        TextView tv =(TextView)findViewById(R.id.tvSQLinfo);
        SQLBlog getdata = new SQLBlog(this);
        getdata.open();
        String data = getdata.getDataFunc();
        getdata.close();
        tv.setText(data);
    }



}

但问题是我将数据作为字符串获取,但我想更动态地显示数据,例如......

嘿,伙计们,你好吗:由杰克发布

//这里会给出评论...

如何从我的数据库中获取数据并将其放在可点击的 ListView 上:Nicole 发布

//评论放在这里

我怎样才能做到这一点..需要帮助...我想我正在寻找某种类型的 foreach 循环,如 php ......它可以破坏数据..但是因为我使用 String 作为返回类型,所以我无法得到它..

4

2 回答 2

1

首先,创建一个将存储您的内容的类:

public class BlogEntry { //I suppose you will call that a BlogEntry ?
    public int id;
    public String name;
    public String question;
    public String blog;
    public ArrayList<Comment> comments = new ArrayList<Comment>();
}

以及存储您的评论的课程:

public class Comment {
    public int id;
    public int questionId;
    public String name;
    public String comment;
    public String blog;

}

然后使用您的 SQLBlog 类创建 2 个表,它们将匹配这两个类中描述的数据。

您现在应该创建一个类似的方法:

public ArrayList<BlogEntry> getAllEntries() {

    Cursor c = db.rawQuery("SELECT * FROM blogentries", null);
    int iRow = c.getColumnIndex(KEY_ROWID);
    int iName = c.getColumnIndex(KEY_NAME);
    int iBlog = c.getColumnIndex(KEY_BLOG);
    int iQuestion = c.getColumnIndex("question");

    //table comment
    int row = c.getColumnIndex("id");
    int name = c.getColumnIndex("name");
    int blog = c.getColumnIndex("blog");
    int iComment = c.getColumnIndex("comment");

    ArrayList<BlogEntry> entries = new ArrayList<BlogEntry>();
    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        BlogEntry b = new BlogEntry();
        b.id = c.getInt(iRow);
        b.name = c.getString(iName);
        b.blog = c.getString(iBlog);
        b.question = c.getString(iQuestion);
        Cursor c2 = db.rawQuery("SELECT * FROM comments WHERE questionId=? ORDER BY id ASC", new String[]{String.valueOf(b.id)});

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            Comment com = new Comment();
            com.questionId = b.id;
            com.id = c.getInt(row);
            com.name = c.getString(name);
            com.blog = c.getString(blog);
            com.comment = c.getString(iComment);
            b.comments.add(com);
        }
        entries.add(b);
    }
    return entries;
}

您现在应该有一些可以使用的东西,下一步是创建一个带有列表视图和适配器的活动来映射数据。

在我的示例中,我将使用如下所示的 ExpandableListView:ExpandableListView

这是 ListViewLayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
android:orientation="horizontal" android:baselineAligned="false">
    <ExpandableListView android:id="@+id/myExpandableListView "
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    </ExpandableListView>
</LinearLayout>

您的活动:

public class myActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout);
    ExpandableListView list = (ExpandableListView) findViewById(R.id.myExpandableListView);
    ArrayList<BlogEntry> entries = new SQLBlog().getAllEntries();
    list.setAdapter(new MyExpandableListAdapter(entries));
}

我们需要创建一个项目布局:(称之为 itemlayout.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" android:baselineAligned="false">
 <TextView
        android:id="@+id/myTextViewThatWillHoldTheQuestion"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

你的 MyExpandableListAdapter :

public class MyExpandableListAdapter extends BaseExpandableListAdapter {
    ArrayList<BlogEntry> entries;
    LayoutInflater inflater;
    public MyExpandableListAdapter(ArrayList<BlogEntry> entries, Context ctx) {
        this.entries = entries;
        inflater = LayoutInflater.from(ctx);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return entries.get(groupPosition).comments.get(childPosition);
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return entries.get(groupPosition).comments.get(childPosition).id;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        commentHolder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.id.itemlayout, null); //we use the same for comment and blogentry but you shouldn't coz you want the display to change
            holder.myTextViewThatHoldComment = (TextView)convertView.findViewById(R.id.myTextViewThatWillHoldTheQuestion);
            convertView.setTag(holder);
        } else {
            holder = (commentHolder) convertView.getTag();
        }
        Comment item = (Comment)getChild(groupPosition,childPosition);
        holder.myTextViewThatHoldComment.setText(item.comment);
        return convertView;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return entries.get(groupPosition).comments.size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return entries.get(groupPosition);
    }

    @Override
    public int getGroupCount() {
        return entries.size();
    }

    @Override
    public long getGroupId(int groupPosition) {
        return entries.get(groupPosition).id;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        BlogEntryHolder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.id.itemlayout, null); //we use the same for comment and blogentry but you shouldn't coz you want the display to change
            holder.myTextViewThatHoldQuestion = (TextView)convertView.findViewById(R.id.myTextViewThatWillHoldTheQuestion);
            convertView.setTag(holder);
        } else {
            holder = (BlogEntryHolder) convertView.getTag();
        }
        BlogEntry item = (BlogEntry)getGroup(groupPosition);
        holder.myTextViewThatHoldComment.setText(item.question);
        return convertView;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }

    private  class BlogEntryHolder{
        TextView myTextViewThatHoldQuestion;
    }
    private  class commentHolder{
        TextView myTextViewThatHoldComment;
    }

}

你应该有你问的东西:)

于 2013-05-16T08:12:01.230 回答
0

你已经有一个foreach循环:

    for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
         result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iBlog) + "\n";
    }

在这里,您将字符串连接在一起,只需将此foreach循环放入您的活动中(返回cursor, 而不是String)或使用具有三个字段的新类创建一个列表并存储您的字段。

这是一个将结果包装在一个类中的示例——这通常是一个好主意。但我真的建议阅读一些关于 java 和面向对象编程的东西。

如果您不想将光标重新返回到活动,您可以这样做。首先创建一个保存博客对象的新类:

public class Blog {

    private String author;
    private String content;

    public Blog(String author, String content){
        this.author = author;
        this.content = content;
    }

    public String getAuthor(){
        return author;
    }

    public String getContent(){
        return content;
    }
}

然后像这样更改您的数据库方法:

public List<Blog> getDataFunc() {
    // TODO Auto-generated method stub
    String columns[]= new String[]{KEY_ROWID, KEY_NAME, KEY_BLOG};
    Cursor c = ourdatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
    List<Blog> results = new ArrayList<Blog>();
    int iRow = c.getColumnIndex(KEY_ROWID);
    int iName = c.getColumnIndex(KEY_NAME);
    int iBlog = c.getColumnIndex(KEY_BLOG);

    for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
     results.add(new Blog(c.getString(iName),c.getString(iBlog)));
    }
    return results;
}

现在在您的活动中,您可以像这样迭代:

   @Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sqlview);
    TextView tv =(TextView)findViewById(R.id.tvSQLinfo);
    SQLBlog getdata = new SQLBlog(this);
    getdata.open();
    for(Blog blog : getdata.getDataFunc()){
        Log.v("tag",blog.getAuthor());
        Log.v("tag",blog.getContent());
    }
    getdata.close();
    tv.setText(data);
}
于 2013-05-16T07:27:27.603 回答