在android中用于打破数据的foreach循环

时间:2013-05-16 07:12:10

标签: android arrays for-loop arraylist foreach

这是我的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

//评论到这里

我怎样才能实现这个...需要帮助...我想我正在寻找像php这样的类型foreach循环...这可以打破数据..但是因为我使用String作为返回类型我不能得到它..

2 个答案:

答案 0 :(得分: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;
}

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

在我的示例中,我将使用看起来像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;
    }

}

你应该有像你这样的问题:)

答案 1 :(得分: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;
    }
}

然后像这样更改你的db-method:

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);
}