Sinch call button error? - java

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

Related

Flag from AsyncTask class doesn't work properly in main class

I've created some lines of code which are supposed to switch to the next activity if connection is set without any exceptions. But if there are some exceptions, it should make "Error!" toast and not go to the next activity.
Boolean flag in Connection class works well: if the server is off, app will say "Error!", if on, it won't. But same flag in main class (con.flag) doesn't work properly, it looks like it is always false. App always switches to the next activity, with making toast or without, depending on server status. What's wrong in my code? I suppose that there's something I don't know about AsyncTask classes' fields initialization.
So, here is my code:
public class Connection extends AsyncTask<Void, Void, String> {
Context mContext;
public Connection(Context context){
this.mContext = context;
}
static String value;
boolean flag = false;
#Override
protected String doInBackground(Void... arg0) {
try {
Jedis jedis = new Jedis("192.168.0.120", 6381);
String name = jedis.ping();
value = name;
} catch (Exception e){
flag = true;
}
return null;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (flag) {
Toast toast = Toast.makeText(mContext,
"Error!", Toast.LENGTH_LONG);
toast.show();
}
}
}
public class MainActivity extends AppCompatActivity {
Button click;
Context maincontext = this;
public void goTo2ndActivity(){
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click = (Button)findViewById(R.id.button);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Connection con = new Connection(maincontext);
con.execute();
if (!con.flag){
goTo2ndActivity();
}
}
});
}
}
Your problem seems to be a race condition between main thread and the asynctask, the problem is in the onClick listener:
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Connection con = new Connection(maincontext);
con.execute();
if (!con.flag){
goTo2ndActivity();
}
}
});
so this part
if (!con.flag){
goTo2ndActivity();
}
must be called from on post execute of your async task, for that pass the activity to the constructor of the async task like this:
update constructor of async task:
public class Connection extends AsyncTask<Void, Void, String> {
Context mContext;
MainActivity activity;
public Connection(Context context,MainActivity activity){
this.mContext = context;
this.activity= activity
}
..........
..........
and on post execute:
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (flag) {
Toast toast = Toast.makeText(mContext,
"Error!", Toast.LENGTH_LONG);
toast.show();
}else{
//go to next activity
activity.goTo2ndActivity();
}
}
now your button click becomes:
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//just execute
final Connection con = new Connection(maincontext,this);
con.execute();
}
});

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

onResume() and onPause() is being called on the first launch

I am having an activity and on Launching the activity through Intent from one of my service, onCreate(), onPause() and onResume() is called.
I am not very sure where i am doing wrong, i have removed all the code, just the basic function codes are available, and also i have removed all the codes which were opening that particular activity, still the behaviour is same.
I am including the simplest code i am using
ActivityClass.java
public class ActivityClass extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println("TEST : onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lockscreen);
ButterKnife.bind(this);
}
#Override
protected void onPause() {
System.out.println("TEST : onPause");
super.onPause();
}
#Override
protected void onDestroy() {
System.out.println("TEST : onDestroy");
super.onDestroy();
}
}
Service class
public class OverlayService extends Service {
Context context;
public static final String TAG = OverlayService.class.getSimpleName();
public OverlayService(Context applicationContext) {
super();
context = applicationContext;
}
public OverlayService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "[onCreateService]");
super.onStartCommand(intent, flags, startId);
KeyguardManager myKM = (KeyguardManager) getApplicationContext().getSystemService(Context.KEYGUARD_SERVICE);
if(myKM.inKeyguardRestrictedInputMode()) {
//it is locked
showOverlayActivity();
} else {
//it is not locked
}
registerOverlayReceiver();
context = this;
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterOverlayReceiver();
Log.i("EXIT", "ondestroy!");
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Intent broadcastIntent = new Intent("ac.in.ActivityRecognition.RestartSensor");
sendBroadcast(broadcastIntent);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void unregisterOverlayReceiver() {
if (overlayReceiver != null) {
unregisterReceiver(overlayReceiver);
}
}
private static final String ACTION_DEBUG = "kunal.lockoverlay.action.DEBUG";
private void registerOverlayReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(ACTION_DEBUG);
registerReceiver(overlayReceiver, filter);
}
private BroadcastReceiver overlayReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(TAG, "[onReceive]" + action);
if (action.equals(Intent.ACTION_SCREEN_ON)) {
// ACTON_SCREEN_ON
showOverlayActivity();
} else if (action.equals(ACTION_DEBUG)) {
showOverlayActivity();
}
}
};
private void showOverlayActivity() {
Intent intent = new Intent();
intent.setClass(this, ActivityClass.class);
intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
Can someone point some of the possible reasons for this behaviour or could identify where i am doing wrong?
Well everything will be called regardless, you have defined it in your ClassName.java file.
You override the method and define it in your class to perform certain action/function when that is called.
For eg.,
You could use onResume to clear an arraylist and add updated elements to arraylist (OR) dismiss all notifications from your app on moving to that activity, say
#Override
public void onResume() {
super.onResume();
calendarList.clear();
//dismiss all notifications here
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager!=null)
notificationManager.cancelAll();
}
OR eg., onDestroy to destroy the bluetooth service,
#Override
public void onDestroy() {
super.onDestroy();
if (mBluetoothService != null) {
mBluetoothService.stop();
}
}
Hope that clarifies. Happy coding!
About service class, you should call registerReceiver() or initialize variables in onCreate instead of onStartCommand because onCreate is only called once at the first time of starting service and onStartCommand will be called every time you want to trigger an action to the service by calling startService(Intent).

How can I get runnable application package name [duplicate]

I used Toast to make notification, but it seems it will appear even its activity is not in the current screen and some other activity has been started.
I want to check this situation, when the activity is not the current one, I'd not send the Toast notification. But how to do ?
When your Activity comes to the foreground, its onResume() method will be invoked. When another Activity comes in front of your Activity, its onPause() method will be invoked. So all you need to do is implement a boolean indicating if your Activity is in the foreground:
private boolean isInFront;
#Override
public void onResume() {
super.onResume();
isInFront = true;
}
#Override
public void onPause() {
super.onPause();
isInFront = false;
}
ArrayList<String> runningactivities = new ArrayList<String>();
ActivityManager activityManager = (ActivityManager)getBaseContext().getSystemService (Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> services = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (int i1 = 0; i1 < services.size(); i1++) {
runningactivities.add(0,services.get(i1).topActivity.toString());
}
if(runningactivities.contains("ComponentInfo{com.app/com.app.main.MyActivity}")==true){
Toast.makeText(getBaseContext(),"Activity is in foreground, active",1000).show();
}
This way you will know if the pointed activity is the current visible activity.
I prefer not to handle the state by myself, so I have implemented a class that does this for me.
package mypackage;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
// Mine extends AppCompatActivity - your's might need to extend Activity, depending on whether
// you use the support library or not.
public class StateTrackingActivity extends AppCompatActivity {
public enum ActivityState {
CREATED, RESUMED, STARTED, PAUSED, STOPPED, DESTROYED
}
private ActivityState _activityState;
protected ActivityState getActivityState() { return _activityState; }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_activityState = ActivityState.CREATED;
}
#Override
protected void onResume() {
super.onResume();
_activityState = ActivityState.RESUMED;
}
#Override
protected void onStart() {
super.onStart();
_activityState = ActivityState.STARTED;
}
#Override
protected void onPause() {
super.onPause();
_activityState = ActivityState.PAUSED;
}
#Override
protected void onStop() {
super.onStop();
_activityState = ActivityState.STOPPED;
}
#Override
protected void onDestroy() {
super.onDestroy();
_activityState = ActivityState.DESTROYED;
}
}
Then your activity can extend this one and you can get the state by calling getActivityState().
This is my ultimate isActivityVisible function.
protected boolean isActivityVisible() {
if (this.mActivity != null) {
Class klass = this.mActivity.getClass();
while (klass != null) {
try {
Field field = klass.getDeclaredField("mResumed");
field.setAccessible(true);
Object obj = field.get(this.mActivity);
return (Boolean)obj;
} catch (NoSuchFieldException exception1) {
// Log.e(TAG, exception1.toString());
} catch (IllegalAccessException exception2) {
// Log.e(TAG, exception2.toString());
}
klass = klass.getSuperclass();
}
}
return false;
}
if (BaseActivity.this instanceof Faq)
{
Toast.makeText(BaseActivity.this, "You are in the Same Page", Toast.LENGTH_SHORT).show();
}else {
Intent intent = new Intent(BaseActivity.this, Faq.class);
startActivity(intent);
drawer.closeDrawer(GravityCompat.START);
}
//// here am All my activities are extending on Activity called BaseActivity
There is Activity#isTaskRoot() method
if ( getActivity() instanceof ManageCardActivity){
// your code
}

AsycTask Throwing IllegalStateException - Fragment Not Attached To Activity

I have the following AsyncTask in my Android application. This AsyncTask is contained with within the OnCreate() method of a class that extends PreferenceFragment.
public class NotificationsPreferenceFragment extends PreferenceFragment {
private static Context context;
public NotificationsPreferenceFragment() {
}
public NotificationsPreferenceFragment(Context context) {
this.context = context;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notifications);
getPreferenceManager().findPreference(getString(R.string.send_all_notifications))
.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
class NotificationSendTask extends DialogAsyncTask {
public static final String TAG = "NotificationFragment";
public NotificationSendTask(Activity activity, String dialogMsg) {
super(activity, dialogMsg);
}
#Override
protected String doInBackground(String... params) {
String url = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString(getString(R.string.notification_web_service_url), getString(R.string.default_notification_web_service_url));
if (NetworkingHelper.isNetworkAvailable(getActivity())) {
NotificationDao notificationDao = new NotificationDaoImpl(DatabaseManager.getInstance(getActivity().getApplicationContext()), getActivity().getApplicationContext());
List<Notification> unsentNotificationList = notificationDao.findAllNotSent();
if (unsentNotificationList.size() != 0) {
NotificationSenderTask ns = new NotificationSenderTask(url, context);
try {
if (ns.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (unsentNotificationList)).get()) {
return getString(R.string.success);
}
} catch (InterruptedException e) {
Log.e(TAG, e.getMessage());
} catch (ExecutionException e) {
Log.e(TAG, e.getMessage());
}
return getString(R.string.failed_to_send_notifications);
} else {
return getString(R.string.no_notifications_to_send);
}
} else {
return getString(R.string.no_connection_notifications);
}
}
public void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog != null && dialog.isShowing()) {
dialog.hide();
}
Toast.makeText(activity, result, Toast.LENGTH_SHORT).show();
}
}
NotificationSendTask notificationSendTask = new NotificationSendTask(getActivity(), "Sending unsent notifications...");
notificationSendTask.execute();
return true;
}
});
getPreferenceManager().findPreference(getString(R.string.export_notifications)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
NotificationExportTask notificationExportTask = new NotificationExportTask(NotificationsPreferenceFragment.this.getActivity(), 1);
notificationExportTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return true;
}
});
}
}
I am getting the following exception:
java.lang.IllegalStateException: Fragment NotificationsPreferenceFragment{416092f8} not attached to Activity
at android.app.Fragment.getResources(Fragment.java:741)
at android.app.Fragment.getString(Fragment.java:763)
Can someone please explain to me why this is happening and suggest ways to fix this issue?
UPDATE:
Here is the code for the Activity:
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
}
Since you are performing background task in your app. there is no guarantee that user will stay on same screen until task finishes so if user navigates to other screen or presses home button before task is completed; your fragment is detached from activity. So always make sure that you have fragment attached with the Activity.
try checking with
if (isAdded) {
//Do your UI stuff here
}
add above check wherever you get callback
Move your code from onCreate to onActivityCreated instead of trying to getActivity # onCreate.
That's because the fragment can be created when the activity is not yet ready, that's when you are trying to use it.
That is of course if you are adding the fragment to an activity like:
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(android.R.id.content, new PreferenceFragment()).commit();

Categories

Resources