Taking String values from Arraylist<Object>

Asked

Viewed 2,541 times

0

I take all my values from the database and put them in one array list<object> i would like to know how to access the value within this arraylist emu, for example TesteLinhas.get(0).toString() or something like return me to where it is allocated in memory, I believe. I would like me to get the value of it. There is some way?

ArrayList linhas = new ArrayList();

        String sql = "SELECT * FROM tb_zerados ORDER BY id ASC";

        conexao.pstm  = conn.prepareStatement(sql);
        conexao.rs = conexao.pstm.executeQuery();

        while(conexao.rs.next()){
            linhas.add(new Object[]{conexao.rs.getInt("id"),
                                    conexao.rs.getInt("numero"),
                                    conexao.rs.getString("ano"),
                                    conexao.rs.getString("nome"),
                                    conexao.rs.getString("estilo"),
                                    conexao.rs.getString("plataforma"),
                                    conexao.rs.getInt("nota")});

        }

        System.out.println(linhas.get(1));

He returns it to me: [Ljava.lang.Object;@28a8f402, and I’d like you to return a String or a Integer.

3 answers

2

You’re putting a array within a ArrayList. I don’t recommend doing it this way, but since you did, the solution is to access the array within the ArrayList. It’s like another dimension. That’s how it works:

System.out.println(linhas.get(1)[0]);

The get(1) is taking the line and the [0] is taking the column.

You have to do this for each field, that is, it must go from 0 to 6 since it has 7 fields.

Can make a loop:

for (Object obj : linhas.get(1)) {
    System.out.println(obj);
}

I put in the Github for future reference.

  • Hello, he sent me mistakes, but I already got the solution with the other who answered. Thank you anyway. Another thing, I wonder why you mean it’s wrong for me to do it like this? I did this way to fill a table using a Tablemodel.

  • It is complicated to answer in a comment, basically you should have a class to deal with it and not throw everything into one array.

1


Each line created in this list is of the type array of Object[], when you recover, you have to give a cast of the type (which in this case is Object[]) and to regain the positions which in their case are 7 (of 0 to 6) return to intended position.

Example with all positions:

System.out.println(((Object[])linhas.get(0))[0]);
System.out.println(((Object[])linhas.get(0))[1]);
System.out.println(((Object[])linhas.get(0))[2]);
System.out.println(((Object[])linhas.get(0))[3]);
System.out.println(((Object[])linhas.get(0))[4]);
System.out.println(((Object[])linhas.get(0))[5]);
System.out.println(((Object[])linhas.get(0))[6]);

here is a minimal example, with fictitious data, but that can help you understand how to recover

This will probably solve your problem, but ideally always create a datum tipado with a array using this guy, it is much easier to recover.

Reading:

  • 1

    Thank you so much for your reply helped me a lot, congratulations for collaborating with the community.

  • @I thank Hamoncórdova. vlw

0

I do something similar in my app and this can help you.

I have a dbHelper class, where all methods of database manipulation are defined.

This is the method that reads the database and returns a list (as an array) of objects that reflect the table:

//Table Name
private static final String TABLE_RUNS = "runs";
//Table Columns
private static final String _ID = "_id";
private static final String COL_ADDRESS = "address"; 
private static final String COL_NAME = "name"; 
private static final String COL_DATE = "date"; 


List<RunData> getAllRuns() {

    List<RunData> runsList = new ArrayList<>();

    String RUN_SELECT_QUERY = "SELECT * FROM " + TABLE_RUNS;

    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.rawQuery(RUN_SELECT_QUERY, null);

    try {
        if (cursor.moveToFirst()) {
            do {
                RunData runData = new RunData();
                runData.run_id = cursor.getString(cursor.getColumnIndex(_ID));

                runData.name = cursor.getString(cursor.getColumnIndex(COL_NAME));
                runData.address = cursor.getString(cursor.getColumnIndex(COL_RADDRESS));
                runData.date = cursor.getString(cursor.getColumnIndex(COL_DATE));

                runsList.add(runData);

            } while (cursor.moveToNext());
        }
    } catch (Exception e) {
        //Log.d(TAG, "Error while trying to get posts from database");
    } finally {
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
    }
    return runsList;
}

Use like this:

// Defina os objetos
RunDbHelper runDbHelper;
List<RunData> runList = new ArrayList<>();

// Instancie a classe dbHelper
runDbHelper = RunDbHelper.getInstance(getContext());
// call para ler o banco de dados e retornar uma lista de objetos runData
runList = runDbHelper.getAllRuns();
for (RunData runData : runList) { // percorre a lista de dados, usando runData como container
    // Agora, cada linha da lista (é manipulada como objeto de dados 
    doWhatwEver(runData.name, runData.address, runData.date); 
}

Rundata is a POJO or Javabeans type object that has the same fields as the table. It is easier to manipulate than array indices.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.