访问ArrayList中的对象

时间:2017-10-30 20:57:57

标签: java android sqlite

我有一个SQLite数据库,其中包含一个名为author的表。我尝试提取idname值并将其传递给MainActivity,其中id将作为变量存储,name将显示在的ListView。

name方面的工作正常,但我不确定如何在我的MainActivity中获取id值。我在get上尝试了authorList ArrayList的public List<Author> getAllAuthors() { List<Author> authorList = new ArrayList<>(); // Select all query String selectQuery = "SELECT * FROM " + AUTHORS + " ORDER BY name_alphabetic"; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { // create new author object Author author = new Author(); // set ID and name of author object author.setID(Integer.parseInt(cursor.getString(0))); author.setName(cursor.getString(1)); // pass author object to authorList array authorList.add(author); } while (cursor.moveToNext()); } // return author list return authorList; } 方法而没有运气。

DatabaseHelper的片段:

public class Author {
    int id;
    String name;
    String name_alphabetic;

    @Override
    public String toString() {
        return name;
    }

    public Author() {
    }

    public Author(int id, String name, String name_alphabetic) {
        this.id = id;
        this.name = name;
        this.name_alphabetic = name_alphabetic;
    }

    // getters
    public int getID() {
        return this.id;
    }

    public String getName() {
        return this.name;
    }

    public String getNameAlphabetic() {
        return this.name_alphabetic;
    }

    // setters
    public void setID(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setNameAlphabetic(String name_alphabetic) {
        this.name_alphabetic = name_alphabetic;
    }
}

作者类:

// connect authorsListView variable to XML ListView
authorsListView = (ListView) findViewById(R.id.authors_list_view);

// create new database helper
DatabaseHelper db = new DatabaseHelper(this);

// create new list through getAllAuthors method (in DatabaseHelper class)
List authorList = db.getAllAuthors();

Log.i("authors", authorList.toString());

// create new Array Adapter
ArrayAdapter<Author> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, authorList);

// link ListView and Array Adapter
    authorsListView.setAdapter(arrayAdapter);

// onItemClickListener waits for user to tap a ListView item
        authorsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                String author = authorsListView.getItemAtPosition(i).toString();

                //Log.i("click", author);

                // new Intent specifies which Activity to move from and to
                Intent intent = new Intent(MainActivity.this, StoriesActivity.class);
                // adds extra author variable to the Intent
                intent.putExtra("author", author);
                startActivity(intent);
            }
        });
来自MainActivity的

片段:

authorList.get(0)

修改

我已尝试返回return authorList.get(id)id(虽然我知道intent.putExtra("author", author_id)尚未设置)。传递此变量的目的是稍后在MainActivity中我可以使用Intent extra将其传递给另一个Activity,即boatDict = {'destroyer1': [3, 5], 'destroyer2': [7, 2], 'submarine1': [1, 1], 'submarine2': [], 'battleship': [], 'carrier': [5, 2]} boatCount = {} for key in boatDict: if boatDict[key] != []: boat = ''.join(i for i in str(key) if not i.isdigit()) if boat not in boatCount: boatCount[boat] = 1 else: boatCount[boat] += 1 print(boatCount) #output {'submarine': 1, 'carrier': 1, 'destroyer': 2}

1 个答案:

答案 0 :(得分:0)

在你的代码中,我看到了:

List authorList = db.getAllAuthors();

您应该将其定义为List<Author>而不是List,这样get()方法将返回Author而不是Object。完成更改后,您应该能够像这样访问作者id

List<Author> authorList = db.getAllAuthors();
int id = authorList.get(0).getID(); // the id of the first author in the list

请注意List的一般规则适用于此处,因此如果列表为空,则get(0)将引发异常。

更新

您可以使用AdapterView.getItemAtPosition(int)方法访问OnItemClickListener内点击的数据对象。由于您将ArrayAdapter定义为ArrayAdapter<Author>,因此您可以保证getItemAtPosition()将返回Author个实例,因此您可以编写如下代码:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Author author = (Author) parent.getItemAtPosition(position);

    Intent intent = new Intent(MainActivity.this, StoriesActivity.class);
    intent.putExtra("author_id", author.getID());
    intent.putExtra("author_name", author.getName());

    startActivity(intent);
}

当您开始使用更复杂的对象时,如果您发现将每个字段(例如nameid)逐个添加到Intent会很烦人,您可以考虑在您的对象上实施Parcelable界面:https://developer.android.com/reference/android/os/Parcelable.html

然后您可以直接将Author添加到Intent,而不是添加其字段。