Getting NullPointerException in SharedPreferences [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I start android developing recently. I may have some lack of knowledge in this scenario.But I searched a lot and can't make a solution for this project.
Facing problem with this.I failed to figure it out. My SharedPreferences Class is.
public class PermanentScoreHolder {
public static boolean storeScore(String prefName,float score)
{
float temp = VarHolder.SHARED_PREFERENCES.getFloat(VarHolder.SUFFIX_PREFERENCES+prefName, 0f);
if(temp<score)
{
VarHolder.EDITOR.putFloat(VarHolder.SUFFIX_PREFERENCES+prefName, score);
VarHolder.EDITOR.commit();
return true;
}
return false;
}
public static float getScore(String prefName)
{
return VarHolder.SHARED_PREFERENCES.getFloat(VarHolder.SUFFIX_PREFERENCES+prefName, 0f);
}
}
My activity class is like this:
public class ScoreActivity extends Activity {
TextView normal,danger,thunder,zen,rush;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_score);
normal = (TextView) findViewById(R.id.normalScore);
normal.setText(PermanentScoreHolder.getScore("1")+"");//Logcat says problem is here.
}
public void onBackPressed() {
Intent i = new Intent(getBaseContext(),OptionMenuActivity.class);
startActivity(i);
finish();
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.score, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPause() {
super.onResume();
overridePendingTransition(0, 0);
}
#Override
protected void onResume() {
super.onResume();
overridePendingTransition(0, 0);
}}
My Logcat is here:
FATAL EXCEPTION: main
Process: cafesoft.td.tappingtile, PID: 8740
java.lang.RuntimeException: Unable to start activity ComponentInfo{cafesoft.td.tappingtile/cafesoft.td.tappingtile.ScoreActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'float android.content.SharedPreferences.getFloat(java.lang.String, float)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'float android.content.SharedPreferences.getFloat(java.lang.String, float)' on a null object reference
at cafesoft.td.tappingtile.PermanentScoreHolder.getScore(PermanentScoreHolder.java:18)
at cafesoft.td.tappingtile.ScoreActivity.onCreate(ScoreActivity.java:98)
at android.app.Activity.performCreate(Activity.java:6980)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6540) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
I don't understand whats wrong with this code.I need a solution and why this occurs.  

Your VarHolder.SHARED_PREFERENCES in the class PermanentScoreHolder has a null reference.
This is how we get SharedPreferences instance:
SharedPreferences pref = context.getSharedPreferences("unique_key", Context.MODE_PRIVATE);
Then get the float from SharedPreferences:
pref.getFloat("key", defaultValue);

Related

startActivity sending to wrong activity: Android

I'm trying to have it to where after the my "Overview" Button is clicked the next button "Variables" is enabled. The button enables, however the setOnClickListener for my "Variables" sends me to my OverviewActivity, rather than my VariablesActivity. I've been stuck on this for a while.
The Variables Activity is just a multiple choice screen, but i was just setting it up.
I'm really new to Java and Android Studio, so this is getting confusing fast
Code:
public class HomeActivity extends AppCompatActivity {
public Button signOutBtn;
public Button overviewBtn;
public Button varBtn;
FirebaseAuth auth;
boolean overviewDone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
signOutBtn = findViewById(R.id.signOutBtn);
overviewBtn = findViewById(R.id.overviewBtn);
varBtn = findViewById(R.id.varBtn);
auth = FirebaseAuth.getInstance();
overviewDone = false;
signOutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
auth.signOut();
startActivity(new Intent(HomeActivity.this, SignInActivity.class));
finish();
}
});
overviewBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent overviewBtnIntent = new Intent(HomeActivity.this, OverviewActivity.class);
startActivity(overviewBtnIntent);
}
});
if (getIntent().hasExtra("state")) {
if (getIntent().getStringExtra("state").equals("enable")) {
overviewDone = true;
varBtn.setEnabled(true);
} else {
varBtn.setEnabled(false);
}
} else {
varBtn.setEnabled(false);
}
varBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent varbiesButtonIntent = new Intent(HomeActivity.this, VariablesActivity.class);
startActivity(varbiesButtonIntent);
Log.i("Variable Button", "Going to Variable Activity");
}
});
}
}
public class OverviewActivity extends AppCompatActivity {
public Button backBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_overview);
backBtn = findViewById(R.id.ov_backButton);
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(OverviewActivity.this, HomeActivity.class);
intent.putExtra("state", "enable");
startActivity(intent);
}
});
}
}
public class VariablesActivity extends AppCompatActivity {
public RadioGroup radioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_variables);
radioGroup = (RadioGroup)findViewById(R.id.RadioGroup);
// getting value of radio button checked
final String value = ((RadioButton)findViewById(radioGroup.getCheckedRadioButtonId())).getText().toString();
if(radioGroup.getCheckedRadioButtonId() == -1){
// no radio buttons checked
} else{
// one the radio buttons are checked
Log.i("Radio Button Clicked", value);
}
}
}
Stacktrace:
2021-11-22 21:45:23.550 4535-4535/com.example.codehorizonapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.codehorizonapplication, PID: 4535
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.codehorizonapplication/com.example.codehorizonapplication.VariablesActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference
at com.example.codehorizonapplication.VariablesActivity.onCreate(VariablesActivity.java:24)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6669) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
int checkedId = radioGroup.getCheckedRadioButtonId();
String value = "";
if(checkedId != -1){
value = ((RadioButton)findViewById(checkedId)).getText().toString();
}
radioGroup.getCheckedRadioButtonId() returns -1 if there is nothing checked, -1 isn't a valid Id thus findViewById returns null.
null.getText() is a java.lang.NullPointerException
This is under the assumption that there is nothing selected and the fact that calling radioGroup.getCheckedRadioButtonId() doesn't crash only when you call getText() does it crash means your radioGroup = (RadioGroup)findViewById(R.id.RadioGroup); is correct.
The reason the OverviewActivity is created instead is due to a stack problem caused by the premature end to VariablesActivity due to the exception.

Problem with actionView() - java.lang.NullPointerException:

So this is a part of code found on my MainActivity.java. What it basically does is allowing me to go to the Cart Fragment when I click on the icon (cart_badge_text_view) at the top of my application.
When I try to open the application,the view loads up but then it immediately crashes.
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
final MenuItem menuItem = menu.findItem(R.id.cartFragment);
View actionView = menuItem.getActionView(); --> PROBLEM
TextView cartBadgeTextView = actionView.findViewById(R.id.cart_badge_text_view);
cartBadgeTextView.setText(String.valueOf(cartQuantity));
cartBadgeTextView.setVisibility(cartQuantity == 0 ? View.GONE : View.VISIBLE);
actionView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOptionsItemSelected(menuItem);
}
});
This is the logcat after building the app:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.example, PID: 8621
**java.lang.NullPointerException: Attempt to invoke interface method 'android.view.View android.view.MenuItem.getActionView()' on a null object reference --> MAIN PROBLEM**
at com.example.example.views.MainActivity.onCreateOptionsMenu(MainActivity.java:69)
at android.app.Activity.onCreatePanelMenu(Activity.java:4206)
at androidx.fragment.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:324)
at androidx.appcompat.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:94)
at androidx.appcompat.app.AppCompatDelegateImpl$AppCompatWindowCallback.onCreatePanelMenu(AppCompatDelegateImpl.java:3070)
at androidx.appcompat.app.AppCompatDelegateImpl.preparePanel(AppCompatDelegateImpl.java:1895)
at androidx.appcompat.app.AppCompatDelegateImpl.doInvalidatePanelMenu(AppCompatDelegateImpl.java:2176)
at androidx.appcompat.app.AppCompatDelegateImpl$2.run(AppCompatDelegateImpl.java:268)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

Error java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService

I'm creating a simple Android Class that update a variable with the most recent value readed from some specific sensors (Light, temp and more), which I access it(sensor value) by getData() method, but i'm getting an error. I hope u can help me!
Here is my generic sensor class.
MySensor
public class mySensor extends Service implements SensorEventListener {
private SensorManager mSensorManager =null;
private Sensor s=null;
float data = 0;
public void onCreate(){
super.onCreate();
mSensorManager= (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
public mySensor(int type){
//HERE I'M GETTING THE ERROR
s= mSensorManager.getDefaultSensor(type);
}
public String getData(){
return String.valueOf(data);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_LIGHT) {
data = event.values[0];
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
protected void onResume() {
mSensorManager.registerListener((SensorEventListener) this, s, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
// super.onPause();
mSensorManager.unregisterListener((SensorEventListener) this);
}
}
Here is the log
...
E/AndroidRuntime: FATAL EXCEPTION: main
Process: project.luke.com.sensorreader, PID: 25297
java.lang.RuntimeException: Unable to start activity ComponentInfo{project.luke.com.sensorreader/project.luke.com.sensorreader.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.hardware.Sensor android.hardware.SensorManager.getDefaultSensor(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2460)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2522)
at android.app.ActivityThread.access$800(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5546)
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:967)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.hardware.Sensor android.hardware.SensorManager.getDefaultSensor(int)' on a null object reference
at project.luke.com.sensorreader.mySensor.<init>(mySensor.java:39)
at project.luke.com.sensorreader.MainActivity.onCreate(MainActivity.java:32)
at android.app.Activity.performCreate(Activity.java:5975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2522) 
at android.app.ActivityThread.access$800(ActivityThread.java:169) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:194) 
at android.app.ActivityThread.main(ActivityThread.java:5546) 
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:967) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762) 
In my MainActivity class I simple call mLight=new mySensor(Sensor.TYPE_LIGHT); but this trigger the error, cause mSensorManager=null, always.
From your MainActivity:
Intent intent = new Intent(this, mySensor.class);
intent.putExtra("type", Sensor.TYPE_LIGHT);
and within your service:
#Override
public IBinder onBind(Intent intent) {
mSensorManager= (SensorManager) getSystemService(Context.SENSOR_SERVICE);
int type = intent.getExtras().get("type");
s= mSensorManager.getDefaultSensor(type);
return null;
}
then you can remove:
public mySensor(int type){
...
}
and eventually the code you wrote within the onCreate.

I have simple android App in android studio and it does not work

package viewbrosers.mehdi.home.mytestappviewbrowser;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button getAnswer = (Button) findViewById(R.id.getAnswerButton);
getAnswer.setOnClickListener(getAnswerListener);
}
private View.OnClickListener getAnswerListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Random randomnum = new Random();
int numToast = randomnum.nextInt(19);
numToast++;
CharSequence text = "";
switch (numToast) {
case 1:
text = getString(R.string.answer1);
break;
case 2:
text = getString(R.string.answer2);
break;
case 3:
text = getString(R.string.answer3);
break;
case 4:
text = getString(R.string.answer4);
break;
case 5:
text = getString(R.string.answer5);
break;
case 6:
text = getString(R.string.answer6);
break;
case 7:
text = getString(R.string.answer7);
break;
}
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.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);
}
}
My error is:
Unfortunately Application has stopped and 06-05
11:31:44.131 13711-13711/? I/art﹕ Not late-enabling -Xcheck:jni
(already on) 06-05 11:31:44.208 13711-13711/? D/AndroidRuntime﹕
Shutting down VM 06-05 11:31:44.208 13711-13711/? E/AndroidRuntime﹕
FATAL EXCEPTION: main
Process: viewbrosers.mehdi.home.mytestappviewbrowser, PID: 13711
java.lang.RuntimeException: Unable to start activity ComponentInfo{viewbrosers.mehdi.home.mytestappviewbrowser/viewbrosers.mehdi.home.mytestappviewbrowser.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'boolean java.lang.String.equals(java.lang.Object)' on a null object
reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on
a null object reference
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:715)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:378)
at android.app.Activity.setContentView(Activity.java:2145)
at viewbrosers.mehdi.home.mytestappviewbrowser.MainActivity.onCreate(MainActivity.java:23)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            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:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 06-05
11:31:44.218 13711-13718/? I/art﹕ Debugger is no longer active 06-05
11:32:28.690 13711-13718/viewbrosers.mehdi.home.mytestappviewbrowser
W/art﹕ Suspending all threads took: 12.748ms
Move the creation and initialization of your text variable outside of the onClick() method. Try the following code.
public class MainActivity extends Activity {
CharSequence text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = "";
Button getAnswer = (Button) findViewById(R.id.getAnswerButton);
getAnswer.setOnClickListener(getAnswerListener);
}
private View.OnClickListener getAnswerListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Random randomnum = new Random();
int numToast = randomnum.nextInt(19);
numToast++;
switch (numToast) {
case 1:
text = getString(R.string.answer1);
break;
case 2:
text = getString(R.string.answer2);
break;
case 3:
text = getString(R.string.answer3);
break;
case 4:
text = getString(R.string.answer4);
break;
case 5:
text = getString(R.string.answer5);
break;
case 6:
text = getString(R.string.answer6);
break;
case 7:
text = getString(R.string.answer7);
break;
}
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.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);
}
}
You are somewhere using equals function on string which is null.
Look at exception: 'boolean java.lang.String.equals(java.lang.Object)' on a null object
reference
Try it, may be like this.
public class MainActivity extends Activity implements OnClickListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button getAnswer = (Button) findViewById(R.id.getAnswerButton);
getAnswer.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.getAnswerButton:
//Your code
break;
}
}
}

App crashed when arrayAdapter.notifyDataSetChanged() was called

public class Activity_search extends ActionBarActivity {
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mArrayAdapter;
private ArrayList<String> mArrayList;
private boolean isDiscovering;
private AdapterView.OnItemClickListener mClickListener = new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> adapterView,View view,int position, long id ){
mBtAdapter.cancelDiscovery();
isDiscovering=false;
Toast.makeText(getApplicationContext(),"Selected",Toast.LENGTH_SHORT).show();
String tmp1 = ((TextView)view).getText().toString();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_search);
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
mArrayList = new ArrayList<String>();
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(this,R.layout.listview_row,mArrayList);
ListView listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(mArrayAdapter);
listView.setOnItemClickListener(mClickListener);
}
#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_activity_search, 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);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String tmp=device.getName() + "\n" + device.getAddress();
Context appContext = getApplicationContext();
Toast.makeText(appContext,tmp,Toast.LENGTH_LONG).show();
mArrayList.add(tmp);
mArrayAdapter.notifyDataSetChanged();
}
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
Toast.makeText(getApplicationContext(),"Discovery Finished",Toast.LENGTH_SHORT).show();
}
}
};
public void onBtn2Clicked(View view) {
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
Context appContext = getApplicationContext();
if(!isDiscovering) {
mBtAdapter.startDiscovery();
Toast.makeText(appContext, "Discovery Started", Toast.LENGTH_SHORT).show();
isDiscovering=true;
} else {
mBtAdapter.cancelDiscovery();
Toast.makeText(appContext,"Discovery Canceled",Toast.LENGTH_SHORT).show();
isDiscovering=false;
}
}
public void onDestroy(){
super.onDestroy();
if(mBtAdapter.isDiscovering()){
mBtAdapter.cancelDiscovery();
}
unregisterReceiver(mReceiver);
}
}
App always crashed when it called the function as mentioned at above, And its error code is
02-13 16:04:47.974 27328-27328/com.skyjohn.nxtrpc E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.bluetooth.device.action.FOUND flg=0x10 (has extras) } in com.skyjohn.nxtrpc.Activity_search$2#41532570
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:798)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.skyjohn.nxtrpc.Activity_search$2.onReceive(Activity_search.java:90)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:788)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
But if i hardcoded mArrayList.add("abc") into the code, the "abc" will appear, but if I do it dynamicly (when I received a new bluetooth device) , the app crashed.
Caused by: java.lang.NullPointerException
at com.skyjohn.nxtrpc.Activity_search$2.onReceive
mArrayAdapter is null because creating new object of Adapter in onCreate method with same name which declare as class level.
To fix error use:
mArrayAdapter = new ArrayAdapter<String>(this,R.layout.listview_row,mArrayList);
in onCreate method instead of creating new object of ArrayAdapter.
inside onCreate you are hiding the scope of the class member variable mAdapter, declaring and initialazing it in the local scope of onCreate. The fix is to remove ArrayAdapter<String> from onCreate, leaving only
mArrayAdapter = new ArrayAdapter<String>(this,R.layout.listview_row,mArrayList);

Categories