Use past values from one Activity to another

0

Well, I'm having trouble with a certain thing. I have created a list where it shows the names of contacts, but these contacts have more attributes, such as date and number. I made another screen for when the person clicks on the list, go on that other screen and show all the details of such contact. I did such coding. (I am using SQLite to save / use the 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 as such. Please help with such a code, thanks already!

EDITED

DBHelper class :

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);
    
asked by anonymous 07.07.2016 / 20:42

1 answer

1

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

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

So let's implement.

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

Do not forget to create the Layout file

    
08.07.2016 / 15:16