Try to invoke virtual method on a null object reference [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 am trying to make a barcode scanner app, and I want to add scan results to a certain list. In the MainActivity, I have a certain button that should send me to MyList activity, but then the app crashes and I don't know how to solve it.
So here is my code:
public class MainActivity extends AbsRuntimePermission implements ZXingScannerView.ResultHandler{
private ZXingScannerView zXingScannerView;
private static final int REQUEST_PERMISSION = 10;
boolean ok = false, chk = false;
private String scanResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chk = getIntent().getBooleanExtra("check", chk);
if(chk) {
chk = false;
ok = true;
zXingScannerView = new ZXingScannerView(getApplicationContext());
setContentView(zXingScannerView);
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera();
}
}
public void scan(View view){
requestAppPermissions(new String[]{Manifest.permission.CAMERA}, R.string.msg, REQUEST_PERMISSION);
ok = true;
zXingScannerView = new ZXingScannerView(getApplicationContext());
setContentView(zXingScannerView);
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera();
}
#Override
public void onPermissionGranted(int requestCode) {
if(ok)
Toast.makeText(getApplicationContext(), "Permission Granted", Toast.LENGTH_LONG).show();
}
#Override
public void onResume(){
super.onResume();
if(ok)
{
if(zXingScannerView == null)
{
zXingScannerView = new ZXingScannerView(this);
setContentView(zXingScannerView);
}
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera();
}
}
#Override
protected void onPause() {
super.onPause();
zXingScannerView.stopCamera();
}
#Override
public void handleResult(final Result result) {
scanResult = result.getText();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Result");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
zXingScannerView.resumeCameraPreview(MainActivity.this);
}
});
builder.setNeutralButton("GO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(scanResult));
startActivity(intent);
}catch (Exception ex)
{
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, scanResult);
startActivity(intent);
}
}
});
builder.setNegativeButton("Add to list", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainActivity.this, MyList.class);
intent.putExtra("CODE", scanResult);
startActivity(intent);
}
});
builder.setMessage(scanResult);
AlertDialog alert = builder.create();
alert.show();
}
public void Lista(View view){
Intent iNtent = new Intent(MainActivity.this, MyList.class);
startActivity(iNtent);
}
}`
And this is my error report:
01-12 09:42:26.013 2670-2670/com.example.tchibo.justqr E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.tchibo.justqr, PID: 2670
java.lang.RuntimeException: Unable to pause activity {com.example.tchibo.justqr/com.example.tchibo.justqr.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void me.dm7.barcodescanner.zxing.ZXingScannerView.stopCamera()' on a null object reference at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:3976)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3942)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3916)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3890)
at android.app.ActivityThread.-wrap15(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1605)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
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 virtual method 'void me.dm7.barcodescanner.zxing.ZXingScannerView.stopCamera()' on a null object reference
Actually, it says that is trying to invoke virtual method void me.dm7.barcodescanner.zxing.ZXingScannerView.stopCamera() on a null object reference.
(sorry for the post style but i'm not familiar with it)

Well you create method scan(View view) in this method you initialize your camera(ZXingScannerView ) object but din't call anywhere. have look for solution
in onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chk = getIntent().getBooleanExtra("check", chk);
zXingScannerView = new ZXingScannerView(getApplicationContext());
if(chk) {
chk = false;
ok = true;
zXingScannerView = new ZXingScannerView(getApplicationContext());
setContentView(zXingScannerView);
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera();
}
}
in onPause()
#Override
protected void onPause() {
super.onPause();
if(zXingScannerView!=null)
zXingScannerView.stopCamera();
}

You can check zXingScannerView before using it.
if (zXingScannerView != null){
zXingScannerView.stopCamera();
}

java.lang.RuntimeException: Unable to pause activity
{com.example.tchibo.justqr/com.example.tchibo.justqr.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
me.dm7.barcodescanner.zxing.ZXingScannerView.stopCamera()' on a null
object reference
the logcat is telling you the problem, which is this line :
zXingScannerView.stopCamera();
your app is trying to stop something that does not exist !!
trivial solution :
if(zXingScannerView!=null){
zXingScannerView.stopCamera();
}

Related

OkHttpClient throws an error when trying to load data from sharedPrefrences

I'm making an app that controls esp modules and I'm using OkHttpClient to make post web requests.
You can set the ip of the esp module in the settings tab(e.g. if your esp ip is 123.456.789, the url for web request would be http://123.456.789), I'm saving, loading and getting that data from my settings activity to my main activity using sharedPrefrences, but when I open the app, it just crashes with the error url == null.
The only way I got it to work would be if I load it something like this:
public String ip = SettingsActivity.ipEsp;
but then every time I re-open the app, I have to open the setting activity for the data to be loaded.(tried saving this value with sharedPrefrences, but it doesn't seem to work, it doesn't crash or anything it just doesn't work)
I would want to have it saved in a way so whenever I re-open the app, it remembers the ip address that i set in the settings.
Here's the main activity code:
public class MainActivity extends AppCompatActivity {
Button settings;
Button send;
TextView view;
TextView see;
public String urlS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settings = (Button) findViewById(R.id.button);
send = (Button) findViewById(R.id.button2);
view = (TextView) findViewById(R.id.textView);
see = (TextView) findViewById(R.id.see);
SharedPreferences urls = getSharedPreferences("sPrefs", MODE_PRIVATE);
urlS = urls.getString("url", "http://0.0.0.0:8888");
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
client.newCall(requestlL).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()){
String myR = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
see.setText(myR);
}
});
}
}
});
view.setText(urlS);
}
}
);
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setting();
}
});
}
OkHttpClient client = new OkHttpClient();
String urllL = urlS;
Request requestlL = new Request.Builder()
.url(urllL)
.build();
public void setting() {
Intent intent = new Intent(this, MainActivity2.class);
startActivity(intent);
}
}
and this is the setting activity code:
public class MainActivity2 extends AppCompatActivity {
private Handler sHand = new Handler();
public static final String S_PREFS = "sPrefs";
public static final String URL = "url";
Button back;
Button save;
EditText url;
public String urlS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
back = (Button) findViewById(R.id.button3);
save = (Button) findViewById(R.id.button4);
url = (EditText) findViewById(R.id.edit);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
back();
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
urlS = url.getText().toString();
save();
}
});
load();
view();
}
public void back()
{
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
public void saveDataRunS()
{
sHand.post(saveDs);
}
private Runnable saveDs= new Runnable() {
#Override
public void run() {
save();
load();
sHand.postDelayed(this, 1);
}
};
public void save()
{
SharedPreferences sharedPreferences = getSharedPreferences("sPrefs", MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString(URL, url.getText().toString());
edit.apply();
}
public void load()
{
SharedPreferences sharedPreferences = getSharedPreferences(S_PREFS, MODE_PRIVATE);
urlS = sharedPreferences.getString(URL, "http://0.0.0.0:8888");
}
public void view()
{
url.setText(urlS);
}
}
and this is the error i get:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.test, PID: 18146
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.test/com.example.test.MainActivity}: java.lang.NullPointerException: url == null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3222)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3437)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2041)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7386)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
Caused by: java.lang.NullPointerException: url == null
at okhttp3.Request$Builder.url(Request.java:132)
at com.example.test.MainActivity.<init>(MainActivity.java:99)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1250)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3210)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3437) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2041) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7386) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980) 
#leeo6002
In MainActivity2, save() method is called in the following fashion.
onCreate -> saveDataRunS ->sHand.post(saveDs) -> save -> edit.putString(URL, url.getText().toString());
Basically, you are fetching the value from the url editText as soon as activity's onCreate is triggered. Which means you are not waiting for the user to enter the value in the EditText. At least, this is one of the issue.
Honestly, You need to clean up your code, It is a lot of mess right now.

How to cann a method located in service form Ativity

I'm trying to call my getWord(String w) function OnButtonClick, but when I do so my app crashes? Am I calling my Service function wrong?
ListActivity.java
WordLeanerService WLService;
ServiceConnection WLConn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent serviceIntent = new Intent(ListActivity.this,WordLeanerService.class);
startService(serviceIntent);
setupConnectionToWLservice();
searchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Saving user's input in search field
input = String.valueOf(editSearch.getText());
//Checking if input is valid (not empty and only alphabet characters)
if (!input.equals("") && (input.matches("[a-zA-Z]+"))) {
//Sending input to request
WLService.getWord(input);
} else {
Toast.makeText(getApplicationContext(), getString(R.string.input_invalid_message_toast), Toast.LENGTH_LONG).show();
}
}
});
}
private void setupConnectionToWLservice(){
WLConn = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
bindService(new Intent(ListActivity.this,WordLeanerService.class),WLConn, Context.BIND_AUTO_CREATE);
//ref: http://developer.android.com/reference/android/app/Service.html
WLService = ((WordLeanerService.ServiceBinder)service).getService();
//TODO: probably a good place to update UI after data loading
}
#Override
public void onServiceDisconnected(ComponentName className) {
//ref: http://developer.android.com/reference/android/app/Service.html
WLService = null;
}
};
}
WordLeanerService.java
public void getWord(String w) {
Toast.makeText(this, w, Toast.LENGTH_SHORT).show();
}
Logcat
2020-03-28 14:27:03.098 28186-28186/com.example.word_learner_app E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.word_learner_app, PID: 28186
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.word_learner_app.WordLeanerService.getWord(java.lang.String)' on a null object reference
at com.example.word_learner_app.ListActivity$1.onClick(ListActivity.java:78)
So the ERROR is: WLService.getWord(input);

Android Java: AlertDialog method called from another class causes null pointer exception

I'm trying to call a method from another class which then calls an AlertDialog method, and I've tried many things but it always causes a null pointer exception. The calling class is running a web server, and I have a RecyclerView list on the activity class containing the method being called. here's some code from the activity class with AlertDialog:
public class ListClass extends AppCompatActivity {
private WebSvr server;
private static final int PORT = 8080;
private androidx.appcompat.widget.Toolbar toolbar;
private ListView lv;
private CustomAdapter customAdapter;
public ArrayList<EditModel> editModelArrayList;
public static String[] newList = new String[20];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server_screen);
toolbar = (androidx.appcompat.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
startWebServer();
customAdapter = new CustomAdapter(this, editModelArrayList);
lv.setAdapter(customAdapter);
}
public static boolean listUpdated;
public void updateList() {
listUpdated = false;
Runnable r = new Runnable() {
#Override
public void run() {
for (int i = 0; i < 20; i++) {
if (CustomAdapter.editModelArrayList.get(i).getEditTextValue() != "") {
newList[i] = CustomAdapter.editModelArrayList.get(i).getEditTextValue();
} else {
if (!showNotification) {
runOnUiThread(new Runnable() {
#Override
public void run() {
showNullFieldNotification(); // <------------- CALLING THIS
}
});
showNotification = true;
}
}
}
listUpdated = true;
}
};
Thread thread = new Thread(r);
thread.start();
}
boolean showNotification = false;
public void showNullFieldNotification() {
new AlertDialog.Builder(ListClass.this)
.setTitle("Warning, some fields are empty")
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
showNotification = false;
}
}).show();
}
public static boolean returnListUpdated() {
return listUpdated;
}
...
}
And here's the code from my web server class:
public class WebSvr extends NanoHTTPD {
public ListClass ListClass = new ListClass();
public WebSvr(int port){
super(port);
}
#Override
public Response serve(String uri, Method method,
Map<String, String> header,
Map<String, String> parameters,
Map<String, String> files) {
ListClass.updateList(); // <--------------- THE METHOD CALLED
while (!ListClass.returnListUpdated()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String strResponse = Arrays.toString(ListClass.returnString());
return newFixedLengthResponse(strResponse);
}
}
It always causes null pointer exception on this line:
new AlertDialog.Builder(ListClass.this)
and where the method is called in ListClass:
showNullFieldNotification();
Error message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.espressif.iot_esptouch_demo, PID: 18217
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:152)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:224)
at android.app.AlertDialog$Builder.<init>(AlertDialog.java:454)
at com.myProject.ListClass.showNullFieldNotification(ListClass.java:177)
at com.myProject.ListClass$4.run(ListClass.java:193)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6665)
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:772)
If I call showNullFieldNotification() in ListClass onCreate() or from the options menu it works no problem, but when called from the WebSvr class it always causes the exception.
For context on the AlertDialog I've tried ListClass.this, getApplicationContext(), getBaseContext()... I've tried to save a context in onCreate as getApplicationContext() and use that.
I've tried to use the solution from this question to get context but that didn't work either. Would really appreciate any help.
EDIT: Forgot to mention that I had also tried to build the alert in this way:
public void showNullFieldNotification2() {
AlertDialog.Builder alert = new AlertDialog.Builder(ListClass.this);
alert.setTitle("Warning, some fields detected as being empty or having \"0\" as value");
alert.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
showNotification = false;
}
});
AlertDialog dialog = alert.create();
dialog.show();
}
you forgot create Alert Dialog so it null, not the context
Android simple alert dialog
Got the solution from here in answer from Dan Bray. Needed to use a static context.
Since you are calling from outside of an activity, you'll need to save the context in activity class:
public static Context context;
And inside onCreate:
context = this;
To show notification:
new Handler(Looper.getMainLooper()).post(new Runnable(){
#Override
public void run(){
new AlertDialog.Builder(context)
.setTitle("Warning, some fields are empty")
.setNegativeButton("OK",new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface,int i){
dialogInterface.cancel();
showNotification=false;
}
}).show();
}
});
The methods called in the activity class must also be public static.

Sinch call button error?

I am trying to access a class in another class and i can getting this error. I am using sinch to implement app to app phone call in my application and it is still not working.
This is my error
FATAL EXCEPTION: main
Process: com.example.thinker.myapplication2, PID: 10039
java.lang.NullPointerException: Attempt to invoke virtual method 'com.sinch.android.rtc.calling.Call com.example.thinker.myapplication2.SinchService$SinchServiceInterface.callUser(java.lang.String)' on a null object reference
at com.example.thinker.myapplication2.tabs.Chatting$Bases.callButtonClicked(Chatting.java:128)
at com.example.thinker.myapplication2.tabs.Chatting$1.onClick(Chatting.java:83)
at android.view.View.performClick(View.java:5265)
at android.view.View$PerformClick.run(View.java:21534)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5683)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
This is my java class.
public class Chatting extends ListActivity {
Runnable refresh, refres;
ImageView send,back,call;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yon);
call= (ImageView)findViewById(R.id.call);
call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (!isOnline(Chatting.this)) {
Toast.makeText(Chatting.this, "No network connection",
Toast.LENGTH_SHORT).show();
return;
}
Bases ba = new Bases();
ba.onServiceConnected();
ba.callButtonClicked();
}
});
}
public class Bases extends BaseActivity {
#Override
protected void onServiceConnected() {
Toast.makeText(this, " call ready", Toast.LENGTH_LONG).show();
}
public void callButtonClicked() {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
String emaill = sp.getString("friend_email", "anon");
if (emaill.isEmpty()) {
Toast.makeText(this, "Please enter a user to call", Toast.LENGTH_LONG).show();
return;
}
try {
Call call = getSinchServiceInterface().callUser("emaill");
if (call == null) {
// Service failed for some reason, show a Toast and abort
Toast.makeText(this, "Service is not started. Try stopping the service and starting it again before "
+ "placing a call.", Toast.LENGTH_LONG).show();
return;
}
String callId = call.getCallId();
Intent callScreen = new Intent(this, CallScreenActivity.class);
callScreen.putExtra(SinchService.CALL_ID, callId);
startActivity(callScreen);
} catch (MissingPermissionException e) {
ActivityCompat.requestPermissions(this, new String[]{e.getRequiredPermission()}, 0);
}
}
}
}
below is the baseactivity class that has the getSinchServiceInterface(). that is returning null
public abstract class BaseActivity extends Activity implements ServiceConnection {
private SinchService.SinchServiceInterface mSinchServiceInterface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getApplicationContext().bindService(new Intent(this, SinchService.class), this,
BIND_AUTO_CREATE);
}
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
if (SinchService.class.getName().equals(componentName.getClassName())) {
mSinchServiceInterface = (SinchService.SinchServiceInterface) iBinder;
onServiceConnected();
}
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
if (SinchService.class.getName().equals(componentName.getClassName())) {
mSinchServiceInterface = null;
onServiceDisconnected();
}
}
protected void onServiceConnected() {
// for subclasses
}
protected void onServiceDisconnected() {
// for subclasses
}
protected SinchService.SinchServiceInterface getSinchServiceInterface() {
return mSinchServiceInterface;
}
}
Most of time this happen when someone use wrong way to pass context try to pass context as YourActivityName.this (eg Bases.this )rather than just this or getApplicationContext()
start with
#Override
protected void onServiceConnected() {
Toast.makeText(Bases.this, " call ready", Toast.LENGTH_LONG).show();
}
this is not the proper method to call activity
Bases ba = new Bases();
ba.onServiceConnected();
ba.callButtonClicked();
use
Intent intent = new Intent(YourCurrentActivityName.this,Bases.class);
startActivity(intent);
in the oncreate method you can call this methods callButtonClicked()

killing a task in android by handler

I am scheduling few functions by using timer handler.This is what happens.
When i press the button the timer starts sending sms and it opens another activity.
Then in the another activity i have put the stop button to terminate the timer and return back to main activity.
The timer terminates but it crashes the app and return back to main activity.
Here is the code
MainActivity.java
public class MainActivity extends FragmentActivity{
protected static final int CONTACT_PICKER_RESULT = 0;
int count=0;
private RadioButton radioBtnten;
private RadioButton radioBtnone;
Button sendBtn,contact;
EditText txtphoneNo;
EditText txtMessage;
GPSTracker gps;
Timer timer;
TimerTask timerTask;
final Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled)
{
Toast.makeText(getApplicationContext(), "Your GPS IS NOT ON SWITCH IT ON HERE",Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
radioBtnten=(RadioButton)findViewById(R.id.ten);
radioBtnone=(RadioButton)findViewById(R.id.one);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
txtphoneNo= (EditText) findViewById(R.id.editTextPhoneNo);
contact = (Button)findViewById(R.id.contact);
//txtMessage //= (EditText) findViewById(R.id.editTextSMS);
gps = new GPSTracker(MainActivity.this);
contact.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, CONTACT_PICKER_RESULT);
}
});
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTimer();
sendSMSMessage();
Intent toAnotherActivity = new Intent(MainActivity.this, maps.class);
startActivityForResult(toAnotherActivity, 0);
}
});
}
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, after the first 5000ms the TimerTask will run every 10000ms//
if(radioBtnten.isChecked()==true)
timer.schedule(timerTask, 5000, 10000);
// if(radioBtn2.isSelected()==true)
else if(radioBtnone.isChecked()==true)
timer.schedule(timerTask, 5000, 1000);
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
//use a handler to run a toast that shows the current timestamp
handler.post(new Runnable() {
public void run() {
//get the current timeStamp
Toast.makeText(getApplicationContext(), "your message has been sent, the message(s) sent are:-"+count++,Toast.LENGTH_LONG).show();
sendSMSMessage();
//show the toast
}
});
}
};
}
public void stoptimertask(View v)
{
//stop the timer, if it's not already null
Toast.makeText(getApplicationContext(), "Stop button pressed",Toast.LENGTH_LONG).show();
if (timer != null)
{
timer.cancel();
timer = null;
}
}
protected void sendSMSMessage() {
Log.i("Send SMS", "");
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
String phoneNo = txtphoneNo.getText().toString();
String message = "These are my co-ordinates:-"+ latitude + ", " + longitude;
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
The next activity is this
maps.java
public class maps extends FragmentActivity implements LocationListener {
MainActivity maine= new MainActivity();
GoogleMap googleMap;
Button stop;
Timer timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.maps);
stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(new View.OnClickListener()
{
public void onClick(View aView)
{
maine.stoptimertask(aView);
Intent toAnotherActivity = new Intent(aView.getContext(), MainActivity.class);
startActivityForResult(toAnotherActivity, 0);
//stop the timer, if it's not already null
Toast.makeText(getApplicationContext(), "Stop button pressed",Toast.LENGTH_LONG).show();
}
});
i created an object of mainactivity and called the stoptimertask method. The app crashes with this log cat :-
FATAL EXCEPTION: main
Process: com.example.textmessage, PID: 27301
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:105)
at com.example.textmessage.MainActivity.stoptimertask(MainActivity.java:129)
at com.example.textmessage.maps$1.onClick(maps.java:42)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
What i want is when the button stop is pressed in maps.java, the sending sms function should stop and it should return back to MainActivity.java
You can't create an Activity by using new. It will not be a valid activity. Only the Android framework can create a valid Activity object. To start a new Activity, call startActivity. WHile using new to create an Activity will compile, that object will not be properly initialized and weird crashes will result.
The maine.stoptimertask(aView); does not contain the correct instance.
Basically you have to in your
stop.setOnClickListener (new View.OnClickListener ()
{
public void onClick(View aView)
{
Intent returnIntent = new Intent();
setResult(RESULT_OK,returnIntent);
this.finish();
//stop the timer, if it's not already null
Toast.makeText(getApplicationContext(), "Stop button pressed",Toast.LENGTH_LONG).show();
}
});
returning to MainActivity the value you want to go there and implement a
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == 0) { // because you startActivityForResult(toAnotherActivity, 0);
// Make sure the request was successful
if (resultCode == RESULT_OK) {
stoptimertask(); // forget view you don't need
}
}
}
to find out that there was an action in your activity maps.
See documentation for getting a result from an Activity in this link:
http://developer.android.com/training/basics/intents/result.html

Categories

Resources