App crashes during Bluetooth discovery - java

What I'm trying to do
I'm trying to create an app that searches all the Bluetooth devices nearby and connects to the ones user wishes to connect to.
I'm trying to create a Connect button in one activity that starts the discovery function in another activity
How I'm trying to do it
So I have this MainActivity.java class / activity that has the Connect button. Upon clicking this button, it should do three things:
Check if the Bluetooth on my Smartphone is on & if it's not, turn it on.
Display a TOAST message to show whether BT has been successfully turned on or not
Start this new activity, called SearchBTDevice.java that looks for nearby BT devices & list them in a ListView
The first two are perfectly working since they're on MainActivity.java & that's where my button has been created.
Problem comes when it creates the new activity & tries to do the 3rd one. The app crashes.
This is what my MainActivity.java looks like
package vertex2016.mvjce.edu.bluealert;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import static java.lang.Thread.sleep;
public class MainActivity extends AppCompatActivity {
public BluetoothAdapter BA = BluetoothAdapter.getDefaultAdapter();
private int REQ_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void connect(View v)
{
if(BA == null)
Toast.makeText(MainActivity.this, "System Doesn't Support Bluetooth", Toast.LENGTH_SHORT).show();
else if(!BA.isEnabled())
{
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, REQ_CODE);
}
else {
Toast.makeText(MainActivity.this, "ALREADY ON!!", Toast.LENGTH_SHORT).show();
searchBTDevices();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode!=RESULT_CANCELED) {
Toast.makeText(MainActivity.this, "TURNED ON!", Toast.LENGTH_SHORT).show();
searchBTDevices();
}
else
Toast.makeText(MainActivity.this,"FAILED TO ENABLE BLUETOOTH", Toast.LENGTH_LONG).show();
}
public void searchBTDevices()
{
Thread searchThread = new Thread() {
#Override
public void run() {
Intent searchBT = new Intent(getApplicationContext(), SearchBTDevice.class);
startActivity(searchBT);
}
};
searchThread.start();
}
}
This is what my SearchBTDevice.java looks like
package vertex2016.mvjce.edu.bluealert;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattDescriptor;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.bluetooth.BluetoothAdapter;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.Set;
public class SearchBTDevice extends AppCompatActivity {
public BluetoothAdapter BlueAdapter = BluetoothAdapter.getDefaultAdapter();
public ArrayAdapter PairedArrayAdapter, BTArrayAdapter;
public IntentFilter filter = new IntentFilter();
public ListView devicesFound;
public Set<BluetoothDevice> pairedDevices;
private final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice btd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BTArrayAdapter.add(btd.getName() + "\t\t" + btd.getAddress() + "\n");
PairedArrayAdapter.add(btd.getName() + "\t\t" + btd.getAddress() + "\n");
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_btdevice);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if(!BTArrayAdapter.isEmpty())
BTArrayAdapter.clear();
searchBTDevices();
}
public void searchBTDevices()
{
pairedDevices = BlueAdapter.getBondedDevices();
if(pairedDevices.size()>0)
for(BluetoothDevice device: pairedDevices)
PairedArrayAdapter.add(device.getName() + "\t\t" + device.getAddress() + "\n");
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice btd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BTArrayAdapter.add(btd.getName() + "\t\t" + btd.getAddress() + "\n");
PairedArrayAdapter.add(btd.getName() + "\t\t" + btd.getAddress() + "\n");
}
}
};
BlueAdapter.startDiscovery();
devicesFound = (ListView)findViewById(R.id.searchpagelistView);
devicesFound.setAdapter(BTArrayAdapter);
}
}
This is what the logcat shows when my app crashes
03-17 11:51:40.120 19178-19178/vertex2016.mvjce.edu.bluealert E/AndroidRuntime: FATAL EXCEPTION: main
Process: vertex2016.mvjce.edu.bluealert, PID: 19178
java.lang.RuntimeException: Unable to start activity ComponentInfo{vertex2016.mvjce.edu.bluealert/vertex2016.mvjce.edu.bluealert.SearchBTDevice}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.ArrayAdapter.isEmpty()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.ArrayAdapter.isEmpty()' on a null object reference
at vertex2016.mvjce.edu.bluealert.SearchBTDevice.onCreate(SearchBTDevice.java:57)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420) 
at android.app.ActivityThread.access$900(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5292) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 
So these are my questions:
Where am I going wrong & what should I do?
Is there any way I can retrieve the BluetoothAdapter, which was created in my MainActivity.java, in my new activity called SearchBTDevice.java?
Is there anyway I can set the onClick operation of a button defined in one activity from another activity?
Thank you for your time!

Define your BTArrayAdapter object in SearchBTDevice class. It is null while you call BTArrayAdapter.isEmpty() in onCreate().

Related

How can I redirect 2 buttons to different intents in android?

enter image description here
I put a listener on each button that takes me to different activities.
The login button works perfectly, but the register button stops the app when I click on it.
I've tried to put a Toast message in the _btnreg listener, and it worked...
I got this error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.virtualshelter, PID: 24128
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.virtualshelter/com.example.android.virtualshelter.register}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2787)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1504)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6247)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.android.virtualshelter.register.onCreate(register.java:35)
at android.app.Activity.performCreate(Activity.java:6754)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2787) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1504) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6247) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762) 
package com.example.android.virtualshelter;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity
{
Button _btnreg, _btnlogin;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_btnlogin = findViewById(R.id.btnlogin);
_btnreg = findViewById(R.id.btnreg);
_btnreg.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,register.class);
startActivity(intent);
}
});
_btnlogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,login.class);
startActivity(intent);
}
});
}
}
My register.java code
package com.example.android.virtualshelter;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class register extends AppCompatActivity
{
SQLiteOpenHelper openHelper;
SQLiteDatabase db;
Button _btnReg;
EditText _txtfname, _txtlname, _txtpass, _txtemail, _txtphone;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
openHelper = new DatabaseHelper(register.this);
_txtfname = findViewById(R.id.txtfname);
_txtlname = findViewById(R.id.txtlname);
_txtpass = findViewById(R.id.txtpass);
_txtemail = findViewById(R.id.txtemail);
_txtphone = findViewById(R.id.txtphone);
_btnReg = findViewById(R.id.btnreg);
_btnReg.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
db = openHelper.getWritableDatabase();
String fname = _txtfname.getText().toString();
String lname = _txtlname.getText().toString();
String pass = _txtpass.getText().toString();
String email = _txtemail.getText().toString();
String phone = _txtphone.getText().toString();
insertdata(fname, lname, pass, email, phone);
Toast.makeText(getApplicationContext(), "register successfully", Toast.LENGTH_LONG).show();
}
});
}
public void insertdata(String fname, String lname, String pass, String email, String phone)
{
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.COL_2, fname);
contentValues.put(DatabaseHelper.COL_3, lname);
contentValues.put(DatabaseHelper.COL_4, pass);
contentValues.put(DatabaseHelper.COL_5, email);
contentValues.put(DatabaseHelper.COL_6, phone);
long id = db.insert(DatabaseHelper.TABLE_NAME, null, contentValues);
}
}
I expect to go to activity register.java, but the app is crashing
My hunch is, you are not able find the button, causing a NPE when setting the listner. Could be that you don't have the button defined in R.layout.activity_main, but in a different layout.

Why is my TabLayout giving me a NullPointerException, and how do I fix it? [duplicate]

When my SplashActivity opens the LoginActivity my app crashes.
The following is my SplashActivity.java:
package com.example.android.appName;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import java.util.Timer;
import java.util.TimerTask;
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}, 1500);
}
}
and my LoginActivity.java:
package com.example.android.appName;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
public class LoginActivity extends AppCompatActivity {
private EditText usernameField = (EditText)findViewById(R.id.username),
passwordField = (EditText)findViewById(R.id.password);
private TextView error = (TextView)findViewById(R.id.error);
private ProgressBar progress = (ProgressBar)findViewById(R.id.progress);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.login_menu, menu);
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (android.os.Build.VERSION.SDK_INT > 5
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
onBackPressed();
return true;
}
return super.onKeyDown(keyCode, event);
}
public void exit(MenuItem item) {
finish();
}
public void signIn(View view) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
Part of AndroidManifest.xml:
<activity android:name=".SplashActivity"
android:theme="#style/NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".LoginActivity"
android:label="#string/title_activity_login" />
Error in logcat:
04-16 23:24:16.124 4015-4015/com.example.android.appName E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.appName, PID: 4015
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.appName/com.example.android.appName.LoginActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2993)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3248)
at android.app.ActivityThread.access$1000(ActivityThread.java:197)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1681)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6872)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:68)
at android.support.v7.app.AppCompatDelegateImplV7.<init>(AppCompatDelegateImplV7.java:145)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:28)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:42)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:186)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:168)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:508)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:180)
at com.example.android.appName.LoginActivity.<init>(LoginActivity.java:20)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1690)
at android.app.Instrumentation.newActivity(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2983)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3248) 
at android.app.ActivityThread.access$1000(ActivityThread.java:197) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1681) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:6872) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
An Activity is not fully initialized and ready to look up views until after setContentView(...) is called in onCreate().
Only declare the fields like the following:
private EditText usernameField, passwordField;
private TextView error;
private ProgressBar progress;
and then assign the values in onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
usernameField = (EditText)findViewById(R.id.username);
passwordField = (EditText)findViewById(R.id.password);
error = (TextView)findViewById(R.id.error);
progress = (ProgressBar)findViewById(R.id.progress);
}
Might not be part of the problem but as an extra bit of advice a Timer runs the TimerTask on a background thread and that should be avoided in this case. Replace the Timer with a Handler instead to run it on the UI thread.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}, 1500);
Views defined in xml file can only be accessed in java code, after setting the ContentView as the required xml file using:
setContentView(R.layout.xml_file_name);
So 1st call above method inside onCreate method and then initialize the View instances inside onCreate or inside the methods in which the instance will be used.

E/SQLiteLog: (1) near "ENTER": syntax error

I'm getting this weird error while trying to create a database. I'm building an expense manager app and want to store the data from textview into SQLite database but I'm getting these errors when I press the save button. IS This because I'm trying to create database in another activity rather than the MainActivity??
07-20 01:49:31.032 28795-28795/com.example.alkesh.expensemanager101 E/SQLiteLog: (1) near "ENTER": syntax error
07-20 01:49:31.032 28795-28795/com.example.alkesh.expensemanager101 D/AndroidRuntime: Shutting down VM
--------- beginning of crash
07-20 01:49:31.042 28795-28795/com.example.alkesh.expensemanager101 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.alkesh.expensemanager101, PID: 28795
Theme: themes:{default=overlay:com.baranovgroup.nstyle, iconPack:com.baranovgroup.nstyle, fontPkg:com.baranovgroup.nstyle, com.android.systemui=overlay:com.baranovgroup.nstyle, com.android.systemui.navbar=overlay:com.baranovgroup.nstyle}
android.database.sqlite.SQLiteException: near "ENTER": syntax error (code 1): , while compiling: ENTER INTO money (name) VALUES ('25');
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at com.example.alkesh.expensemanager101.AddMoney.insertIntoDatabase(AddMoney.java:95)
at com.example.alkesh.expensemanager101.AddMoney.onClick(AddMoney.java:63)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21158)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
Here's my code for the AddMoney Activity
package com.example.alkesh.expensemanager101;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddMoney extends AppCompatActivity implements View.OnClickListener{
Button Save,Cancel;
EditText expText;
int[] expense=new int[100];
int temp=900;
int c=0;
int sum=0;
String DBOnce;
private SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_money);
expText=(EditText)findViewById(R.id.expense);
Cancel=(Button)findViewById(R.id.cancelbutton);
Cancel.setOnClickListener(this);
Save = (Button)findViewById(R.id.savebutton);
Save.setOnClickListener(this);
CreateDatabase();
}
#Override
public void onClick(View view) {
if(view== Save){
insertIntoDatabase();
}
if(view==Cancel){
Intent intent =new Intent(AddMoney.this,MainActivity.class);
startActivity(intent);
finish();
}
}
protected void CreateDatabase(){
db=openOrCreateDatabase("MoneyDB", Context.MODE_PRIVATE,null);
db.execSQL("CREATE TABLE IF NOT EXISTS money(ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR);");
}
protected void insertIntoDatabase(){
String amount = expText.getText().toString().trim();
if(amount.equals("")){
Toast.makeText(this,"Please enter your expense or press Cancel to go back",Toast.LENGTH_LONG).show();
return;
}
String query="ENTER INTO money (name) VALUES ('"+amount+"');";
db.execSQL(query);
Toast.makeText(this,"Expense Saved",Toast.LENGTH_LONG).show();
}
}
Here's my code for MainActivity.
package com.example.alkesh.expensemanager101;
import android.content.Intent;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button Add;
TextView expense;
int c=0;
String DBonce="0";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Add = (Button) findViewById(R.id.addbutton);
Add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddMoney.class);
intent.putExtra("counter", DBonce);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menuhome,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.feedback:{}
break;
case R.id.exit: finish();
break;
}
return super.onOptionsItemSelected(item);
}
}
In AddMoney Activity function insertIntoDatabase() change your query Enter to INSERT

Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference

When my SplashActivity opens the LoginActivity my app crashes.
The following is my SplashActivity.java:
package com.example.android.appName;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import java.util.Timer;
import java.util.TimerTask;
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}, 1500);
}
}
and my LoginActivity.java:
package com.example.android.appName;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
public class LoginActivity extends AppCompatActivity {
private EditText usernameField = (EditText)findViewById(R.id.username),
passwordField = (EditText)findViewById(R.id.password);
private TextView error = (TextView)findViewById(R.id.error);
private ProgressBar progress = (ProgressBar)findViewById(R.id.progress);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.login_menu, menu);
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (android.os.Build.VERSION.SDK_INT > 5
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
onBackPressed();
return true;
}
return super.onKeyDown(keyCode, event);
}
public void exit(MenuItem item) {
finish();
}
public void signIn(View view) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
Part of AndroidManifest.xml:
<activity android:name=".SplashActivity"
android:theme="#style/NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".LoginActivity"
android:label="#string/title_activity_login" />
Error in logcat:
04-16 23:24:16.124 4015-4015/com.example.android.appName E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.appName, PID: 4015
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.appName/com.example.android.appName.LoginActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2993)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3248)
at android.app.ActivityThread.access$1000(ActivityThread.java:197)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1681)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6872)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:68)
at android.support.v7.app.AppCompatDelegateImplV7.<init>(AppCompatDelegateImplV7.java:145)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:28)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:42)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:186)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:168)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:508)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:180)
at com.example.android.appName.LoginActivity.<init>(LoginActivity.java:20)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1690)
at android.app.Instrumentation.newActivity(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2983)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3248) 
at android.app.ActivityThread.access$1000(ActivityThread.java:197) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1681) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:6872) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
An Activity is not fully initialized and ready to look up views until after setContentView(...) is called in onCreate().
Only declare the fields like the following:
private EditText usernameField, passwordField;
private TextView error;
private ProgressBar progress;
and then assign the values in onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
usernameField = (EditText)findViewById(R.id.username);
passwordField = (EditText)findViewById(R.id.password);
error = (TextView)findViewById(R.id.error);
progress = (ProgressBar)findViewById(R.id.progress);
}
Might not be part of the problem but as an extra bit of advice a Timer runs the TimerTask on a background thread and that should be avoided in this case. Replace the Timer with a Handler instead to run it on the UI thread.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}, 1500);
Views defined in xml file can only be accessed in java code, after setting the ContentView as the required xml file using:
setContentView(R.layout.xml_file_name);
So 1st call above method inside onCreate method and then initialize the View instances inside onCreate or inside the methods in which the instance will be used.

Error receiving broadcast intent using BatteryManager

I am getting Error in receiving broadcast intent i am using BatteryManager for it. I have no clue why I am getting this error.
Someone please help.
thanks in advance
Let me know if you need more code.
Here is the error:
> Error receiving broadcast Intent {
> act=android.intent.action.BATTERY_CHANGED flg=0x60000010 (has extras)
> } in com.example.android.login.MainActivity$1#260e12dc
> at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:933)
> at android.os.Handler.handleCallback(Handler.java:739)
> at android.os.Handler.dispatchMessage(Handler.java:95)
> at android.os.Looper.loop(Looper.java:145)
> at android.app.ActivityThread.main(ActivityThread.java:5972)
> at java.lang.reflect.Method.invoke(Native Method)
> at java.lang.reflect.Method.invoke(Method.java:372)
> at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
> at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
> Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
> android.widget.TextView.setText(java.lang.CharSequence)' on a null
> object reference
> at com.example.android.login.MainActivity$1.onReceive(MainActivity.java:37)
> at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:923)
>             at android.os.Handler.handleCallback(Handler.java:739)
>             at android.os.Handler.dispatchMessage(Handler.java:95)
>             at android.os.Looper.loop(Looper.java:145)
>             at android.app.ActivityThread.main(ActivityThread.java:5972)
>             at java.lang.reflect.Method.invoke(Native Method)
>             at java.lang.reflect.Method.invoke(Method.java:372)
Activity Class
package com.example.android.login;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.BatteryManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.LogOutCallback;
import com.parse.Parse;
import com.parse.ParseObject;
import com.parse.ParseUser;
import com.parse.ParseException;
public class MainActivity extends ActionBarActivity {
private TextView batteryTxt;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context ctxt, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
batteryTxt.setText(String.valueOf(level) + "%");
}
};
private Toolbar toolbar;
public Button logoutButton;
public int level;
#Override
public void onCreate(Bundle savedInstanceState) {
batteryTxt = (TextView) this.findViewById(R.id.percent);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_appbar);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawerLayout), toolbar);
logoutButton = (Button) findViewById(R.id.logoutButton);
logoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Set up a progress dialog
final ProgressDialog logout = new ProgressDialog(MainActivity.this);
logout.setTitle("Please wait.");
logout.setMessage("Logging out. Please wait.");
logout.show();
ParseUser.logOutInBackground(new LogOutCallback() {
public void done(ParseException e) {
logout.dismiss();
if (e == null) {
Intent logoutDone = new Intent(MainActivity.this, DispatchActivity.class);
startActivity(logoutDone);
} else {
Toast.makeText(MainActivity.this, "Logout Unsuccessful", Toast.LENGTH_LONG).show();
}
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Based on your stack trace, it looks like it is throwing a NullPointerException because the batteryTxt field is null at the time that the intent was received. As Daniel Nugent pointed out, this is because the receiver is registered before calling setContentView(). However, it looks like you're also never unregistering your receiver, so I suggest moving the code to register the receiver to the onResume() method, and adding an unregister call in the onPause() method to prevent this same NullPointerException from occurring when your activity is stopped.
#Override
protected void onResume() {
super.onResume();
registerReceiver(mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
#Override
protected void onPause() {
unregisterReceiver(mBatInfoReceiver);
super.onPause();
}
do this
batteryTxt = (TextView) this.findViewById(R.id.percent);
after this
setContentView(R.layout.activity_main_appbar);
always read this section in your error log
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Write the code like that
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_appbar);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
batteryTxt = (TextView) this.findViewById(R.id.percent);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

Categories

Resources