Call a Context within a class for a different activity - java

I am checking for SEND_SMS permission within a class:
public class SendSms extends Activity{
int requestPerm;
private void checkPermissionSms(){
if(ContextCompat.checkSelfPermission(, Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS},
requestPerm); //If we don't have the permission, request it here
}
}
But at checkSelPermission, it needs a context but I'm not sure what context it needs(not even too sure what Context for checkSelfPermission)
I am following:
https://developer.android.com/training/permissions/requesting.html#java
The above method is called like so:
public static void sendSms(String message){
// Intent calledSendSMS = getIntent();
//String message = calledSendSMS.getStringExtra(Intent.EXTRA_TEXT);
// PendingIntent pi = PendingIntent.getActivity(this,0, new Intent(this,SendSms.class),0);
SendSms checkPerm = new SendSms();
SmsManager sendTheMessage = SmsManager.getDefault();
String phoneNumber = "5556";
checkPerm.checkPermissionSms();
sendTheMessage.sendTextMessage(phoneNumber, null,message,null,null);
}
And this Method is called from another activity.
I did put in "this" but then I get the following error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.checkPermission(java.lang.String, int, int)' on a null object reference
at android.content.ContextWrapper.checkPermission(ContextWrapper.java:724)
at android.support.v4.content.ContextCompat.checkSelfPermission(ContextCompat.java:430)
at com.example.android.footysortit.SendSms.checkPermissionSms(SendSms.java:17)
Really all I want to do is check for permission and request it if needed.
Edit: If I add the check permissions within an actual activity and use "this" it works just fine.
So how do I get it to pass the activity data?

Change this:
SendSms checkPerm = new SendSms();
To:
SendSms checkPerm = new SendSms(this);
SendSms class - you need to create constuctor of the class
public class SendSms extends Activity {
private Activity mActivity;
private int requestPerm;
public SendSms(Activity mActivity) {
this.mActivity = mActivity;
}
private void checkPermissionSms() {
if (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, requestPerm);
//If we don't have the permission, request it here
}
}
}

Related

How to move reusable functionalities to a generic class and invoke another activity from there?

I am new to Android development and I am facing an issue in invoking an activity from a generic class where I have a reusable function.
I have MainActivity where I need to check if the application has Network connectivity and then check if the user is already signed in.
If the user is signed in I need to open the Rate activity otherwise I will open the Login activity.
I thought I can keep the logic that checks the Network connectivity and shows the popup reusable and move it to a Global class as below
public class Global extends AppCompatActivity {
public static boolean hasConnectivity = false;
public static boolean userSignedIn = false;
String TAG = "Debug Log - Helper";
Context context;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
context = this;
}
private void networkConnectionErrorDialog(final Context context, final Class targetClass){
Log.d(TAG, "Show Alert Dialog");
new AlertDialog.Builder(context)
.setTitle(R.string.connection_error_title)
.setMessage(R.string.connection_error_message)
.setIcon(R.drawable.warning)
.setPositiveButton(
R.string.try_again,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "Trying Again");
isNetworkAvailable(context, targetClass);
}
}).show();
}
protected void isNetworkAvailable(Context context, Class targetClass) {
if(NetworkUtil.isConnected(context)){
Log.d(TAG, "Has connectivity");
if(targetClass != null){
Log.d(TAG, targetClass.toString());
Intent targetIntent = new Intent(context, targetClass);
startActivity(targetIntent);
}
hasConnectivity = true;
return;
}else{
Log.d(TAG, "Has no connectivity");
hasConnectivity = false;
networkConnectionErrorDialog(context, targetClass);
}
}
}
I pass in the targetClass as Login.class or Rate.class (based on user signed in state) from the MainActivity where isNetworkAvailable() is invoked.
I am getting the following error. Could someone help me fix the issue and help me understand if my approach needs improvement?
java.lang.RuntimeException: Unable to resume activity {com.solitontech.dayatsoliton/com.solitontech.dayatsoliton.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3581)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3621)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2862)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.Activity.startActivityForResult(Activity.java:4488)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
at android.app.Activity.startActivityForResult(Activity.java:4445)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
at android.app.Activity.startActivity(Activity.java:4806)
at android.app.Activity.startActivity(Activity.java:4774)
at com.solitontech.dayatsoliton.Global.isNetworkAvailable(Global.java:50)
at com.solitontech.dayatsoliton.MainActivity.onResume(MainActivity.java:68)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1355)
at android.app.Activity.performResume(Activity.java:7117)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3556)
It looks like your application is experiencing a null pointer exception in your activity's onResume method. If you had called startActivityForResult, make sure that the data in
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{..}
is non null before processing it.
As for your question about starting an activity from your helper class Global, you can define a function like this.
private static void goToActivity(Context context, Class<?> activityClass){
Intent intent = new Intent(context, activityClass);
context.startActivity(intent);
}
You can call this method as below.
goToActivity(context,TargetActivity.class);
Good luck.
Intent targetIntent = new Intent(context, targetClass);
startActivity(targetIntent);
above code is wrong. You should pass your current activity and target activity here.
Intent intent = new Intent(CurrentActivity.this, TargetingActivity.class);
startActivity(intent);
As a example :
If you want to start ActivtyB form ActivtyA
Intent intent = new Intent(ActivityA.this, ActivityD.class);
startActivity(intent);
1st try to correct this error. then you can find some others.

Can't ask permission at runtime (Android)

I am following a video on Lynda.com and i am trying to
request permissions at runtime. But i get this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.checkPermission(java.lang.String, int, int)' on a null object reference
at com.doppler.stackingcoder.pechhulp.PechhulpActivity.makeCall(PechhulpActivity.java:226)
Here is the method where the error appears:
public void makeCall() {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:09003344556"));
if (ActivityCompat.checkSelfPermission(
PechhulpActivity.this, Manifest.permission.CALL_PHONE) // Line 226 (Error)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(PechhulpActivity.this,
Manifest.permission.CALL_PHONE)) {
Toast.makeText(PechhulpActivity.this, "I know you said no, but I'm asking again", Toast.LENGTH_SHORT).show();
}
ActivityCompat.requestPermissions(PechhulpActivity.this,
new String[]{Manifest.permission.CALL_PHONE},
MY_PERMISSIONS_REQUEST_CALL_PHONE);
return;
}
startActivity(callIntent);
}
I hope someone knows why this error appears. Here is a gist of my full class:
https://gist.github.com/soufyanekaddouri/812f65669847619e3af7016403b1e7be
You are passing PechhulpActivity.this as the Context but it seems that this is actually a null reference.
I suggest trying to resolve the Context in some other way (i.e. getApplicationContext(), saving the Context as global variable etc...).
Here is an example of how to access your application context:
public class PechhulpActivity extends Activity{
Context mContext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getApplicationContext();
...
...
}
public static Context getContext(){
return mContext;
}
}

Android Retrofit "Attempt to invoke virtual method on a null object reference"

Hi first of all i searched some similar questions like mine but unfortunately i couldn't find the similarity of my code to them so please here me out
I have a Main Activity Class
public class MainActivity extends AppCompatActivity {
public ProgressDialog loading;
public String[] itemer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RetrofitHandler handler = new RetrofitHandler();
handler.getContacts(MainActivity.this);
}
public void getter(String[] response, int size) {
String[] itemer;
itemer = new String[size];
if (response != null) {
itemer = response;
Toast.makeText(MainActivity.this, itemer[0], Toast.LENGTH_SHORT).show();
}
}
And a Handler for my result
public class RetrofitHandler {
public String[] item;
public static final String ROOT_URL = "http://api.androidhive.info";
public List<Contacts> contacts;
// final MainActivity main = new MainActivity();
public void getContacts(final Context context) {
final ProgressDialog loading = ProgressDialog.show(context, "Fetching Data", "Please wait...", false, false);
RestAdapter adapter = new RestAdapter.Builder().setEndpoint(ROOT_URL).build();
ContactsAPI api = adapter.create(ContactsAPI.class);
api.getContacts(new Callback<Contacts>() {
#Override
public void success(Contacts contacts, Response response) {
loading.dismiss();
MainActivity update = new MainActivity();
List<Contact> contactList = contacts.getContacts();
item = new String[contactList.size()];
int size = contactList.size();
for (int i = 0; i < contactList.size(); i++) {
item[i] = contactList.get(i).getName();
}
update.getter(item, size);
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(context, "Error Occured", Toast.LENGTH_LONG).show();
}
});
}
But I get an error on my response in the main activity here is my log
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at android.support.v7.app.AppCompatActivity.getResources(AppCompatActivity.java:542)
at android.widget.Toast.<init>(Toast.java:102)
at android.widget.Toast.makeText(Toast.java:259)
at com.exist.kelvs.retrofit2.MainActivity.getter(MainActivity.java:55)
at com.exist.kelvs.retrofit2.RetrofitHandler$1.success(RetrofitHandler.java:41)
at com.exist.kelvs.retrofit2.RetrofitHandler$1.success(RetrofitHandler.java:28)
at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I maked sure that the handler item where not null tested it with toast but when i pass it to getter it gives me the error where did i do wrong? :(
MainActivity update = new MainActivity();
Never instantiate activities with new. They are not initialized to be useful.
Instead, you can pass your activity as a reference where needed. Change
public void getContacts(final Context context)
to e.g.
public void getContacts(final MainActivity mainActivity)
and use mainActivity where you need an activity Context (such as with Dialogs) and when you need to invoke a method on MainActivity.
Note that generally passing activity references to async operations can be prone to significant memory leaks, and you need to take activity lifecycle into account - the activity might not be active when the async operation finishes.
try to delete the toast in your main activity or replace Mainactivity.this to getApplicationContext() .
from :
Toast.makeText(MainActivity.this, itemer[0], Toast.LENGTH_SHORT).show();
to :
Toast.makeText(getApplicationContext(), itemer[0], Toast.LENGTH_SHORT).show();

Can I attach and then retrieve my own class descending from android.os.ResultReceiver to an Intent?

I'm trying to make a class that extends Android's ResultReceiver for use with a custom IntentService. The problem is that when I try to attach my receiver to an Intent using putExtra and then retrieve it in onHandleIntent that I am unable to cast it to the child class. A simple code example can be seen here.
public class MyReceiver extends ResultReceiver {
public JSONReceiver(Handler handler) {
super(handler);
}
}
public class MyService extends IntentService {
private static final String EXTRA_RECEIVER = "com.myname.extra.receiver";
protected static void sendIntent(Context context, MyReceiver receiver) {
Intent intent = new Intent(context, MyService.class);
intent.putExtra(EXTRA_RECEIVER, receiver);
//outputs com.myname.MyReceiver
Log.i("type", receiver.getClass().getName());
//outputs com.myname.MyReceiver
Log.i("type", intent.getParcelableExtra(EXTRA_RECEIVER).getClass().getName());
context.startService(intent);
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final Parcelable parcelable = intent.getParcelableExtra(EXTRA_RECEIVER);
//outputs android.os.ResultReceiver
Log.i("type", parcelable.getClass().getName());
//results in a casting error
final MyReceiver receiver = (MyReceiver) parcelable;
}
}
}
It seems that the retrieval works as expected before calling startService so something must be happening between that and onHandleIntent being called that changes what the receiver is an instance of. I'm curious why/how this is happening and also if it is possible to achieve what I'm trying to accomplish here. Thanks!

Error Receiving broadcast Intent notification

I'm getting this error in log cat when i receive a notification but not always. Seems that sometimes the String i want pass and display in a toast results null but not always. The error is this as from title:
java.lang.RuntimeException: Error receiving broadcast Intent { act=it.dd.notification flg=0x10 (has extras) }
--
--
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x7f04006b
--
at it.dd.notification.Main$2.onReceive(Main.java:417)
--
i can't post all logCat because i don't have Eclipse here. I remember this parts that are what i need to understand the problem.
I declared these first in MainActivity:
//private String dir;
protected MyReceiver mReceiver = new MyReceiver();
public static String INTENT_ACTION_NOTIFICATION = "it.dd.notification";
private String titoloNoti;
private String contenutoNoti;
//
Always in MainActivity i have this BroadcastReceiver:
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
Bundle extras = intent.getExtras();
String notificationTitle = extras.getString(Notification.EXTRA_TITLE);
CharSequence notificationText = extras.getCharSequence(Notification.EXTRA_TEXT);
contenutoNoti = notificationText.toString(); //Line 417
Toast loc = Toast.makeText(getApplicationContext(), contenutoNoti, Toast.LENGTH_SHORT);
loc.show();
}
}
}
So when i intercept a notification it crashes. But, i repeat, not always. Sometimes when it wants and it's so frustrating!! Have you any ideas?

Categories