Application cannot be cast to android.app.Activity while checking permission - java

I am creating a call application i created an adapter for Recycler view on requesting CALL_PHONE there is showing the error
E/AndroidRuntime: FATAL EXCEPTION: main Process: in.welcomeyou.merchant, PID: 14890 java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
#Override
public void onBindViewHolder(EnquiryViewHolder holder, int position) {
Enquiry enquiry = enquiryList.get(position);
holder.domainTextView.setText(enquiry.getDomain());
holder.nameTextView.setText(enquiry.getName());
holder.commentsTextView.setText(enquiry.getComments());
holder.dateTextView.setText(enquiry.getDate());
holder.callBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ActivityCompat.checkSelfPermission(mCtx, CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CALL_PHONE},
Constants.CALL_PHONE);
return;
}
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:123456"));
mCtx.startActivity(intent);
}
});
}

Where you are passing context to this adapter use ActivityName.this or this .
Maybe now you passed
getApplicationContext();
And you get this exception because you can not cast the Application to Activity because Application is not a sub-class of Activity.

Please write this as below
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:123456"));
((YourActivityName)mContext).startActivity(intent);

Related

I have a problem when I try to use a variable from a getStringArrayListExtra()

When I use getStringArrayListExtra() to transport a variable from SecondActivity to the MainActivity, and when I use the variable, my app always crash. This is the code where there is a problem :
in MainActivity :
List<String> maSuperlist= getIntent().getStringArrayListExtra("tag");
System.out.println(maSuperlist);
//TextView DisplayList;
//DisplayList = (TextView) findViewById(R.id.DisplayListt);
//DisplayList.setText(maSuperlist.toString());
CharSequence[] testlist= maSuperlist.toArray(new CharSequence[maSuperlist.size()]);
//Toast.makeText(getApplicationContext(),testlist,Toast.LENGTH_SHORT).show();
}
}
in SecondActivity :
super.onCreate(savedInstanceState);
setContentView(R.layout.second_main);
ArrayList tag = new ArrayList();
EditText edit;
Button button;
Intent intent = new Intent(getBaseContext(), SecondActivity.class);
intent.putStringArrayListExtra("tag", tag);
edit = (EditText) findViewById(R.id.edit);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = edit.getText().toString();
tag.add(name);
Toast.makeText(getApplicationContext(), tag.toString(), Toast.LENGTH_SHORT).show();
}
});
Button button2;
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(intent);
}
});
Button button3;
button3 = (Button) findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent retourgameActivity = new Intent(SecondActivity.this, MainActivity.class);
startActivity(retourgameActivity);
}
});
}
}
Thank you so much for your help !
EDIT:
This is the error log (logcat):
021-06-24 15:43:16.734 11451-11451/fr.apprentissage.version2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: fr.apprentissage.version2, PID: 11451
java.lang.RuntimeException: Unable to start activity ComponentInfo{fr.apprentissage.version2/fr.apprentissage.version2.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3782)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3961)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2386)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at fr.apprentissage.version2.MainActivity.onCreate(MainActivity.java:158)
at android.app.Activity.performCreate(Activity.java:8086)
at android.app.Activity.performCreate(Activity.java:8074)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1313)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3755)
You are starting MainActivity from SecondActivity without any extras.
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent retourgameActivity = new Intent(SecondActivity.this, MainActivity.class);
//add arraylist here in intent
retourgameActivity .putStringArrayListExtra("tag", tag);
startActivity(retourgameActivity);
}
});
//in your second activity ,make sure you have extras in intent.
if(getIntent!=null && getIntent().getStringArrayListExtra("tag")!=null){
List<String> maSuperlist= getIntent().getStringArrayListExtra("tag");
System.out.println(maSuperlist);
//TextView DisplayList;
//DisplayList = (TextView) findViewById(R.id.DisplayListt);
//DisplayList.setText(maSuperlist.toString());
CharSequence[] testlist= maSuperlist.toArray(new CharSequence[maSuperlist.size()]);
//Toast.makeText(getApplicationContext(),testlist,Toast.LENGTH_SHORT).show();
}}
You are initiating an arraylist and before populating list you are sending it to your MainActivity.So you are passing null list to MainActivity. You should pass your list to other activity on button click.
Just do this inside your button3 listener:
Intent retourgameActivity = new Intent(MainActivity.this, SecondActivity.class);
retourgameActivity.putStringArrayListExtra("tag", tag);
startActivity(retourgameActivity);
Remove
retourgameActivity.putStringArrayListExtra("tag", tag);
from here
Intent intent = new Intent(getBaseContext(), SecondActivity.class);
intent.putStringArrayListExtra("tag", tag);
Good Practices:
Always put null check before sending arraylist to other activity and also check null before using arraylist.size() or getting some indexes of arralist.

Trying to seperate OnClickListener() to another class

I'm trying to create an onClickListener for another class, but there's a NullPointerException. I already tried to pass the value of context, but still, it didn't work. I don't know what value is null.
This is the class for ExternalOnClickListener
public class ExternalOnClickListener implements View.OnClickListener{
private Context context;
public ExternalOnClickListener(Context c) {
context = c;
}
public void setRowCol(Intent hardLevelIntent) {
hardLevelIntent.putExtra("rowCount", 6);
hardLevelIntent.putExtra("colCount", 6);
hardLevelIntent.putExtra("difficulty", 3);
}
#SuppressLint("NonConstantResourceId")
#Override
public void onClick(View v) {
//Hard levels intent
Intent hardLevelIntent = new Intent(context, GameActivity.class);
setRowCol(hardLevelIntent);
switch (v.getId()) {
case R.id.btnBack:
Intent intent = new Intent(context, Level_Selection.class);
context.startActivity(intent);
break;
case R.id.btnHard1:
hardLevelIntent.putExtra("hardStageCount", 1);
context.startActivity(hardLevelIntent);
break;
}
}
}
And the btnEndless.onClickListener() here is trying to create an object for the external onClick. But there's a null pointer exception
public class Level_Selection extends AppCompatActivity {
ImageButton btnBack, btnEasy, btnAverage, btnHard, btnEndless;
ImageButton btnHard1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level__selection);
this.btnBack = findViewById(R.id.btnBack);
this.btnEasy = findViewById(R.id.btnEasy);
this.btnAverage = findViewById(R.id.btnAverage);
this.btnHard = findViewById(R.id.btnHard);
this.btnEndless = findViewById(R.id.btnEndless);
this.btnHard1 = findViewById(R.id.btnHard1);
btnBack.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), Menu.class);
startActivity(intent);
});
btnEasy.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), Level_Easy.class);
startActivity(intent);
});
btnAverage.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), Level_Average.class);
startActivity(intent);
});
btnHard.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), Level_Hard.class);
startActivity(intent);
});
btnEndless.setOnClickListener(v -> {
btnHard1.setOnClickListener(new ExternalOnClickListener(getApplicationContext()));
btnHard1.performClick();
});
}
This is the error.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.flip, PID: 10862
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.flip.Level_Selection.lambda$onCreate$4$Level_Selection(Level_Selection.java:59)
at com.flip.-$$Lambda$Level_Selection$EhORL8AmJ4WhZjndwpPfbUXg1uA.onClick(Unknown Source:2)
at android.view.View.performClick(View.java:6312)
at android.view.View$PerformClick.run(View.java:24811)
at android.os.Handler.handleCallback(Handler.java:794)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:6651)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
I hope someone answers my question. Thanks in advance!
Try check btnHard1 value, is it null?
Make sure there is ImageButton with id 'btnHard1' in your activity_level__selection layout.
Seems like your R.layout.activity_level__selection, doesn't containt of button which you set click listener or has different id

ActivityNotFoundException: No Activity found to handle Intent { (has extras) }

I have an activity, let's call it MainActivity which has an SomeAdapter.
In the adapter's code I have
#Override
public void onBindViewHolder(#NonNull OptionViewHolder holder, final int position) {
final Option o = values.get(position);
holder.textView.setText(o.getOption());
holder.foreGround.setBackgroundColor(o.getOptionLayout().getBackGroundColor());
holder.editOptionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("option",o);
context.startActivityForResult(intent,1);
}
});
}
When actually clicking the editOptionButton, I get the following stack trace
Process: com.company.app, PID: 20916
android.content.ActivityNotFoundException: No Activity found to handle Intent { (has extras) }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2007)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1673)
at android.app.Activity.startActivityForResult(Activity.java:4586)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
at android.app.Activity.startActivityForResult(Activity.java:4544)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
at com.company.app.adapters.OptionsAdapter$1.onClick(OptionsAdapter.java:86)
the context that calls startActivityForResult is the MainActivity and is not null and alive (visible) at the time of calling because the adapter runs in it.
Therefor, I have no idea why this error pops up nor what I could do about it. Do any of you may know why or have experienced it before?
You have to include the Activity name like this
Intent intent = new Intent(context, SecondActivity.class);
intent.putExtra("option",o);
context.startActivityForResult(intent,1);
First
you are initlizing the intent in wrong way, you need init it as below:
Intent intent = new Intent(context, SecondActivity.class);
Second
If the result do not return to your MainActivity then you need to cast the context to activity before starting the second activity as:
((Activity) context).startActivityForResult(intent,1);
This means that intent doesn't know where to go. So give the context and the activity name where u want to go.
Intent intent = new Intent(getActivity(), SecondActivity.class);
intent.putExtra("Key",value);
startActvity(intent);

App crashes on Button Press stating "Attempt to invoke virtual method"

I have an android application which should opens an activity on button press, but when i click on itm the app crashes stating "Attempt to invoke virtual method". Here is my Code.
MainClass.java
public class MainActivity extends ActionBarActivity {
Button Notify;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Notify = (Button)findViewById(R.id.notify);
Notify.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, DisplayPush.class);
startActivity(intent);
}
});
}
My another activity class
DisplayPush.java
public class DisplayPush extends Activity {
#Override
public void onBackPressed(){
Intent myIntent = new Intent(DisplayPush.this,MainActivity.class);
startActivity(myIntent);
// overridePendingTransition(R.anim.from_middle, R.anim.to_middle);
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
TextView notification_title = (TextView) findViewById(R.id.title);
TextView notification_message = (TextView) findViewById(R.id.message);
ParseAnalytics.trackAppOpened(getIntent());
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String jsonData = extras.getString("com.parse.Data");
try{
JSONObject notification = new JSONObject(jsonData);
// String title = notification.getString("push_hash");
String message = notification.getString("alert");
// notification_title.setText(title);
notification_message.setText(message);
}
catch(JSONException e){
Toast.makeText(getApplicationContext(), "Something went wrong with the notification", Toast.LENGTH_SHORT).show();
}
}
I have defined the acitivities in my manifest.
Here is the logcat.
03-21 06:51:35.157: E/AndroidRuntime(3042): FATAL EXCEPTION: main
03-21 06:51:35.157: E/AndroidRuntime(3042): Process: hasan.parsereceiveandshow, PID: 3042
03-21 06:51:35.157: E/AndroidRuntime(3042): java.lang.RuntimeException: Unable to start activity ComponentInfo{hasan.parsereceiveandshow/hasan.parsereceiveandshow.DisplayPush}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
As in log:
Bundle.getString(java.lang.String)' on a null object reference
Because extras is null.
Not sending Bundle which contain com.parse.Data key with Intent which is used for starting DisplayPush Activity on Button Click.
What should i edit in code ?
Send data with com.parse.Data key in Intent on Notify Button click:
Intent intent = new Intent(MainActivity.this, DisplayPush.class);
intent.putExtra("com.parse.Data","String text");
startActivity(intent);
And also add null check before getting values from Bundle:
if(extras !=null)
if(extras.containsKey("com.parse.Data"))
String jsonData = extras.getString("com.parse.Data");
And define String jsonData; globally as said in comments.
The exception says that you're trying to call getString method on null reference. In DisplayPush you are getting Bundle object from intent which is null, because you didn't put any in your intent in onClick method in MainActivity class.

Error using onClickListener (Intent)

Well, I'm trying to create an intent on a "login.java" the code is :
Button btEntrar = (Button) findViewById(R.id.btnSingIn);
btEntrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i;
i = new Intent(this, MainActivity.class);
startActivity(i);
}
});
But it says that I can't go to the other activity saying this :
Error:(24, 21) error: no suitable constructor found for Intent(,Class)
constructor Intent.Intent(String,Uri) is not applicable
(argument mismatch; cannot be converted to String)
constructor Intent.Intent(Context,Class) is not applicable
(argument mismatch; cannot be converted to Context)
and...
Error:Execution failed for task ':app:compileDebugJava'.
Compilation failed; see the compiler error output for details.
Just a few lines to explain the reason why this does not work in:
i = new Intent(this, MainActivity.class)
The intent is created inside another class, here an anonymous inner class OnClickListener. Thus this does not refer the instance of your Activity (or Context) as intended but the instance of your anonymous inner class OnClickListener.
So you should provide the correct context of your class.
i = new Intent(YourClassName.this, MainActivity.class)
use
if you want to send it from login.java to mainactivity.class use
Intent intent=new Intent(login.this,Mainactivity.class);
startActivity(intent);
updated code in to your activity
Button btEntrar = (Button) findViewById(R.id.btnSingIn);
btEntrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i;
i = new Intent(login.this, MainActivity.class);
startActivity(i);
}
});
try using
Intent i = new Intent(login.this, mainActivity.class);
hope this helps
Did you add manifest.xml or try this code ?
Intent i = new Intent(login.this,mainActivity.class);

Categories

Resources