【问题标题】:foreach loop in android for breaking dataandroid中的foreach循环用于破坏数据
【发布时间】:2013-05-10 23:24:12
【问题描述】:

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



}

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

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

//这里会给出cmets...

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

//评论放这里

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

【问题讨论】:

  • 请提供有关 cmets 和帖子的数据库结构,我认为这会有所帮助。但是一点建议:您应该创建一个代表您的表的类并使用列表视图的自定义适配器来映射数据(有关适配器和列表视图的更多信息:vogella.com/articles/AndroidListView/article.html
  • 我发布了整个班级..检查出来..@NeeL

标签: android arrays for-loop arraylist foreach


【解决方案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>();
}

还有存储你的 cmets 的类:

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:

这里是 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;
    }

}

你应该有你问的东西:)

【讨论】:

    【解决方案2】:

    你已经有一个foreachloop:

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

    【讨论】:

    • 这行是什么意思??... Log.v("tag",blog.getAuthor());
    • 你能建议我在哪里阅读有关 java 和面向对象编程的内容。它应该会有所帮助
    • 在尝试做类似的事情之前,你真的应该学习 OOP 和 java+android 基础 =) 你可以从在 google 上的 java 中输入 OOP 开始,我相信你会发现很多有用的链接
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多