Android: java.lang.IllegalStateException: Already attached - java

I'm developing an Android app to store personal info in SQLite database, withdraw them out and display the list in Activity.Actually,the moment users have put data into database and returned to Activity,the page must be refreshed to upgrade the list with something new data.I used the statementonCreate(null) to make it,but an exception came into being:java.lang.IllegalStateException: Already attached.
Here is the code :
/* MainActivity */
public class MainActivity
extends AppCompatActivity
implements View.OnClickListener{
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==0x1&&resultCode==RESULT_OK){
onCreate(null); // Upgrade the list
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addItem=(Button)findViewById(R.id.addItem);
addItem.setOnClickListener(this);
.....
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.addItem:
Intent intent=new Intent(this,AddItemActivity.class);
startActivityForResult(intent,0x1);
break;
default:
break;
}
}
}
/*AddItemActivity*/
public class AddItemActivity
extends AppCompatActivity
implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
Button submit=(Button)findViewById(R.id.submit);//get submit button
submit.setOnClickListener(this);
....
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.submit:
EditText editName=(EditText)findViewById(R.id.editName),
editAge=(EditText)findViewById(R.id.editAge);
insert(new Person(
editName.getText().toString(),
Integer.parseInt(editAge.getText().toString())));
//return
setResult(RESULT_OK,null);
finish();
break;
default:
break;
}
}
}
stackTrace is this:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.sqlitetest/com.example.sqlitetest.MainActivity}: java.lang.IllegalStateException: Already attached
at android.app.ActivityThread.deliverResults(ActivityThread.java:4053)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.IllegalStateException: Already attached
at android.support.v4.app.FragmentManagerImpl.attachController(FragmentManager.java:2871)
at android.support.v4.app.FragmentController.attachHost(FragmentController.java:104)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:317)
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:85)
at com.example.sqlitetest.MainActivity.onCreate(MainActivity.java:29)
at com.example.sqlitetest.MainActivity.onActivityResult(MainActivity.java:23)
at android.app.Activity.dispatchActivityResult(Activity.java:6915)

Related

Error android java.lang.RuntimeException: Failure delivering result ResultInfo

I'm using the AppAuth library and trying to open the google website and go back to my activity (baseActivity) that calls a webview.
Basically i have a method that makes a call to open a webview page that i cannot put in the "OAuthJava" class, so I created an interface in the BaseActivity class, which I pass to the "OAuthJava" activity that makes the request for appAuth and after giving success uses the interface that is in the other activity to open the method that opens the webview
Error android : IlegalStateException: can not perform this action after onSaveInstance
#EActivity
public abstract class BaseActivity extends AppCompatActivity {
//code
private void test() {
//this builder is to create an intent to open the new activity and I pass this interface so that the next //activity can call the method that calls the webview
new OpenAppAuth.Builder()
.context(this)
.listener(new abc())
.build();
}
class abc implements RedirectInterface {
#Override
public void goToWebView() {
gotoScreen();
}
}
private void gotoScreen(String menuItem) {
//code that calls a webview screen
}
}
this class makes the call from the google site using appAuth
public class OAuthJava extends AppCompatActivity {
public static final int OAUTH_RC = 7777;
private RedirectInterface repository; // receives the abc class
#Override
public void onCreate(final Bundle icicle) {
// create the appauth request by opening google
Intent authIntent = authService.getAuthorizationRequestIntent(authRequest);
startActivityForResult(authIntent, OAUTH_RC);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == OAUTH_RC) {
AuthorizationResponse resp = AuthorizationResponse.fromIntent(data);
AuthorizationException ex = AuthorizationException.fromIntent(data);
if (resp != null) {
//success
//after I click on my email enter the "if" that calls goToWebView (interface abc)
repository.goToWebView();
}
}
}
error:
- beginning of crash
2021-04-01 18:52:58.729 9870-9870/com. E/AndroidRuntime: FATAL EXCEPTION: main
Process: com., PID: 9870
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=7777, result=-1, data=Intent { (has extras) }} to activity {com./br.o.commons.repository.OAuthJava}: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.app.ActivityThread.deliverResults(ActivityThread.java:4423)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4465)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
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:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
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:873)
Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at androidx.fragment.app.FragmentManager.checkStateLoss(FragmentManager.java:1832)
at androidx.fragment.app.FragmentManager.enqueueAction(FragmentManager.java:1872)
at androidx.fragment.app.BackStackRecord.commitInternal(BackStackRecord.java:329)
at androidx.fragment.app.BackStackRecord.commit(BackStackRecord.java:294)

How to use interface between two activities [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am passing my data from one activity to another activity via intent using a bundle.now this bundle is received by another activity here i am gonna display the values i passed.now when the a button is clicked it is suppose to fire a interface which has a function .There it is showing a null point error.
MainActivity.class
public class MainActivity extends AppCompatActivity implements WILO.Communicator {
int Tap=0,loss=9;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CountDowntimer();
}
public void CountDowntimer()
{
new CountDownTimer(3000, 1000) {
#Override
public void onTick(long millisUntilFinished)
{
Tap+=1;
loss-=2;
}
#Override
public void onFinish()
{
Bundle arg=new Bundle();
arg.putInt("Tap",Tap);
arg.putInt("Loss",loss);
Intent i=new Intent(getBaseContext(),WILO.class);
i.putExtras(arg);
startActivity(i);
}
}.start();
}
#Override
public void Restart()
{
CountDowntimer();
}
}
WILO.class
public class WILO extends Activity {
Communicator communicator;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wilo);
Bundle arg=getIntent().getExtras();
Button Restart;
TextView Tap,Loss;
Restart= (Button) findViewById(R.id.Restart);
Tap= (TextView) findViewById(R.id.Tap);
Loss= (TextView) findViewById(R.id.Loss);
Loss.setText(String.valueOf(arg.getInt("Loss")));
Tap.setText(String.valueOf(arg.getInt("Tap")));
Restart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
communicator.Restart();
finish();
}
});
}
interface Communicator
{
public void Restart();
}
}
Error
FATAL EXCEPTION: main
Process: com.matrix.storm.question, PID: 27805
java.lang.NullPointerException
at com.matrix.storm.question.WILO$1.onClick(WILO.java:34)
at android.view.View.performClick(View.java:4452)
at android.view.View$PerformClick.run(View.java:18451)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5421)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:979)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:795)
at dalvik.system.NativeStart.main(Native Method)
How to use interface between two activities
You can not connect two activities using interfaces. If you want to send receive data between two activities, you can use the help of intent arguments and ActivityResult method.
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
startActivityForResult(intent, 2);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
}

How to play a video from gallery in Android?

I am trying to play a video from the gallery, but i can only reach the gallery.
I have a button and when i press it i am redirected to the gallery. I can see that there are videos, but when i press the video the application crashes.
This is the "On activity result".
public void onActivityResult(int requestCode,int resultCode,Intent data){
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == SELECT_PHOTO ) {
Uri mVideoURI = data.getData();
video_player_view.setMediaController(media_Controller);
video_player_view.setVideoURI(mVideoURI);
video_player_view.requestFocus();
video_player_view.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
video_player_view.start();
}
});
}
}
And this is "On Create"
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_camera = (Button)findViewById(R.id.btn_camera);
Button btn_arhiva = (Button)findViewById(R.id.btn_arhiva);
video_player_view = (VideoView)findViewById(R.id.video_player_view);
media_Controller = new MediaController(this);
media_Controller.setAnchorView(video_player_view);
btn_camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(intent,CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
}
});
btn_arhiva.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*,video/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
});
The Exception:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=199, result=-1, data=Intent { dat=content://media/external/video/media/39 }} to activity {licenta.licenta/licenta.licenta.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.VideoView.setMediaController(android.widget.MediaController)' on a null object reference`
I searched online and tutorials are made using a video from "Raw" directory. But i want it dynamically. If i record a video now, i want to be able to play it through the app.
Thank you!

Android: No Activity found to handle Intent (trying to add an activity to exsisting app)

Ok so I am very new to the Android programming, I am starting week 2 of this class and cannot for the life of me figure out what is going wrong. I have read/watched tons of tutorials on adding new Activities and nothing works.
Assignment: Use the Activities app and add a fourth activity
My activity is simple, 3 buttons and an image. One button makes the image visible and the other makes it invisible. Third returns back to the main.
Note: I edited the original app to have buttons on Main Activity because it had me hitting center on the d-pad which I found dumb. Another note is that Activity 2 & 3 use the same layout and do basically the same thing from what I can tell
public class MainActivity extends Activity {
String tag = "Events";
int request_Code = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//---hides the title bar---
//requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
Log.d(tag, "In the onCreate() event");
Button act2Butt = (Button) findViewById(R.id.act2Butt);
Button act3Butt = (Button) findViewById(R.id.act3Butt);
Button act4Butt = (Button) findViewById(R.id.act4Butt);
act2Butt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivityForResult(new Intent("net.learn2develop.ACTIVITY2"), request_Code);
}
});
act3Butt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivityForResult(new Intent("net.learn2develop.ACTIVITY2"), request_Code);
}
});
act4Butt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivityForResult(new Intent("net.learn2develop.MYACTIVITY"), request_Code);
}
});
}
/*
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
{
//startActivity(new Intent("net.learn2develop.ACTIVITY2"));
//startActivity(new Intent(this, Activity2.class));
startActivityForResult(new Intent(
"net.learn2develop.ACTIVITY2"),
request_Code);
}
return false;
}
*/
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == request_Code) {
if (resultCode == RESULT_OK) {
Toast.makeText(this,data.getData().toString(),
Toast.LENGTH_LONG).show();
}
}
}
public void onStart()
{
super.onStart();
Log.d(tag, "In the onStart() event");
}
public void onRestart()
{
super.onRestart();
Log.d(tag, "In the onRestart() event");
}
public void onResume()
{
super.onResume();
Log.d(tag, "In the onResume() event");
}
public void onPause()
{
super.onPause();
Log.d(tag, "In the onPause() event");
}
public void onStop()
{
super.onStop();
Log.d(tag, "In the onStop() event");
}
public void onDestroy()
{
super.onDestroy();
Log.d(tag, "In the onDestroy() event");
}
public class MyActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity4);
Button yesButt = (Button) findViewById(R.id.yesButton);
Button noButt = (Button) findViewById(R.id.noButton);
Button finButt = (Button) findViewById(R.id.finButton);
final ImageView img1 = (ImageView) findViewById(R.id.image1);
yesButt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
img1.setVisibility(View.VISIBLE);
}
});
noButt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
img1.setVisibility(View.INVISIBLE);
}
});
finButt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent data = new Intent();
data.setData(Uri.parse("OMG IT WORKS"));
setResult(RESULT_OK, data);
finish();
}
});
}
public class Activity2 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
String defaultName="";
Bundle extras = getIntent().getExtras();
if (extras!=null)
{
defaultName = extras.getString("Name");
}
//---get the EditText view---
EditText txt_username =
(EditText) findViewById(R.id.txt_username);
txt_username.setHint(defaultName);
//---get the OK button---
Button btn = (Button) findViewById(R.id.btn_OK);
//---event handler for the OK button---
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view) {
Intent data = new Intent();
//---get the EditText view---
EditText txt_username =
(EditText) findViewById(R.id.txt_username);
//---set the data to pass back---
data.setData(Uri.parse(
txt_username.getText().toString()));
setResult(RESULT_OK, data);
//---closes the activity---
finish();
}
});
}
I have entered the code for Main Activity, My Activity (the one I made), and Activity 2. My Activity runs great and does exactly what I want it to but if I try to access it from main it dies.
928-928/net.learn2develop.Activities E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: net.learn2develop.Activities, PID: 928
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=net.learn2develop.MYACTIVITY }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1765)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1485)
at android.app.Activity.startActivityForResult(Activity.java:3736)
at android.app.Activity.startActivityForResult(Activity.java:3697)
at net.learn2develop.Activities.MainActivity$3.onClick(MainActivity.java:48)
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)
This code is for my last attempt and making it work before throwing my hands up. Last thing I did was make My Activity act like the other and use startActivityForResult.
Any help would help greatly. I don't know if it matters or not but I do not have a .class for My Activity in the bin directory but there is one for all the others.
If you need any more info please just ask.
Like I said before I'm really new to the whole Android area.
Edit: Manifest
<activity android:name=".MyActivity"
android:label="My Activity">
<intent-filter>
<action android:name="net.learn2develop.MYACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
You may need to add the Activity to the manifest. If you are sure you have done this, I would recommend using an Intent slightly differently.
Try using an Intent the following way:
Intent intent = new Intent(MyActivity.this, SecondActivity.class);
startActivityForResult(intent, requestCode);
The first parameter of this Intent is the current Activity. The second parameter is theActivity you wish to navigate to. Handling an Intent this way prevents a small typo in the package name which would throw that exception. As long as the Activity you are trying to navigate to is in the manifest and you have set up your Intent like the code above, everything should work fine.
Good luck and happy coding!
you need to add your activity to your manifest
<activity
android:name=".MySecondActivity"
android:label="#string/title_second_activity">
</activity>
net.learn2develop.MYACTIVITY
Android is not finiding the above activity like other engineers said,add this activity in your manifest file so JVM can find which class you are referring to.

Converting String to int from intent

I have 2 activities, and I'm passing edit number editText data to 2nd activity with intent. But in second activity I can't convert data from String to int with any functions. Here is my code:
This is main function:
public class MainActivity extends ActionBarActivity {
public EditText mAge;
public Button mCalculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAge = (EditText) findViewById(R.id.numberImputEditText);
mCalculate = (Button) findViewById(R.id.calculateButton);
mCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String age = mAge.getText().toString();
Intent mIntent = new Intent(getApplicationContext(),FinalActivity.class);
mIntent.putExtra("age", age);
startActivity(mIntent);
}
});
}
}
and this is 2nd activity where is data passed:
public class FinalActivity extends Activity {
public Button mCalculateAgain;
public TextView mMinAge;
public TextView mMaxAge;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final);
Intent mIntent = getIntent();
String age = mIntent.getStringExtra("age");
mCalculateAgain = (Button) findViewById(R.id.calculateAgainButton);
mMinAge = (TextView) findViewById(R.id.minAgeTextView);
mMaxAge = (TextView) findViewById(R.id.maxAgeTextView);
Integer i = Integer.parseInt(age);
mMinAge.setText((i/2)+7);
mMaxAge.setText((i-7)*2);
Toast.makeText(getApplicationContext(), age, Toast.LENGTH_LONG).show();
mCalculateAgain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mIntent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(mIntent);
}
});
}
}
here's the log:
`java.lang.RuntimeException: Unable to start activity ComponentInfo{com.robigroza.halfyourage/com.robigroza.halfyourage.FinalActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x12
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2114)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2139)
at android.app.ActivityThread.access$700(ActivityThread.java:143)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4960)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x12
at android.content.res.Resources.getText(Resources.java:1058)
at android.widget.TextView.setText(TextView.java:3857)
at com.robigroza.halfyourage.FinalActivity.onCreate(FinalActivity.java:35)
at android.app.Activity.performCreate(Activity.java:5203)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2078)
There's a few types of TextView.setText(...). One takes a CharSequence, which is probably what you expected to use, and another commonly used variant takes an int. The int form expects the parameter to be a resource ID.
mMinAge.setText((i/2)+7);
mMaxAge.setText((i-7)*2);
Given that (i/2)+7 isn't likely to resolve to a string resource, you could do:
mMinAge.setText("" + (i/2)+7);
mMaxAge.setText("" + (i-7)*2);
or better:
mMinAge.setText(String.valueOf((i/2)+7));
mMaxAge.setText(String.valueOf((i-7)*2));
Use this code in MainActivity.java
int age = Integer.parseInt(mage.getText().toString());
Intent i = new Intent(MainActivity.this,FinalActivity.class);
i.putExtra("age", age);
startActivity(i);
Code for FinalActivity .java
Bundle extras = getIntent().getExtras();
int age = extras.getInt("age");
In this way you can send integer value to other activity.
EnJoY coding :)

Categories