loop through Arraylist and add contact to arraylist - android

I am trying to loop through an ArrayList and add the record to array list if data doesn't already exist. if the data already exists it will just print out a message saying data already exist. However, I keep getting the error
Caused by: java.lang.ClassCastException: android.text.SpannableStringBuilder cannot be cast to com.application.Contact
I have added my post and included the contact class below
private ArrayList<Contact> contacts = new ArrayList<Contact>();
private ArrayAdapter<Contact> adapter;
private ListView contactListView;
public void saveContact(View view) {
EditText nameField = (EditText) findViewById(R.id.name);
Contact name = (Contact) nameField.getText();
EditText emailField=(EditText) findViewById(R.id.email);
Contact email = (Contact) emailField.getText();
EditText phoneField=(EditText) findViewById(R.id.mobile);
Contact phone= (Contact) phoneField.getText();
// Setup Adapter
contactListView = (ListView) findViewById(R.id.contactsListView);
adapter = new ArrayAdapter<Contact>(this,android.R.layout.simple_list_item_1, contacts);
contactListView.setAdapter(adapter);
for(int i=0;i<contacts.size();i++){
if(contacts.get(i).name.equals(name)){
Toast.makeText(this,"user exist",Toast.LENGTH_SHORT).show();
}else {
contacts.add(name);
contacts.add(email);
contacts.add(phone);
}
}
}
public class Contact {
public String name;
public String email;
public String mobile;
public Contact(String name, String email, String mobile) {
this.name = name;
this.email = email;
this.mobile = mobile;
}
public String toString() {
return name;
}
}

EditText nameField = (EditText) findViewById(R.id.name);
Contact name = (Contact) nameField.getText();
function getText returns Editable and you are trying to cast it to Contact. This is wrong. If you post your Contact class code than maybe we can figure out how to fix it. But for now I only can say that you are doing something wrong
EDIT
private ArrayList<Contact> contacts = new ArrayList<Contact>();
private ArrayAdapter<Contact> adapter;
private ListView contactListView;
public void saveContact(View view) {
EditText nameField = (EditText) findViewById(R.id.name);
String name = nameField.getText().toString();
EditText emailField=(EditText) findViewById(R.id.email);
String email = emailField.getText().toString();
EditText phoneField=(EditText) findViewById(R.id.mobile);
String mobile = phoneField.getText().toString());
// Setup Adapter
contactListView = (ListView) findViewById(R.id.contactsListView);
adapter = new ArrayAdapter<Contact>(this,android.R.layout.simple_list_item_1, contacts);
contactListView.setAdapter(adapter);
boolean contactExist = false;
for(int i=0;i<contacts.size();i++){
if(contacts.get(i).name.equals(name)){
contactExist = true;
break;
}
}
if (!contactExist) {
contacts.add(new Contact(name, email, mobile));
}
}

You are casting SpananbleStringBuilder to Contact class, exactly as your error says
Try this
EditText nameField = (EditText) findViewById(R.id.name);
String name = nameField.getText().toString();
EditText emailField=(EditText) findViewById(R.id.email);
String email = emailField.getText().toString();
EditText phoneField=(EditText) findViewById(R.id.mobile);
String phone= phoneField.getText().toString();

Try this code. I think you will get what you needed perfectly.
private ArrayList<Contact> contacts = new ArrayList<Contact>();
private ArrayAdapter<Contact> adapter;
private ListView contactListView;
public void saveContact(View view) {
EditText nameField = (EditText) findViewById(R.id.name);
//initialize a objects of contact class
Contact contactObj = new Contact();
contactObj.setName(nameField.getText().toString());
EditText emailField=(EditText) findViewById(R.id.email);
contactObj.setEmail(emailField.getText().toString());
EditText phoneField=(EditText) findViewById(R.id.mobile);
contactObj.setPhone(phoneField.getText().toString());
// Setup Adapter
contactListView = (ListView) findViewById(R.id.contactsListView);
adapter = new ArrayAdapter<Contact>(this,android.R.layout.simple_list_item_1, contacts);
contactListView.setAdapter(adapter);
for(int i=0;i<contacts.size();i++){
if(contacts.get(i).name.equals(contactObj.getName())){
Toast.makeText(this,"user exist",Toast.LENGTH_SHORT).show();
}else {
contacts.add(contactObj);
}
}
}

Firstly you are trying to parse an edittext to your model class (Contact), You will have to get the values from edittext and create an object of Contact class, then add it into the list. And make sure to use iterator to add while looping the array list
example here

Try this code.
Contact contact= new Contact();
EditText nameField = (EditText) findViewById(R.id.name);
contact.name=nameField.getText().toString;
contacts.add(contact);
This problem is due to casting. You are trying to cast a string directly to a Class object. Fetch String using editText.getText.toString.
I hope this will help you.

Related

Android Studio get data from sqlite

I had some problem about get data from sqlite different database.One database that save user's name and phone and they can update as they like. While another is house information but also contain user's name and phone.
My problem is i just realize that the phone that had been update in user database is not same with phone that previous store in house database. So i wanna call the user's phone from user database and use for phone call function and message function. But it does not work.And i trying to match the fullname that in user database with house database to call the phone data but still cant.
here is my call and message function
public class HouseDetail extends AppCompatActivity {
EditText etAddress,etDetail,etPhone;
TextView txType,txProperty,txPrice,txState,txTitle,txOther,txSize,txFullname;
ImageButton bPhone,bMessage;
String type,property,price,state,address,title,other,size,detail,fullnames,fullname,phone;
HousesDB db = new HousesDB(this);
Houses houses;
DatabaseOperations Udb = new DatabaseOperations(this);
PersonalData profileInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_house_detail);
txType = (TextView) findViewById(R.id.txTypes);
txProperty = (TextView) findViewById(R.id.txProperty);
txPrice = (TextView) findViewById(R.id.txPrice);
txState = (TextView) findViewById(R.id.txState);
etAddress = (EditText) findViewById(R.id.etAddress);
txTitle = (TextView) findViewById(R.id.txTitle);
txOther = (TextView) findViewById(R.id.txOther);
txSize = (TextView) findViewById(R.id.txSize);
txFullname = (TextView) findViewById(R.id.txFullname);
etPhone = (EditText) findViewById(R.id.etPhone);
etDetail = (EditText) findViewById(R.id.etDetail);
bPhone = (ImageButton) findViewById(R.id.bPhone);
bMessage = (ImageButton) findViewById(R.id.bMessage);
fullnames = txFullname.getText().toString();
type = txType.getText().toString();
property = txProperty.getText().toString();
price = txPrice.getText().toString();
state = txState.getText().toString();
address = etAddress.getText().toString();
title = txTitle.getText().toString();
other = txOther.getText().toString();
size = txSize.getText().toString();
detail = etDetail.getText().toString();
phone = etPhone.getText().toString();
Intent i = getIntent();
property = i.getStringExtra("house_property");
txProperty.setText(property);
houses = db.getInfo(property);
txType.setText(houses.getTypes());
txFullname.setText(houses.getFullname());
txPrice.setText(houses.getPrice());
txState.setText(houses.getState());
etAddress.setText(houses.getAddress());
txTitle.setText(houses.getTitle());
txOther.setText(houses.getOther());
txSize.setText(houses.getSize());
etDetail.setText(houses.getDetail());
this.fullnames = fullname;
profileInfo = Udb.getNumber(fullname);
etPhone.setText(profileInfo.get_phone());
bPhone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent callIntent =new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + etPhone));
startActivity(callIntent);
}
});
bMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("sms:" + etPhone)));
}
});
}
Here is my user database that get the phone number
public PersonalData getNumber(String fullname)
{
SQLiteDatabase SQ = this.getWritableDatabase();
String query = "select FullName,Phone from "+ Table_NAME;
Cursor CR = SQ.rawQuery(query,null);
String a;
PersonalData info = new PersonalData();
if (CR.moveToFirst())
{
do {
a = CR.getString(0);
if (a.equals(fullname)) {
info._phone = CR.getString(1);
break;
}
}while (CR.moveToNext());
}
return info;
}
try this:
public PersonalData getNumber(String fullName) {
SQLiteDatabase database = this.getReadableDatabase();
String table = "YOUR TABLE NAME";
String[] columns = {
"FullName" ,
"Phone"
};
Cursor cursor = database.query(table , columns , null , null , null , null , null);
cursor.moveToPosition(-1);
PersonalData info = new PersonalData();
while (cursor.moveToNext()) {
String name = cursor.getString(0);
if (name.equals(fullName)) {
info._phone = cursor.getString(1);
break;
}
}
cursor.close();
return info;
}
Replace
a = CR.getString(0);
if (a.equals(fullname)) {
info._phone = CR.getString(1);
break;
}
with
a = CR.getString(CR.getColumnIndex("Fullname"));
if (a.equals("FullName")) {
info._phone = CR.getString(CR.getColumnIndex("Phone"));
break;
}
your data gotten by query maybe not be ordered as you want,in your case that is, the result maybe not in "Fullname,Phone",so you should use getColumnIndex() to get data for each column.

How to display messages from a particular phone number in `ListView`?

I have to display SMS messages from a given number in ListView.
I have displayed messages from a number that i described in program.
Now i have to get number using EditText and display messages from that number.
My MainActivity.java is
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = (ListView) findViewById(R.id.listView);
List<String> msgList=getSMS();
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,msgList);
listView.setAdapter(adapter);
}
public List<String> getSMS(){
List<String>sms=new ArrayList<String>();
final String SMS_URI_INBOX="content://sms/inbox";
try {
Uri uri=Uri.parse(SMS_URI_INBOX);
String[] projection=new String[]{"_id","address","person","body","date","type"};
Cursor cursor=getContentResolver().query(uri,projection,"address='+918870346164'",null,null);
if (cursor.moveToFirst()){
int index_Address = cursor.getColumnIndex("address");
int index_Person = cursor.getColumnIndex("person");
int index_Body = cursor.getColumnIndex("body");
int index_Date = cursor.getColumnIndex("date");
int index_Type = cursor.getColumnIndex("type");
do {
String strAddress = cursor.getString(index_Address);
int intPerson = cursor.getInt(index_Person);
String strBody = cursor.getString(index_Body);
String longDate = cursor.getString(index_Date);
int intType = cursor.getInt(index_Type);
sms.add("\n"+strBody+"\n");
}while (cursor.moveToNext());
if (!cursor.isClosed()){
cursor.close();
cursor=null;
}
}
}catch (SQLiteException e){
Log.d("SQLiteException",e.getMessage());
}
return sms;
}
In this line i have defined the number i want to use
Cursor cursor=getContentResolver().query(uri,projection,"address='+918870346164'",null,null);
Here i have to get the number from user via TextView.
Please help
i think you need to get track with Android Training
But any way EditText getText()
EditText et = (EditText) findViewById(R.id.edit_text_id);
String address="address='"+et.getText().toString()+"'";
cursor=getContentResolver().query(uri,projection,address,null,null);

whats wrong in my code, showing "null pointer exception" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am new at android. I am trying to take data from user and toast to screen... but I am facing null pointer exception... i am trying from long time to solve ...plzzz help me
here is my code:
public class MainActivity extends ActionBarActivity {
private EditText etName;
private EditText etEmail;
private EditText etPhone;
private EditText etDesignation;
DatabaseHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.etName);
findViewById(R.id.etEmail);
findViewById(R.id.etPhone);
findViewById(R.id.etDesignation);
//dbHelper = new DatabaseHelper(this);
}
public void save(View v) {
String name = etName.getText().toString();
String email = etEmail.getText().toString();
String phone = etPhone.getText().toString();
String designation = etDesignation.getText().toString();
Employee employee = new Employee(name, email, phone, designation);
Toast.makeText(getApplicationContext(), employee.toString(),
Toast.LENGTH_LONG).show();
}
I suggest you to check the basics first
replace this part:
etName = (EditText) findViewById(R.id.etName);
etEmail = (EditText) findViewById(R.id.etEmail);
etPhone = (EditText) findViewById(R.id.etPhone);
etDesignation = (EditText) findViewById(R.id.etDesignation);
dbHelper = new DatabaseHelper(this);
None your your fields are initialized. Doing just a findViewById(R.id.etName); is not enough as global members will be holding null values giving NullPointerException. Hence assignment is important
private EditText etName; // default - null
private EditText etEmail; // default - null
private EditText etPhone; // default - null
private EditText etDesignation; // default - null
DatabaseHelper dbHelper; // default - null
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// changes here, link layout fields to objects
etName = (EditText) findViewById(R.id.etName);
etEmail = (EditText)findViewById(R.id.etEmail);
etPhone = (EditText)findViewById(R.id.etPhone);
etDesignation = (EditText)findViewById(R.id.etDesignation);
//dbHelper = new DatabaseHelper(this);
}
public void save(View v) {
String name = etName.getText().toString();
String email = etEmail.getText().toString();
String phone = etPhone.getText().toString();
String designation = etDesignation.getText().toString();
Employee employee = new Employee(name, email, phone, designation);
Toast.makeText(getApplicationContext(), employee.toString(),
Toast.LENGTH_LONG).show();
}
Try this
private EditText etName;
private EditText etEmail;
private EditText etPhone;
private EditText etDesignation;
DatabaseHelper dbHelper;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
etName = (EditText)findViewById(R.id.etName);
etEmail = (EditText) findViewById(R.id.etEmail);
etPhone = (EditText) findViewById(R.id.etPhone);
etDesignation = (EditText) findViewById(R.id.etDesignation);
//dbHelper = new DatabaseHelper(this);
}
public void save(View v) {
String name = etName.getText().toString();
String email = etEmail.getText().toString();
String phone = etPhone.getText().toString();
String designation = etDesignation.getText().toString();
Employee employee = new Employee(name, email, phone, designation);
Toast.makeText(context, employee.toString(),
Toast.LENGTH_LONG).show();
}
In onCreate
etName = (EditText)findViewById(R.id.etName);
etEmail = (EditText)findViewById(R.id.etEmail);
etPhone = (EditText)findViewById(R.id.etPhone);
etDesignation = (EditText)findViewById(R.id.etDesignation);
You forgot to initialize the views and you called getText() on null
It appears your fields are not being instantiated, this is usually the indication of a null pointer exception.Have you tried changing
findViewById(R.id.etName);
findViewById(R.id.etEmail);
findViewById(R.id.etPhone);
findViewById(R.id.etDesignation);
to
this.eName = (EditText)findViewById(R.id.etName);
this.etEmail = (EditText)findViewById(R.id.etEmail);
this.etPhone = (EditText)findViewById(R.id.etPhone);
this.etDesignation = (EditText)findViewById(R.id.etDesignation);
? Also are you certain that all if the R.id. are valid references?

How to store Multiline EditText into SQLiteDatabase? [ANDROID]

I'm working on an application where I've 2 Multiline EditText and I need to store them into database. i only know how to store the single line EditText.
Here is my codes for inserting into database:
btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//startActivityForResult(new Intent(Intent.ACTION_PICK),PICK_CONTACT);
likeDB.open();
long likes_id;
Spinner nameSpinner = (Spinner) findViewById(R.id.nameSpinner);
String NameValue = nameSpinner.getSelectedItem().toString();
EditText txtLikes = (EditText) findViewById(R.id.txtLikes);
String LikesValue = txtLikes.getText().toString();
likes_id = likeDB.insertLikes(NameValue, LikesValue);
likeDB.close();
dislikeDB.open();
long dislikes_id;
Spinner names = (Spinner) findViewById(R.id.nameSpinner);
String NamesValue = names.getSelectedItem().toString();
EditText txtDislikes = (EditText) findViewById(R.id.txtDislikes);
String DislikesValue = txtDislikes.getText().toString();
dislikes_id = dislikeDB.insertDislikes(NamesValue, DislikesValue);
Toast.makeText(getBaseContext(),
"Your information is saved successfully!", Toast.LENGTH_SHORT).show();
dislikeDB.close();
}
});
This the code where I've declared the LikeDBAdapter and DislikesDBAdapter above the onCreate() method:
LikesDBAdapter likeDB = new LikesDBAdapter(this);
DislikesDBAdapter dislikeDB = new DislikesDBAdapter(this);
I need help with this. Any help will be appreciated. Thanks!
=)
set a method on your dbHelper class and
use a ContentValues, e.g :
public boolean createNote(String VALUE_1 , String VALUE_2) {
ContentValues initValue = new ContentValues();
initValue.put(COLUMN_NAME_1 , VALUE_1);
initValue.put(COLUMN_NAME_2 , VALUE_2);
return mDb.insert(YOUR_TABLE_NAME , null, initValue) > 0;
}

Can't see data from db in my listview

I was trying to display my data dynamically in a listview. I first insert data into db then displaying them in listview. I don't understand why but I created db and listview, it doesn't show data when I try to display it.
I'm getting data from EditText fields but I insert and display the data in another activity. I first thought I coludn't get the data from first activity, but I'm sure that I wrote the right code.
The field for the data in listview always empty. I should create a new entry when I press a "Add" button. I can see that it creates a new row in the list with a new id but the rest is empty.
Why I don't see data there? This is how I get data and put inside db and list:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
String name = "";
String email = "";
String phone = "";
String address = "";
Bundle extras = getIntent().getExtras();
if (extras != null) {
name = extras.getString("name");
email = extras.getString("email");
phone = extras.getString("phone");
address = extras.getString("address");
}
listContent = (ListView)findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.queueAll();
String[] from = new String[]{SQLiteAdapter.KEY_ID, SQLiteAdapter.COLUMN_NAME, SQLiteAdapter.COLUMN_EMAIL,SQLiteAdapter.COLUMN_PHONE, SQLiteAdapter.COLUMN_ADDRESS};
int[] to = new int[]{R.id.id, R.id.text1, R.id.text2,R.id.text3, R.id.text4};
cursorAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
mySQLiteAdapter.insert(name,email,phone,address);
updateList();
}
This is my main activity
Button next = (Button) findViewById(R.id.add);
EditText nametext = (EditText) this.findViewById(R.id.NameText);
final String nt = nametext.getText().toString();
EditText emailtext = (EditText) this.findViewById(R.id.MailText);
final String et = emailtext.getText().toString();
EditText phonetext = (EditText) this.findViewById(R.id.PhoneText);
final String pt = phonetext.getText().toString();
EditText addresstext = (EditText) this.findViewById(R.id.AddressText);
final String at = addresstext.getText().toString();
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(getApplicationContext(), Activity2.class);
myIntent.putExtra("name",nt);
myIntent.putExtra("email",et);
myIntent.putExtra("phone",pt);
myIntent.putExtra("address",at);
startActivity(myIntent);
}
});
Here is my queueAll function:
public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, COLUMN_NAME,
COLUMN_EMAIL,COLUMN_PHONE,COLUMN_ADDRESS};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}

Categories

Resources