Use values passed from one Activity to another

Asked

Viewed 339 times

0

Guys, I’m having a hard time with something. I created a list that shows contact names, but these contacts have more attributes, such as date and number. I made another screen for when the person click on the list, go on this other screen and shows all the details of such contact. I did such encoding. (I am using Sqlite to save/use contacts) if this is relevant On the contact details screen, I did this:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_contact__detail);

    long idSelected = getIntent().getLongExtra("ID", 0);
    long positionSelected = getIntent().getIntExtra("POSITION", 0);


    textView_dName = (TextView) findViewById(R.id.textView_dName);
    textView_dDate = (TextView) findViewById(R.id.textView_dDate);
    textView_dNumber = (TextView) findViewById(R.id.textView_dNumber);

}

My question is: How do I get textviews to receive past values? For example: textView_dName.setText such a. I ask for help please with such code, thanks in advance!

EDITED

Class Dbhelper:

public final static String DATABASE = "mydb";
public final static String TABLE = "contacts";
public final static String NAME = "name";
public final static String DATE = "date";
public final static String NUMBER = "numberr";

public DBHelper(Context context) {
    super(context, DATABASE, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table if not exists "+TABLE+" (id integer primary key, "+NAME+" text, "+DATE+" text, "+NUMBER+" text)");


}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public boolean insertContact(String name, String date, String number){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues content = new ContentValues();
    content.put(NAME, name);
    content.put(DATE, date);
    content.put(NUMBER, number);
    db.insert(TABLE, null, content);
    return true;
}

public ArrayList<Contact> getAllContacts(){
    ArrayList<Contact> myArray = new ArrayList<Contact>();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cur = db.rawQuery("select * from "+TABLE, null);
    cur.moveToFirst();
    while(cur.isAfterLast()==false){
        Contact c = new Contact();
        c.setName(cur.getString(cur.getColumnIndex(NAME)));
        c.setDate(cur.getString(cur.getColumnIndex(DATE)));
        c.setNumber(cur.getString(cur.getColumnIndex(NUMBER)));
        myArray.add(c);
        cur.moveToNext();
    }
    return myArray;
}

//

public Cursor getAllContactss(){

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cur1 = db.rawQuery("select * from "+TABLE, null);

    return cur1;
}

Mainactivity:

DBHelper myDb = new DBHelper(this);
Cursor cursor = myDb.getAllContactss();
String[] columns = new String[]{
        DBHelper.NAME,
        DBHelper.DATE,
        DBHelper.NUMBER
};

int[] to = new int[]{
        R.id.textView_l1,
        R.id.textView_l2,
        R.id.textView_l3
};

ListView listView_contacts = (ListView) findViewById(R.id.listView_contacts);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SimpleCursorAdapter myAdapter1 = new SimpleCursorAdapter(this,
            R.layout.layoutdalist,
            cursor,
            columns,
            to,
            0);

    listView_contacts.setAdapter(myAdapter1);




    listView_contacts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Cursor cursor1 = (Cursor) listView_contacts.getItemAtPosition(position);
            String nome = cursor1.getString(cursor1.getColumnIndex(DBHelper.NAME));
            String data = cursor1.getString(cursor1.getColumnIndex(DBHelper.DATE));
            String number = cursor1.getString(cursor1.getColumnIndex(DBHelper.NUMBER));
            Intent intent = new Intent(getApplicationContext(), Contact_Detail_Activity.class);
            intent.putExtra("NOME", nome);
            intent.putExtra("DATA", data);
            intent.putExtra("NUMERO", number);
            startActivity(intent);
           /* Intent intent = new Intent(getApplicationContext(), Contact_Detail_Activity.class);
            intent.putExtra("ID", id);
            intent.putExtra("POSITION", position);
            startActivity(intent); */
        }
    });



}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);

    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch(item.getItemId()){
        case R.id.menu_item_new_contact:
            startActivity(new Intent(MainActivity.this, NewContactActivity.class));
            break;
    }

    return super.onOptionsItemSelected(item);
}

protected void onResume() { super.onResume();

    DBHelper myDb = new DBHelper(this);
    ArrayList<String> arrayNames = new ArrayList<String>();
    for(int i = 0; i < myDb.getAllContacts().size(); i++){
        arrayNames.add(myDb.getAllContacts().get(i).getName());

    }

    ArrayAdapter myAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayNames);
    listView_contacts.setAdapter(myAdapter);
  • 1

    Your doubt would be in relation to TextView receive the values or how to make you search for this data in Sqlite?

  • My question is how would I set the data that I have stored in the text views of the other Activity. I hope you understand, I think it would be in relation to Textview itself

  • 1

    But in your question is already the answer, just use the function you said: textView_dName.setText("texto recebido");. The steps would be to take your variable idSelected that is coming in Intent, consult the bank contact with this identification and pass the data through the setText of TextView, that would be it?

  • Hmm, could you explain to me how I would consult at the bank using the idSelected? and give the setText with the result?

  • 1

    The id that shows on Adapter is not the id in the database, you need to create an Adapter that stores this ID or do a Hashmap to connect the X ID to the item ID in the adapter.

  • 1

    If possible, show how you populate this Listview, then it is easier to suggest how to implement this issue

  • 1

    Another option is to use a Simplecursoradapter, in which case the ID in the item will be the _id of the table.

  • @Lucasqueirozribeiro I edited my post and put more information about the program. I put the class DBhelper which has a population method and the MainActivity which has a repopulation method as well. Thanks for the help

Show 3 more comments

1 answer

1


There are several ways you can get what you want, I would use a Simplecursoradapter.

It works as follows, instead of you passing a list of Strings to popular Listview, you will pass directly the Cursor, this way, when selecting an item you can access any information from that record (which you have included in the initial query of course).

So let’s go the implementation.

Dbhelper class:

public Cursor getAllContacts(){

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cur = db.rawQuery("select * from "+TABLE, null);

    return cur;
}

Mainactivity:

DBHelper myDb = new DBHelper(this);

 Cursor cursor = myDb.getAllContacts();

String[] columns = new String[] {
NAME
};  // Coloque o nome das colunas que você deseja exibir


int[] to = new int[] { 
  R.id.textViewName   
  }; // Colocar o ID da textview que você vai utilizar pra mostrar os dados (Se for mais de um, só acrescente , entre um e outro, o mesmo com as colunas)

SimpleCursorAdapter myAdapter= new SimpleCursorAdapter(
this,  // Contexto
R.layout.meu_layout_itens, // O layout que será inflado para comportar os itens (crie um xml com um Root Element como um Linear Layout e coloque um TextView nele, estilize como quiser, só não esqueça de usar o mesmo id que você usou acima)
cursor,           // Seu cursor
columns,          // Nome das colunas do banco
to,              // Views que receberão os dados
0);              // Nesse campo você pode usar uma Flag para ativar outras funções do Adapter, como auto atualizar ou registrar um Observer (Não vamos entrar nesse mérito aqui ainda) 


listView_contacts.setAdapter(myAdapter);
}

And in his Clicklistener:

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Cursor cursor = (Cursor) listView.getItemAtPosition(position); // Recupera o cursor na posição escolhida
        String nome =  cursor.getString(cursor.getColumnIndexOrThrow("NAME")); // Pega o item que deseja de dentro do cursor

        Intent intent = new Intent(getApplicationContext(), Contact_Detail_Activity.class);
        intent.putExtra("NOME", nome); // Envie tudo que precisar, repita com outros campos necessários
        startActivity(intent);
    }

Don’t forget to create the Layout file

  • Whoops, thanks for the answer. Just a few questions about this implementation. String[] columns = new String[] {&#xA;NAME&#xA;}; Where there is NAME I would put the columns made in Dbhelper, right? and put type "name", "date", "number" and in int[] to = new int[] { &#xA; R.id.textViewName &#xA; }; I would put R.id.textView_dName, R.id.textView_dDate, R.id.textView_dNumber? I already have Activity with people’s details, it has these 3 TextView

  • R.layout.meu_layout_itens, // O layout que será inflado para comportar os itens (crie um xml com um Root Element como um Linear Layout e coloque um TextView nele, estilize como quiser, só não esqueça de usar o mesmo id que você usou acima) here I put my Activity with contact details, which contains the textView_dName, dDate and dNumber. Correct?

  • 1

    Where are you going NAME you use the same DB Helper variable, the Columns you want to display, as for Layout, before you were inflating the android.R.layout.simple_list_item_1 this is a standard Android layout, however, you do not have access to the Textviews that it uses, so you create a Layout of your own, with the Textviews that you want to use, and on int[] to = new int[] { R.id.textViewName } you put the ID of these views. This is only for you to map, saying that that String item goes to that View.

  • 1

    The layout you use for Activity has other things put together right? Ideally you use a layout just for the items. Then it would be a Linearlayout>Textview|Textview|Textview. And this will be repeated for each Listview item

  • I got it, I just created a layout and put 3 TextViewin them. Where you told to put the Dbhelper variable, I can’t put the NAME variable there, it turns red. I don’t think I have access to the Dbhelper variable outside of class. Then I put "name" which is what is in the variable NAME, another question, how I will recover these values in my class Contact_detail_activity?

  • 1

    If the variables are private you will not be able to use them yourself, if it is public you have to import the class. To recover the data, you take the "extras" you are ordering in Intent

  • Opa, sorry to bother you again Lucas, I did what you asked, I think I’m on the right track, however, my app is going wrong as soon as it opens, I edited the post as was the code after the changes. Did I do right? Thanks again

  • 1

    @Viskee Which error message gives ?

  • 1

    Hi Lucas, I managed to solve the problem using your methods. I kept giving a stir there and here and solved. Thanks for your help and patience.

Show 4 more comments

Browser other questions tagged

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