Hello I'm starting at Android Development and I need to do a user registration in two tables at the same time.
I have the User table and I have Patient and Caregiver tables, in the Register Activity I have two radio buttons to check the user type. If "Patient" is selected then I want to insert into user and patient.
But, my radiogroup (i think) is always returning null. I have checked other posts and tried different solutions but neither of them worked.
So my RegisterActivity code:
public class RegisterActivity extends AppCompatActivity {
DatabaseHelper helper = new DatabaseHelper(this);
private AlphaAnimation buttonClick = new AlphaAnimation(0.0F, 0.8F);
//RadioButton rb1, rb2, rb3;
RadioGroup radiogroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
radiogroup = (RadioGroup) findViewById(R.id.radiogroup);
//rb1 = (RadioButton) findViewById(R.id.radioButton);
//rb2 = (RadioButton) findViewById(R.id.radioButton2);
}
//get selected radio button id (also returns null)
/* public int getIDRadio() {
int idRadio = radiogroup.getCheckedRadioButtonId();
if (idRadio == R.id.radioButton) {
return 1; //patient
} else if (idRadio == R.id.radioButton2) {
return 2; //caregiver
} else {
return -1; //erro não esta nenhum selecionado
}
}*/
//another try
public boolean radioGroup(){
int checkedID = radiogroup.getCheckedRadioButtonId(); //LINE 51
if(checkedID == R.id.radioButton) {
return true; //for patient
} else {
return false; //for caregiver
}
//return radiogroup.getCheckedRadioButtonId() == R.id.radioButton;
}
public void onRegisterClick(View v) {
if (v.getId() == R.id.REGISTARBUTTON) {
EditText name = (EditText) findViewById(R.id.TFNAME);
EditText email = (EditText) findViewById(R.id.TFEMAIL);
EditText uname = (EditText) findViewById(R.id.TFUNAME);
EditText password1 = (EditText) findViewById(R.id.TFPASSWORD1);
EditText password2 = (EditText) findViewById(R.id.TFPASSWORD2);
String namestr = name.getText().toString();
String emailstr = email.getText().toString();
String unamestr = uname.getText().toString();
String pass1str = password1.getText().toString();
String pass2str = password2.getText().toString();
if (namestr.isEmpty() || emailstr.isEmpty() || unamestr.isEmpty() || pass1str.isEmpty()) { //se os campos estiverem null
Toast fields = Toast.makeText(RegisterActivity.this, "Por favor, preencha os campos!", Toast.LENGTH_SHORT);
fields.show();
} else if (!pass1str.equals(pass2str)) { //se as passwords não forem iguais
Toast pass = Toast.makeText(RegisterActivity.this, "Password incorrecta, tente de novo!", Toast.LENGTH_SHORT);
pass.show();
/*} else if (getIDRadio() == -1) { //se nenhum radiobutton estiver selecionado
Toast userType = Toast.makeText(RegisterActivity.this, "Por favor, selecione um tipo de utilizador!", Toast.LENGTH_SHORT);
userType.show();*/
} else {
if (radioGroup()) {
//if patient radiobutton selected inserts into user and patient tables
UsersRegister userPatient = new UsersRegister();
userPatient.setName(namestr);
userPatient.setEmail(emailstr);
userPatient.setUname(unamestr);
userPatient.setPassword(pass1str); //pass1 ou pass2 e igual
Patient patient = new Patient();
patient.setName(namestr);
patient.setEmail(emailstr);
patient.setPassword(pass1str);
helper.insertUser(userPatient); //LINE 103
} else { //inserts into user and caregiver tables (...)
Now my RegisterActivity Layout:
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="left|bottom"
android:layout_marginBottom="90dp"
android:orientation="horizontal"
android:id="#+id/radiogroup">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Paciente"
android:id="#+id/radioButton"
android:checked="false"
android:layout_marginLeft="50dp"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cuidador"
android:id="#+id/radioButton2"
android:layout_marginLeft="50dp"/>
</RadioGroup>
Logcat
Process: com.example.dc.smoveen, PID: 25361
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3848)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18770)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3843)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18770)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.dc.smoveen.RegisterActivity.radioGroup(RegisterActivity.java:51)
at com.example.dc.smoveen.DatabaseHelper.insertUser(DatabaseHelper.java:108)
at com.example.dc.smoveen.RegisterActivity.onRegisterClick(RegisterActivity.java:103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3843)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18770)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
So since it always returns null giving the NullPointerException error I can't do the signup.
Can anyone help me discover what have I done wrong?
Related
I am creating an application using Android Studio and Genymotion as an emulator, in which i am entering the data in 3 EditTexts, when i click the button to store it in sqlite database then it is not working.. and this is what i see in LOGCAT
FATAL EXCEPTION: main
Process: com.example.aadeshmishra.com.sdk18, PID: 1551
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.aadeshmishra.com.sdk18.ThirdActitvity.addData(ThirdActitvity.java:64)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
The button will call a method named addData() which is in ThirdActivity.
here the code for ThirdActivity.java
public class ThirdActitvity extends AppCompatActivity {
EditText ed1,ed2,ed3;
Button B1;
UserDBHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
ed1 = (EditText)findViewById(R.id.E1);
ed2 = (EditText)findViewById(R.id.E2);
ed3 = (EditText)findViewById(R.id.E3);
B1 = (Button) findViewById(R.id.addB);
}
public void addData(View view)
{
String name = ed1.getText().toString();
String desc = ed2.getText().toString();
String contact = ed3.getText().toString();
Boolean r1 = mydb.insertDataClient(name,desc,contact);
if(r1 == true)
{
Toast.makeText(this,"Data inserted",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this,"Data not inserted",Toast.LENGTH_LONG).show();
}
}
}
Here the Code for activity_third.xml
<EditText
android:id="#+id/E1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/client"
android:textSize="20sp"
android:layout_marginEnd="20dp"/>
<EditText
android:id="#+id/E2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/destail"
android:textSize="20sp"
android:layout_alignEnd="#+id/E1" />
<EditText
android:id="#+id/E3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="#string/EN"
android:textSize="20sp"
android:layout_marginBottom="18dp"
android:layout_above="#+id/addB"
/>
<Button
android:id="#+id/addB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="49dp"
android:text="#string/add"
android:textSize="20sp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="addData"
/>
And at Last the UserDbHelper.java
public class UserDBHelper extends SQLiteOpenHelper {
// Database Details
private static final int DB_VER = 1;
private static final String DB_NAME = "DIARY_DB";
// Table Name
private static final String table_clientinfo = "Client_Info";
// columns
private static final String name = "Name";
private static final String desc = "Desc";
private static final String cont = "Contact";
// Create table -- ClientInfo
private String Create_ClientInfo = "Create table "+ table_clientinfo +"(" + id + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ name + " TEXT ," + desc + " TEXT,"
+ cont + " INTEGER)";
public UserDBHelper(Context context)
{
super(context,DB_NAME,null,DB_VER);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(Create_ClientInfo);
db.close();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
public Boolean insertDataClient(String Name, String Desc, String Contact)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues con = new ContentValues();
con.put(name,Name);
con.put(desc,Desc);
con.put(cont,Contact);
long r = db.insert(table_clientinfo,null,con);
db.close();
if(r == -1)
{
return false;
}
else
{
return true;
}
}}
Can anyone tell what's the problem..?
thanks in advance..!
You need to initialize mydb in onCreate (or before using it anywhere though oncreate executed only once so better to do it inside onCreate) as
UserDBHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
mydb = new UserDBHelper(this);
//^^^^^^^^^^^^^^^^^^^^^
ed1 = (EditText)findViewById(R.id.E1);
ed2 = (EditText)findViewById(R.id.E2);
ed3 = (EditText)findViewById(R.id.E3);
B1 = (Button) findViewById(R.id.addB);
}
I have a class login.java which i am running as main activity but when i run it the application suddenly stops and says following error. I have also pasted activity_login.xml and login.java. I am stuck here and can not understand what the issue is. Any suggestions please
Error
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.admin.funtube_mp4/com.example.admin.funtube_mp4.Login}: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2404)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5653)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:626)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:675)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:700)
at android.view.LayoutInflater.inflate(LayoutInflater.java:470)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:257)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at com.example.admin.funtube_mp4.Login.onCreate(Login.java:24)
at android.app.Activity.performCreate(Activity.java:5541)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2368)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5653)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at android.view.LayoutInflater.createView(LayoutInflater.java:600)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:675)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:700)
at android.view.LayoutInflater.inflate(LayoutInflater.java:470)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:257)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at com.example.admin.funtube_mp4.Login.onCreate(Login.java:24)
at android.app.Activity.performCreate(Activity.java:5541)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2368)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5653)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f0b0001 a=-1 r=0x7f0b0001}
at android.content.res.Resources.loadDrawable(Resources.java:3348)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.view.View.<init>(View.java:3715)
at android.view.ViewGroup.<init>(ViewGroup.java:480)
at android.widget.LinearLayout.<init>(LinearLayout.java:176)
at android.widget.LinearLayout.<init>(LinearLayout.java:172)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at android.view.LayoutInflater.createView(LayoutInflater.java:600)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:675)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:700)
at android.view.LayoutInflater.inflate(LayoutInflater.java:470)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:257)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at com.example.admin.funtube_mp4.Login.onCreate(Login.java:24)
at android.app.Activity.performCreate(Activity.java:5541)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2368)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5653)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/bg_login"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical"
android:paddingLeft="20dp"
android:paddingRight="20dp" >
<EditText
android:id="#+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#color/white"
android:hint="#string/hint_email"
android:inputType="textEmailAddress"
android:padding="10dp"
android:singleLine="true"
android:textColor="#color/input_login"
android:textColorHint="#color/input_login_hint" />
<EditText
android:id="#+id/password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#color/white"
android:hint="#string/hint_password"
android:inputType="textPassword"
android:padding="10dp"
android:singleLine="true"
android:textColor="#color/input_login"
android:textColorHint="#color/input_login_hint" />
<!-- Login Button -->
<Button
android:id="#+id/btnLogin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
android:background="#color/btn_login_bg"
android:text="#string/btn_login"
android:textColor="#color/btn_login" />
<!-- Link to Login Screen -->
<Button
android:id="#+id/btnLinkToRegisterScreen"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dip"
android:background="#null"
android:text="#string/btn_link_to_register"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="15dp" />
</LinearLayout>
</LinearLayout>
login.java
package com.example.admin.funtube_mp4;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends AppCompatActivity {
private FunTubeOperations FunTubeDBOperations;
private DatabaseWrapper db;
private SessionManager session;
public static String UserName;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final AlertDialog ad = new AlertDialog.Builder(this).create();
Button login = (Button) findViewById(R.id.btnLogin);
Button reg = (Button) findViewById(R.id.btnLinkToRegisterScreen);
FunTubeDBOperations = new FunTubeOperations(this);
FunTubeDBOperations.open();
db = new DatabaseWrapper(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(Login.this, Main.class);
// session.setname(UserName);
String n=session.getdata();
//session.pref.getString(USER_NAME,UserName);
intent.putExtra("name", n);
startActivity(intent);
finish();
}
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(Login.this, register.class);
startActivity(intent);
finish();
}
});
try {
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText email = (EditText) findViewById(R.id.email);
EditText password = (EditText) findViewById(R.id.password);
if (email != null && password !=null) {
String em=email.getText().toString();
String pwd=password.getText().toString();
UserName= FunTubeDBOperations.loginUsers(em, pwd);
if(UserName!=null)
{
session.setLogin(true);
session.setname(UserName);
Toast.makeText(getApplicationContext(), "Login successfully!!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Login.this, Main.class);
intent.putExtra("name", UserName);
startActivity(intent);
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Invalid information provided!! Check your credentials or Sign up account!!", Toast.LENGTH_LONG).show();
}
}
else {
Toast.makeText(getApplicationContext(), "Fill all the fields!!", Toast.LENGTH_LONG).show();
}
}
});
} catch (Exception er) {
ad.setMessage(er.toString());
}
}
}
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="bg_login">#26AE90</color>
<color name="bg_register">#2E3237</color>
<color name="bg_main">#428BCA</color>
<color name="white">#FFFFFF</color>
<color name="input_login">#222222</color>
<color name="input_login_hint">#999999</color>
<color name="input_register">#888888</color>
<color name="input_register_bg">#3B4148</color>
<color name="input_register_hint">#5E6266</color>
<color name="btn_login">#26AE90</color>
<color name="btn_login_bg">#ECEEF1</color>
<color name="lbl_name">#333333</color>
<color name="btn_logut_bg">#FF6861</color>
<color name="view_background">#E8ECfA</color>
<color name="btn_bg">#277BEC</color>
<color name="txt_font">#4E5572</color>
<color name="action_bar">#1F2649</color>
</resources>
I have a problem. I want to read value Integer of activity "Settings" in the service GPSTracker and use it there. I use this SharedPrefrences and confirming key input. If the data is validated that the application returns to class FullscreenActivity.
This is the code responsible for this in activity Settings:
SharedPreferences.Editor editor;
public static final String NAME = "DISTANCE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);
SharedPreferences pref = getApplicationContext().getSharedPreferences(NAME, MODE_PRIVATE);
editor=pref.edit();
Edit1= (EditText) findViewById(R.id.editSkan);
accept= (Button) findViewById(R.id.buttonSkan);
accept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (!Edit1.getText().toString().equals(""))
value = Integer.parseInt(Edit1.getText().toString());
editor.putInt("settings", value);
editor.commit();
Toast.makeText(getApplicationContext(), "Changed, value + " m", Toast.LENGTH_SHORT).show();
finish();
}
});
A code in GPSTracker like this:
SharedPreferences pref;
(...)
private int downloadSettings()
{
pref=context.getSharedPreferences("DISTANCE", Activity.MODE_PRIVATE);
value = pref.getInt("settings",15);
return value;
}
and a method call:
int dist = downloadSettings();
When I run the apps I get two errors in the log:
*java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.adam.mobileproject/com.example.adam.mobileproject.FullscreenActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.adam.mobileproject.GPSTracker.downloadSettings(GPSTracker.java:284)
at com.example.adam.mobileproject.GPSTracker.<init>(GPSTracker.java:200)
at com.example.adam.mobileproject.FullscreenActivity.onCreate(FullscreenActivity.java:40)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)*
PLEASE HELP!!!
The problem is definitely that context is null.
However, just like the Activity class, the Service class extends Context, so you should be able to replace context with this or getApplicationContext().
Try this:
private int downloadSettings()
{
pref = getApplicationContext().getSharedPreferences("DISTANCE", Activity.MODE_PRIVATE);
value = pref.getInt("settings",15);
return value;
}
At no time que instantiate my object EmailTask the error occurs.
public void send(View view){
EditText text = (EditText) findViewById(R.id.editText);
Switch iluminacao = (Switch) findViewById(R.id.switch1);
Switch wifi = (Switch) findViewById(R.id.switch2);
RatingBar mBar = (RatingBar) findViewById(R.id.ratingBar);
try {
EmailTask asyncTask = new EmailTask(text.getText().toString(), iluminacao.isChecked(), wifi.isChecked(), mBar.getNumStars());
asyncTask.execute();
}catch(Exception e){
e.printStackTrace();
}
}
My AsyncTask
package com.morais.daniela.conectasp;
import android.os.AsyncTask;
import android.os.Build;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
/**
* Created by daniela.morais on 24/03/15.
*/
public class EmailTask extends AsyncTask<Void, Void, Void> {
private String comments;
private boolean getIluminacao;
private boolean getWifi;
private float getStars;
private SimpleEmail email = new SimpleEmail();
/**
* Recebe feedbacks enviados pelo usuario e inicializa configuracoes do email
* #param comments
* #param getIluminacao
* #param getWifi
* #param getStars
*/
public EmailTask(String comments, boolean getIluminacao, boolean getWifi, float getStars) {
this.comments = comments;
this.getIluminacao = getIluminacao;
this.getWifi = getWifi;
this.getStars = getStars;
email.setSSLOnConnect(true);
email.setHostName("smtp.gmail.com");
email.setSslSmtpPort("465");
email.setAuthenticator(new DefaultAuthenticator("conectasaopaulo#gmail.com.br","senha"));
}
/**
* Encaminhar email
* #param params
* #return
*/
#Override
protected Void doInBackground(Void... params) {
String iluminacao = "Não.";
String wifi = "Não.";
if(getIluminacao==true){
iluminacao = "Sim.";
}
if(getWifi==true){
wifi = "Sim.";
}
try {
email.setFrom("conectasaopaulo#gmail.com.br");
email.setDebug(true);
email.setSubject("Feedback - ConectaSP");
email.setMsg("Houve problemas com a iluminação? " + iluminacao + "\n\n"
+ "Houve problemas com o wifi? " + wifi + "\n\n"
+ "Avaliação geral " + getStars + "\n\n"
+ "Comentários:\n" + comments + "\n\n"
+ "Informações gerais do aparelho\n" + Build.DEVICE + "\t" + Build.HARDWARE + "\t" + Build.MODEL);
email.addTo("dani.m#hotmail.co.uk");
email.send();
} catch (EmailException e) {
System.err.println("Erro ao enviar email.");
}
return null;
}
}
Error
03-24 16:10:13.790 7215-7215/com.morais.daniela.conectasp E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3103)
at android.view.View.performClick(View.java:3574)
at android.view.View$PerformClick.run(View.java:14293)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4448)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3098)
at android.view.View.performClick(View.java:3574)
at android.view.View$PerformClick.run(View.java:14293)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4448)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.VerifyError: com/morais/daniela/conectasp/EmailTask
at com.morais.daniela.conectasp.FeedbackActivity.send(FeedbackActivity.java:50)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3098)
at android.view.View.performClick(View.java:3574)
at android.view.View$PerformClick.run(View.java:14293)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4448)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
at dalvik.system.NativeStart.main(Native Method)
Looks like maybe you either require a permission you don't have, or you require a newer version of the OS to run on.
Please check FeedbackActivity and make sure you aren't using any SDK calls that won't run on the device with which you are testing.
The operation button is correct, it performs all previous lines. However, when instantiating an email object displays the error.
public void send(View view){
EditText text = (EditText) findViewById(R.id.editText);
Switch iluminacao = (Switch) findViewById(R.id.switch1);
Switch wifi = (Switch) findViewById(R.id.switch2);
RatingBar mBar = (RatingBar) findViewById(R.id.ratingBar);
System.out.println(text.getText().toString() + iluminacao.isChecked() +
wifi.isChecked() + mBar.getNumStars());
Email email = new Email();
email.sendEmail(text.getText().toString(), iluminacao.isChecked(),
wifi.isChecked(), mBar.getNumStars());
}
Email.Java
package com.morais.daniela.conectasp;
import android.os.Build;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
public class Email {
private SimpleEmail email = new SimpleEmail();
//FIXME
//Adicionar email correto para onde deverá ser enviado!
public Email() {
email.setSSLOnConnect(true);
email.setHostName("smtp.gmail.com");
email.setSslSmtpPort("465");
email.setAuthenticator(new DefaultAuthenticator("conectasaopaulo#gmail.com.br","senha"));
}
public void sendEmail(String comments, boolean getIluminacao, boolean getWifi, float getStars){
String iluminacao = "Não.";
String wifi = "Não.";
if(getIluminacao==true) {
iluminacao = "Sim.";
}
if(getWifi==true) {
wifi = "Sim.";
}
try {
email.setFrom("conectasaopaulo#gmail.com.br");
email.setDebug(true);
email.setSubject("Feedback - ConectaSP");
email.setMsg("Houve problemas com a iluminação? " + iluminacao + "\n\n"
+ "Houve problemas com o wifi? " + wifi + "\n\n"
+ "Avaliação geral " + getStars + "\n\n"
+ "Comentários:\n" + comments + "\n\n"
+ "Informações gerais do aparelho\n" + Build.DEVICE + "\t" + Build.HARDWARE + "\t" + Build.MODEL);
email.addTo("dani.m#hotmail.co.uk");
email.send();
} catch (EmailException e) {
System.err.println("Erro ao enviar email.");
}
}
}
Error
03-24 12:37:36.277 4037-4037/com.morais.daniela.conectasp E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3103)
at android.view.View.performClick(View.java:3574)
at android.view.View$PerformClick.run(View.java:14293)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4448)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3098)
at android.view.View.performClick(View.java:3574)
at android.view.View$PerformClick.run(View.java:14293)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4448)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.VerifyError: com/morais/daniela/conectasp/Email
at com.morais.daniela.conectasp.FeedbackActivity.send(FeedbackActivity.java:53)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3098)
at android.view.View.performClick(View.java:3574)
at android.view.View$PerformClick.run(View.java:14293)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4448)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
at dalvik.system.NativeStart.main(Native Method)
Please check below code:
private SimpleEmail email = new SimpleEmail();
//FIXME
//Adicionar email correto para onde deverá ser enviado!
public Email() {
if(email==null)
email = new SimpleEmail();
email.setSSLOnConnect(true);
email.setHostName("smtp.gmail.com");
email.setSslSmtpPort("465");
email.setAuthenticator(new DefaultAuthenticator("conectasaopaulo#gmail.com.br","senha"));
}
And also check permission in manifest file regarding email.