Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/194.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
android中用于中断数据的foreach循环_Android_Arrays_For Loop_Arraylist_Foreach - Fatal编程技术网

android中用于中断数据的foreach循环

android中用于中断数据的foreach循环,android,arrays,for-loop,arraylist,foreach,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.s

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



}
但问题是我获取的数据是字符串,但我想更动态地显示数据,如

嘿,伙计们,你好吗?杰克发帖

//评论将在这里给出

如何从我的数据库中获取数据并将其放在可点击的列表视图中:Nicole发布

//评论就在这里


如何实现这一点..需要帮助..我想我正在搜索某种类型的foreach循环,比如php…它可以破坏数据..但由于我使用字符串作为返回类型,我无法获取它..

您已经有了一个
foreach
循环:

    for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
         result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iBlog) + "\n";
    }
在这里,您可以将字符串连接在一起,只需将此
foreach
循环放入活动中(返回
光标,而不是
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方法,如下所示:

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

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

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>();
}
然后使用SQLBlog类创建两个表,这些表将匹配这两个类中描述的数据

您现在应该创建一个方法,如:

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;
}
public ArrayList getAllEntries(){
游标c=db.rawQuery(“SELECT*fromBlogEntries”,null);
int iRow=c.getColumnIndex(KEY_ROWID);
int iName=c.getColumnIndex(键名称);
int iBlog=c.getColumnIndex(KEY_BLOG);
int iQuestion=c.getColumnIndex(“问题”);
//表注释
int row=c.getColumnIndex(“id”);
int name=c.getColumnIndex(“名称”);
int blog=c.getColumnIndex(“blog”);
int iComment=c.getColumnIndex(“注释”);
ArrayList条目=新的ArrayList();
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
BlogEntry b=新的BlogEntry();
b、 id=c.getInt(iRow);
b、 name=c.getString(iName);
b、 blog=c.getString(iBlog);
b、 问题=c.getString(iQuestion);
游标c2=db.rawQuery(“从注释中选择*,其中questionId=?按id排序ASC”,新字符串[]{String.valueOf(b.id)});
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
Comment com=新注释();
com.questionId=b.id;
com.id=c.getInt(行);
com.name=c.getString(name);
com.blog=c.getString(blog);
com.comment=c.getString(iComment);
b、 comments.add(com);
}
条目。添加(b);
}
返回条目;
}
您现在应该可以使用一些东西了,下一步是创建一个带有listview和适配器的活动来映射数据

在我的示例中,我将使用一个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));
}
公共类myActivity扩展活动{
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
ExpandableListView列表=(ExpandableListView)findViewById(R.id.myExpandableListView);
ArrayList entries=new SQLBlog().getAllEntries();
setAdapter(新的MyExpandableListAdapter(条目));
}
我们需要创建一个项目布局:(称之为itemlayout.xml)


您的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;
    }

}
公共类MyExpandableListAdapter扩展了BaseExpandableListAdapter{
ArrayList条目;
充气机;
公共MyExpandableListAdapter(ArrayList条目,上下文ctx){
this.entries=条目;
充气机=从(ctx)开始的充气机;
}
@凌驾
公共对象getChild(int-groupPosition,int-childPosition){
返回条目.get(groupPosition).comments.get(childPosition);
}
@凌驾
公共长getChildId(int-groupPosition,int-childPosition){
返回条目.get(groupPosition).comments.get(childPosition).id;
}
@凌驾
公共视图getChildView(int-groupPosition、int-childPosition、布尔isLastChild、视图convertView、视图组父级){
持票人;
if(convertView==null){
convertView=inflater.inflate(R.id.itemlayout,null);//我们对注释和博客条目使用相同的方法,但您不应该这样做,因为您希望显示发生更改
holder.myTextViewThatHoldComment=(TextView)convertView.findViewById(R.id.myTextViewThatHoldComment将保留问题);
convertView.setTag(支架);
}否则{
holder=(commentHolder)convertView.getTag();
}
注释项=(注释)getChild(groupPosition,childPosition);
holder.myTextViewThatHoldComment.setText(item.comment);
返回视图;
}
@凌驾
公共整数getChildrenCount(整数组位置){
返回entries.get(groupPosition.comments.size();
}
@凌驾
公共对象getGroup(int-groupPosition){
返回条目.get(groupPosition);
}
@凌驾
public int getGroupCount(){
返回条目。size();
}
@凌驾
公共长getGroupId(int-groupPosition){
返回条目.get(groupPosition).id;
}
@凌驾
公共视图getGroupView(int groupPosition、布尔isExpanded、视图convertView、视图组父级){
博客持有者;
if(convertView==null){
convertView=inflater.inflate(R.id.itemlayout,null);//我们对注释和博客条目使用相同的方法,但您不应该这样做,因为您希望显示发生更改
holder.myTextViewThatHoldQuestion=(TextView)conv
<?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>
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;
    }

}