Android Sqlite: Displaying bank content in textView?

Asked

Viewed 4,232 times

2

I would like to know how I do to display content from the Sqlite database in textviews. I am using the following method to display in a Customlistview:

    public Cursor getAllData ()
{
    String buildSQL = "SELECT * FROM " + DatabaseHelper.DiferencaPercentual.TABELA; //pega todos os dados da tabela
    return database.rawQuery(buildSQL, null);
}

And then I hand it over to an Adapter telling me what the fields in my custom list view are:

    @Override
public void bindView(View view, Context context, Cursor cursor) 
{
    TextView textViewPersonName = (TextView) view.findViewById(R.id.tv1);
    textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));

    TextView textViewPersonPIN = (TextView) view.findViewById(R.id.tv2);
    textViewPersonPIN.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(2))));
}

And then I pass it all on to Activity, in the onCreate method:

        new Handler().post(new Runnable() {
        @Override
        public void run() {
            //customAdapter = new CustomCursorAdapter(ListarCliente.this, clienteDAO.findById(51));
            customAdapter = new ClienteAdapter(ListarCliente.this, clienteDAO.getAllData());
            listView.setAdapter(customAdapter);
        }
    });

And in a separate method:

    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK)
    {
        clienteDAO.insertData(data.getExtras().getString("tag_nome"),
                              data.getExtras().getString("tag_email"));

        customAdapter.changeCursor(clienteDAO.getAllData());
    }
}

My question is, there is no simpler way to take the contents of the database and quickly display in a textView, just so the user can edit the information?

Thank you for your attention!

1 answer

2


I’ll give you an example that I’m sure works. Since you have not shown your complete code, I will present a form, you must adapt it and study it:

1 - You need to make every field of your listView clickable, so it can be passed via putExtra(); the information of each item individually- EXAMPLE:

...
...
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

...
...

        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long viewId) {
                TextView idTextView = (TextView) view.findViewById(R.id.id);
                TextView titleTextView = (TextView) view.findViewById(R.id.titulo);
                TextView descTextView = (TextView) view.findViewById(R.id.desc);

                String id = idTextView.getText().toString();
                String titulo = titleTextView.getText().toString();
                String desc = descTextView.getText().toString();

                Intent modify_intent = new Intent(getApplicationContext(), ModifyTodoActivity.class);
                modify_intent.putExtra("titulo", titulo);
                modify_intent.putExtra("desc", desc);
                modify_intent.putExtra("id", id);

                startActivity(modify_intent);
            }
        });
    }

2 - To display on TextView create a new activity and make this logic:

Displaying activity.class:

...
...

//título do texto.   
        titleText = (TextView) findViewById(R.id.subject_edittext);

//descrição do texto. 
        descText = (TextView) findViewById(R.id.description_edittext);


//RECEBE OS VALORES DA ATIVIDADE PRINCIPAL

        Intent intent = getIntent();
        String name = intent.getStringExtra("titulo");
        String desc = intent.getStringExtra("desc");

    //EXIBINDO NO TEXTVIEW, CONFORME VOCÊ PEDIU - NOME E DESCRIÇÃO SÃO EXEMPLOS

            titleText.setText(name);
            descText.setText(desc);

...
}

If you want to edit the fields, follow the logic below:

2 - You will need to create an activity that will only serve to modify the fields, is a tip, so the client will be directed to an editing screen. WILL NOT NEED SELECT, everything will be passed by parameters:

Modificandoactivity.class:

public class ModificandoActivity extends Activity implements OnClickListener {

...
...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

...
//Abra o banco
//NÃO SE PREOCUPE COM SELECT, OS TEXTOS VIRÃO POR getStringExtra();
//Abrir o banco é somente para dar o update e delete, CASO VOCÊ ASSIM QUEIRA

//título do texto. Aqui abrimos um EditText para que ele possa ser editado     
        titleText = (EditText) findViewById(R.id.subject_edittext);

//descrição do texto. Aqui abrimos um EditText para que ele possa ser editado
        descText = (EditText) findViewById(R.id.description_edittext);

//Botão update. Aqui abrimos um Button para para salvar as mudanças

        updateBtn = (Button) findViewById(R.id.btn_update);

//Botão delete. Aqui abrimos um Button para para deletar a o texto NO BANCO
        deleteBtn = (Button) findViewById(R.id.btn_delete);

//RECEBE OS VALORES DA ATIVIDADE PRINCIPAL

        Intent intent = getIntent();
        String id = intent.getStringExtra("id");
        String name = intent.getStringExtra("titulo");
        String desc = intent.getStringExtra("desc");

        _id = Long.parseLong(id);

//EXIBINDO NO EDITTEXT - NOME E DESCRIÇÃO SÃO EXEMPLOS

        titleText.setText(name);
        descText.setText(desc);

        updateBtn.setOnClickListener(this);
        deleteBtn.setOnClickListener(this);
    }

//ESSA PARTE É FUNDAMENTAL, POIS O CLIENTE PODERÁ DELETAR OU DAR UPDATE
//DEPOIS QUE ELE ESCOLHER, O CASE IRÁ SETAR O NOVO VALOR OU DELETAR

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn_update:

//SETANDO O NOVO TEXTO NA STRING
            String titulo = titleText.getText().toString();
            String desc = descText.getText().toString();

//UPDATE NO BANCO É UM EXEMPLO

            dbManager.update(_id, titulo, desc);
            this.returnHome();
            break;

        case R.id.btn_delete:
//ele pega o ID, busca no banco e deleta a coluna referente (é somente uma lógica)
            dbManager.delete(_id);
            this.returnHome();
            break;
        }
    }
  • That’s a great idea, man! Just one last question to mark you as the best answer: The edit button is in a Contextmenu, would the onItemClick method be activated yet? UPDATE: I found a way to do this. Thanks friend!

  • Note this: http://stackoverflow.com/questions/17419357/how-to-open-menu-context-android-with-click-button-listview-adapter

  • You did it, Diego?

  • Not yet, but I believe I’m on the right track! Maybe I should create a method with the content of onItemCLick and pass it on to onLongItemClick, but I’ll look for a simpler alternative

  • Okay, I found a link that’s helping me ( http://android.konreu.com/developer-how-to/click-long-press-event-listeners-list-activity/ ). If I can, I’ll let you know! thank you!

  • All right. Let me know! Is this link I gave you? No good? http://stackoverflow.com/questions/17419357/how-to-open-menu-context-android-with-click-button-in-listview-adapter

  • Dude, I was able to get information with Longclick and Normal Click, and still use the contextmenu. Thanks a lot bro! Then I’m going to post the answer to how to do this in a separate question, because it gave a giant job of finding XD vlw bro!

  • It took a while, man. I sent you an e-mail and I’ll post the answer here on the stack of the solution I found in a little while

Show 3 more comments

Browser other questions tagged

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