Updating MainActivity Items

1

I'm studying an application that has the same functionality as a contacts calendar. The application is divided into two tabs, one tab to add the user and another tab to list the users that have been added. After adding a user, his information (phone, address, email, image) still remains in MainActivity . In código there is only one control to not let the same user add twice.

I would like help updating by "clearing" the value of each item from MainActivity every time a user is entered and saved to the database.

Thank you.

MainActivity

public class MainActivity extends AppCompatActivity {

EditText nomeEtxt, telefoneEtxt, enderecoEtxt, emailEtxt;
ImageView contactImageImgView;
List<Contato> Contatos = new ArrayList<Contato>();
ListView contactListView;
Uri imageUri = Uri.parse("android.resource://luizugliano.com.br.agendaapp/drawable/ic_user.png");
DatabaseHandler dbHandler;

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

    nomeEtxt = (EditText) findViewById(R.id.EtxtNome);
    telefoneEtxt = (EditText) findViewById(R.id.EtxtTelefone);
    enderecoEtxt = (EditText) findViewById(R.id.EtxtEndereco);
    emailEtxt = (EditText) findViewById(R.id.EtxtEmail);
    contactListView = (ListView) findViewById(R.id.listView);
    contactImageImgView = (ImageView) findViewById(R.id.imgViewContactImage);
    dbHandler = new DatabaseHandler(getApplicationContext());

    TabHost tabHost = (TabHost) findViewById(R.id.tabHost);

    tabHost.setup();

    TabHost.TabSpec tabSpec = tabHost.newTabSpec("Adicionar");
    tabSpec.setContent(R.id.tabCreator);
    tabSpec.setIndicator("Adicionar");
    tabHost.addTab(tabSpec);

    tabSpec = tabHost.newTabSpec("Agenda");
    tabSpec.setContent(R.id.tabContactList);
    tabSpec.setIndicator("Agenda");
    tabHost.addTab(tabSpec);

    final Button addBtn = (Button) findViewById(R.id.btnAdd);
    addBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Contato contato = new Contato(dbHandler.getContactsCount(), String.valueOf(nomeEtxt.getText()), String.valueOf(telefoneEtxt.getText()), String.valueOf(enderecoEtxt.getText()), String.valueOf(emailEtxt.getText()), imageUri);
            if (!contactExists(contato)) {
                dbHandler.createContact(contato);
                Contatos.add(contato);
                Toast.makeText(getApplicationContext(), String.valueOf(nomeEtxt.getText()) + " foi adicionado com sucesso aos contatos", Toast.LENGTH_SHORT).show();
                return;
            }
            Toast.makeText(getApplicationContext(), String.valueOf(nomeEtxt.getText()) + " já existe. Por favor, adicione um nome diferente", Toast.LENGTH_SHORT).show();
        }
    });

    nomeEtxt.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
            addBtn.setEnabled(String.valueOf(nomeEtxt.getText()).trim().length() > 0);
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });

    contactImageImgView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
        }

    });

    if (dbHandler.getContactsCount() != 0)
        Contatos.addAll(dbHandler.getAllContacts());

    populateList();
}

private boolean contactExists(Contato contato) {
    String name = contato.getName();
    int contactCount = Contatos.size();

    for (int i = 0; i < contactCount; i++) {
        if (name.compareToIgnoreCase(Contatos.get(i).getName()) == 0)
            return true;
    }
    return false;
}

public void onActivityResult(int reqCode, int resCode, Intent data) {
    if (resCode == RESULT_OK) {
        if (reqCode == 1) {
            imageUri = data.getData();
            contactImageImgView.setImageURI(data.getData());
        }
    }
}

private void populateList() {
    ArrayAdapter<Contato> adapter = new ContactListAdapter();
    contactListView.setAdapter(adapter);
}

private class ContactListAdapter extends ArrayAdapter<Contato> {
    public ContactListAdapter() {
        super (MainActivity.this, R.layout.lista_contatos, Contatos);
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        if (view == null)
            view = getLayoutInflater().inflate(R.layout.lista_contatos, parent, false);

        Contato currentContact = Contatos.get(position);

        TextView nome = (TextView) view.findViewById(R.id.nomeContato);
        nome.setText(currentContact.getName());
        TextView telefone = (TextView) view.findViewById(R.id.telefoneContato);
        telefone.setText(currentContact.getPhone());
        TextView endereco = (TextView) view.findViewById(R.id.enderecoContato);
        endereco.setText(currentContact.getAddress());
        TextView email = (TextView) view.findViewById(R.id.emailContato);
        email.setText(currentContact.getEmail());
        ImageView ivContactImage = (ImageView) view.findViewById(R.id.ivContactImage);
        ivContactImage.setImageURI(currentContact.getImageURI());

        return view;
    }
}

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

DatabaseHandler class

/**
* Created by luizugliano on 28/10/15.
*/
public class DatabaseHandler extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;

private static final String DATABASE_NAME = "controleAgenda",
        TABLE_CONTACTS = "contatos",
        KEY_ID = "id",
        KEY_NAME = "nome",
        KEY_PHONE = "telefone",
        KEY_ADDRESS = "endereco",
        KEY_EMAIL = "email",
        KEY_IMAGEURI = "imageUri";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT," + KEY_PHONE + " TEXT," + KEY_ADDRESS + " TEXT," + KEY_EMAIL + " TEXT," + KEY_IMAGEURI + " TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

    onCreate(db);
}

public void createContact(Contato contato) {
    SQLiteDatabase db = getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(KEY_NAME, contato.getName());
    values.put(KEY_PHONE, contato.getPhone());
    values.put(KEY_EMAIL, contato.getEmail());
    values.put(KEY_ADDRESS, contato.getAddress());
    values.put(KEY_IMAGEURI, contato.getImageURI().toString());

    db.insert(TABLE_CONTACTS, null, values);
    db.close();
}

public int getContactsCount() {
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);
    int count = cursor.getCount();
    db.close();
    cursor.close();

    return count;
}

public List<Contato> getAllContacts() {
    List<Contato> contacts = new ArrayList<Contato>();

    SQLiteDatabase db = getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);

    if (cursor.moveToFirst()) {
        do {
            contacts.add(new Contato(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), Uri.parse(cursor.getString(5))));
        }
        while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return contacts;
}
}

Contact class

/**
* Created by luizugliano on 28/10/15.
*/
public class Contato {

private String _nome, _telefone, _endereco, _email;
private Uri _imageURI;
private int _id;

public Contato (int id, String nome, String telefone, String endereco, String email, Uri imageURI) {
    _id = id;
    _nome = nome;
    _telefone = telefone;
    _endereco = endereco;
    _email = email;
    _imageURI = imageURI;
}

public int getId() { return _id; }

public String getName() {
    return _nome;
}

public String getPhone() {
    return _telefone;
}

public String getAddress() {
    return _endereco;
}

public String getEmail() {
    return _email;
}

public Uri getImageURI() { return _imageURI; }
}
    
asked by anonymous 29.10.2015 / 14:21

1 answer

2

You can restart Activity after entering the data.

Intent intent = getIntent();
finish();
startActivity(intent);
    
19.11.2015 / 14:25