Error receiving broadcast intent using BatteryManager - java

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));

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.

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.

App crashes during Bluetooth discovery

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().

Values not passed between Intent Service and Class

Explanation:
I made this intent service in a new class (connectionchecker.java) which is used to check for internet connection.
Now in my main class (First.java), the values are not recieved because the if() is never executed.
My app doesn't crash, the problem is the TextView is stuck on "CONNECTION:" instead of saying "CONNECTION:You are not connected to the internet." or ""CONNECTION:You are not connected to the internet.".
Code:
First.java
package com.lofty.lofti;
import com.lofty.lofti.util.SystemUiHider;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView.OnKeyboardActionListener;
import android.view.KeyEvent;
import android.view.View.OnKeyListener;
import android.inputmethodservice.KeyboardView;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.content.BroadcastReceiver;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* #see SystemUiHider
*/
public class First extends Activity {
/**
* Whether or not the system UI should be auto-hidden after
* {#link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;
/**
* If {#link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* If set, will toggle the system UI visibility upon interaction. Otherwise,
* will show the system UI visibility upon interaction.
*/
private static final boolean TOGGLE_ON_CLICK = true;
/**
* The flags to pass to {#link SystemUiHider#getInstance}.
*/
private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
/**
* The instance of the {#link SystemUiHider} for this activity.
*/
private SystemUiHider mSystemUiHider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().hide(); // HIDE ACTION BAR.
setContentView(R.layout.activity_first);
EditText enter = (EditText) findViewById(R.id.searchbox);
enter.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
EditText searchbox = (EditText) findViewById(R.id.searchbox);
String search = searchbox.getText().toString();
Intent open = new Intent(Intent.ACTION_WEB_SEARCH);
open.putExtra(SearchManager.QUERY, search);
startActivity(open);
return true;
}
else
{
return false;
}
}
});
}
public class Connection extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
Integer connectionn = intent.getIntExtra("connection",0);
TextView connectiontext = (TextView) findViewById(R.id.connectiontext);
if(connectionn==1)
{
connectiontext.setText("CONNECTION:You are not connected to the internet.");
}
if(connectionn==0)
{
connectiontext.setText("CONNECTION:You are not connected to the internet.");
}
}
}
public void exit(View view)
{
finish();
System.exit(0);
}
public void usernameclick (View view)
{
EditText searchbox = (EditText) findViewById(R.id.searchbox);
String search = searchbox.getText().toString();
Intent open = new Intent(Intent.ACTION_WEB_SEARCH);
open.putExtra(SearchManager.QUERY, search);
startActivity(open);
}
}
connectionchecker.java
package com.lofty.lofti;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.EditText;
public class connectionchecker extends IntentService
{
public static final int connection =0;
public connectionchecker() {
super("connectionchecker");
}
#Override
protected void onHandleIntent(Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED || connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED|| connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET).getState()== NetworkInfo.State.CONNECTED)
{
Intent data = new Intent(this, First.class);
data.putExtra("connection",1);
sendBroadcast(data);
}
else
{
Intent data = new Intent(this, First.class);
data.putExtra("connection", 0 );
sendBroadcast(data);
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.lofty.lofti" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".First"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
android:theme="#style/FullscreenTheme" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".connectionchecker"/>
<receiver android:name=".First$Connection"/>
</application>
</manifest>
Thank you and have a good day.
Logcat:
10-23 16:01:25.765 2175-2175/com.lofty.lofti E/Zygote﹕ MountEmulatedStorage()
10-23 16:01:25.765 2175-2175/com.lofty.lofti E/Zygote﹕ v2
10-23 16:01:25.775 2175-2175/com.lofty.lofti I/SELinux﹕ Function: selinux_compare_spd_ram, SPD-policy is existed. and_ver=SEPF_GT-I9505_5.0.1 ver=27
10-23 16:01:25.775 2175-2175/com.lofty.lofti I/SELinux﹕ Function: selinux_compare_spd_ram , priority [2] , priority version is VE=SEPF_GT-I9505_5.0.1-1_0032
10-23 16:01:25.775 2175-2175/com.lofty.lofti E/SELinux﹕ [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
10-23 16:01:25.775 2175-2175/com.lofty.lofti I/art﹕ Late-enabling -Xcheck:jni
10-23 16:01:25.955 2175-2175/com.lofty.lofti D/ResourcesManager﹕ creating new AssetManager and set to /data/app/com.lofty.lofti-2/base.apk
10-23 16:01:26.185 2175-2175/com.lofty.lofti D/AndroidRuntime﹕ Shutting down VM
10-23 16:01:26.195 2175-2175/com.lofty.lofti E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.lofty.lofti, PID: 2175
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lofty.lofti/com.lofty.lofti.First}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
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:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.support.v7.app.AppCompatDelegateImplV7.createSubDecor(AppCompatDelegateImplV7.java:309)
at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:278)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:252)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at com.lofty.lofti.First.onCreate(First.java:68)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
            at android.app.ActivityThread.access$900(ActivityThread.java:177)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5942)
            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:1400)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
10-23 16:06:26.538 2175-2175/? I/Process﹕ Sending signal. PID: 2175 SIG: 9
I just update your code, by following the tuto from Lars http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html
You have to register the broadcast receiver before it can receive anything.
Have a look at this question. https://stackoverflow.com/a/4806091/2733216
IntentFilter filter = new IntentFilter(Connection.ACTION_RESP);
registerReceiver(mConnection, filter);
Your service wasn't started (at least in the code you provided)
in your Activity 'onCreate'
// Start your Service
Intent msgIntent = new Intent(this, ConnectionChecker.class);
startService(msgIntent);
You didn't instantiate your BroadCastReceiver
// Instanciate your BCR
mConnection = new Connection();
Define a message :
public static final String ACTION_RESP = "intent.action.MESSAGE_PROCESSED";
Define the message to the Intent
data.setAction(MainActivity.Connection.ACTION_RESP);
Use Default Intent Constructor for the one that are sent from the Service
Intent data = new Intent();
Then finally, the whole code :
Activity
public class MainActivity extends AppCompatActivity {
private Connection mConnection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText enter = (EditText) findViewById(R.id.searchbox);
enter.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
EditText searchbox = (EditText) findViewById(R.id.searchbox);
String search = searchbox.getText().toString();
Intent open = new Intent(Intent.ACTION_WEB_SEARCH);
open.putExtra(SearchManager.QUERY, search);
startActivity(open);
return true;
} else {
return false;
}
}
});
// Start your Service
Intent msgIntent = new Intent(this, ConnectionChecker.class);
startService(msgIntent);
// Instanciate BCR
mConnection = new Connection();
// Register BCR
IntentFilter filter = new IntentFilter(Connection.ACTION_RESP);
registerReceiver(mConnection, filter);
}
public class Connection extends BroadcastReceiver {
public static final String ACTION_RESP = "intent.action.MESSAGE_PROCESSED";
#Override
public void onReceive(Context context, Intent intent) {
Integer connectionn = intent.getIntExtra("connection", 0);
TextView connectiontext = (TextView) findViewById(R.id.connectiontext);
if (connectionn == 1)
connectiontext.setText("CONNECTION:You are not connected to the internet.");
else
connectiontext.setText("CONNECTION:You are not connected to the internet.");
}
}
public void exit(View view) {
finish();
System.exit(0);
}
public void usernameclick(View view) {
EditText searchbox = (EditText) findViewById(R.id.searchbox);
String search = searchbox.getText().toString();
Intent open = new Intent(Intent.ACTION_WEB_SEARCH);
open.putExtra(SearchManager.QUERY, search);
startActivity(open);
}
}
Service
public class ConnectionChecker extends IntentService
{
public static final int connection =0;
public ConnectionChecker() {
super("connectionchecker");
}
#Override
protected void onHandleIntent(Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED || connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED|| connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET).getState()== NetworkInfo.State.CONNECTED)
{
Intent data = new Intent();
data.setAction(MainActivity.Connection.ACTION_RESP);
data.putExtra("connection", 1);
sendBroadcast(data);
}
else
{
Intent data = new Intent();
data.setAction(MainActivity.Connection.ACTION_RESP);
data.putExtra("connection", 0 );
sendBroadcast(data);
}
}
}
the values are not received because the if() is never executed
Pass an action for the Intent, instead of using like this:
Intent data = new Intent(this, First.class);
But, you should:
Intent data = new Intent("ACTION_NAME");
And make sure that you registered that action to manifest:
<receiver android:name=".First$Connection">
<intent-filter>
<action android:name="ACTION_NAME" />
</intent-filter>
</receiver>
the problem is the TextView is stuck
Make an instance variable for connectiontext:
public class First extends Activity {
...
private TextView connectiontext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
getActionBar().hide(); // HIDE ACTION BAR.
connectiontext = (TextView) findViewById(R.id.connectiontext);
...
}
...
}

Categories

Resources