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?
Related
I have this to add elements on my real time database:
mEditTextTitulo = (EditText) findViewById(R.id.editTitulo);
mEditTextMensaje = (EditText) findViewById(R.id.editDescripcion);
mFecha = (EditText) findViewById(R.id.editFecha);
mDatabase = FirebaseDatabase.getInstance().getReference();
EnviarRTB = findViewById(R.id.btnEnviar);
EnviarRTB.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
String titulo = mEditTextTitulo.getText().toString();
String descripcion = mEditTextMensaje.getText().toString();
String fecha = mFecha.getText().toString();
mDatabase.child("Eventos").push().child("Publicacion").child("Titulo").setValue(titulo);
mDatabase.child("Eventos").push().child("Publicacion").child("DescripciĆ³n").setValue(descripcion);
mDatabase.child("Eventos").push().child("Publicacion").child("Fecha").setValue(fecha);
}
});
But this show my in the data base like this.
Must see like this
Just Generate key one time use it multiple times. You don't need to use push many time
EnviarRTB.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
String key = mDatabase.child("Eventos").push().getKey();
String titulo = mEditTextTitulo.getText().toString();
String descripcion = mEditTextMensaje.getText().toString();
String fecha = mFecha.getText().toString();
mDatabase.child("Eventos").child(key).child("Publicacion").child("Titulo").setValue(titulo);
mDatabase.child("Eventos").child(key).child("Publicacion").child("DescripciĆ³n").setValue(descripcion);
mDatabase.child("Eventos").child(key).child("Publicacion").child("Fecha").setValue(fecha);
}
});
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.
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.
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;
}
I am making an application to Store textfield values to database.After entering values when I press the button to submit it, it just hanged and give no response.
my onCreate code is given below:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final DBAdapter db = new DBAdapter(this);
//---add 2 titles---
db.open();
final long d_id ;
final EditText input1 = (EditText) findViewById(R.id.isbn);
final String isbn = input1.getText().toString();
final EditText input2 = (EditText) findViewById(R.id.titleText);
final String tText = input2.getText().toString();
final EditText input3 = (EditText) findViewById(R.id.publisherText);
final String pText = input3.getText().toString();
this.btn = (Button)this.findViewById(R.id.button1);
this.btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
db.insertTitle(isbn, tText, pText);
}
});
db.close();
}
}
isbn,titleText and publisherText are my id for Textfield.
insertTitle is function to insert the values.
Whats wrong with my code?
thanks.
You are reading the values of your text fields as the app is being created, not when the button is pushed. You will always enter the initial values of your EditTexts with your current code. Try this:
db.insertTitle(input1.getText().toString(), input2.getText().toString(), input3.getText().toString());
You will have to move where you close your database, otherwise you will get an error for attempting to access a closed database. Try putting it in onPause() or onDestroy().
If this isn't the solution please post your logcat errors so we don't have to guess what is happening.
try this
this.btn = (Button)this.findViewById(R.id.button1);
this.btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
final EditText input1 = (EditText) findViewById(R.id.isbn);
final String isbn = input1.getText().toString();
final EditText input2 = (EditText) findViewById(R.id.titleText);
final String tText = input2.getText().toString();
final EditText input3 = (EditText) findViewById(R.id.publisherText);
final String pText = input3.getText().toString();
db.insertTitle(isbn, tText, pText);
}
});
I think your problem is open() and close() they are in onclick method or about your insertTitle() method. Check your values and types.
ContentValues cv = new ContentValues();
cv.put(KEY_WORK_OUT, workout);
cv.put(KEY_NAME, name);
cv.put(KEY_REP,rep);
cv.put(KEY_WEIGHT, weight);
ourDataBase.insert(DATABASE_TABLE, null, cv);