putExtra(), getStringExtra() - why it does not work? - java

I suspect there is only some stupid mistake, but I'm stuck. The problem is simple: my String path is not send to MainActivity.
Creating intent in FileListActivity.class
intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("path", fileName);
Toast.makeText(this, fileName + " set to play!", Toast.LENGTH_SHORT).show();
startActivity(intent);
Receiving intent in MainActivity.class
protected void onResume(){
super.onResume();
Toast.makeText(this, "path set" + getIntent().getStringExtra("path"), Toast.LENGTH_SHORT).show();
if(getIntent().hasExtra("path")) try {
mediaPlayer.setDataSource(this, Uri.parse(getIntent().getStringExtra("path")));
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
Toast in FileListActivity shows right filename. In MainActivity it is null.

Try overriding protected void onNewIntent (Intent intent) in MainActivity as follows...
#Override
protected void onNewIntent (Intent intent) {
setIntent(intent);
}
Relaunching MainActivity using Intent.FLAG_ACTIVITY_SINGLE_TOP and calling getIntent() in the MainActivity onResume() method won't get the new Intent and it simply gets the original Intent which won't have your path extra.
By overriding onNewIntent(...) and using it to call setIntent(...), the new Intent overwrites the original one and the call to getIntent() in onResume() should get the correct data.

getStringExtra() returns null if the value passed to putExtra() was not a String object.
Judging by the comments to the question, this is not the answer in this specific case. However, it is worth mentioning because this is a very common cause for the problem "putExtra(), getStringExtra() - why it does not work?"

You can try in this way in MainActivity:
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle pathBundle=getIntent().getExtras();
if(pathBundle!=null)
{
String myPath=pathBundle.getString("path");
}
}
And In onResume method
protected void onResume()
{
super.onResume();
try
{
mediaPlayer.setDataSource(this, Uri.parse(myPath)); // Dont forget to declare myPath String globally.
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
Hope this resolves your problem..

Related

How to start same Activity with new data when android:launchMode="singleInstance"?

I am trying to do it like :
startActivity(new Intent(ActivityRating.this, ActivityRating.class).putExtra("Type", AppConstant.PRODUCT_REVIEW).putExtra("Id", review.getId()).putExtra("paramStore", mVendor));
finish();
Activity close but it didn't open again? with this code.
I found the Solution
Intent intent = new Intent(ActivityRating.this, ActivityRating.class).putExtra("Type", AppConstant.PRODUCT_REVIEW).putExtra("Id", review.getId()).putExtra("paramStore", mVendor);
finish();
startActivity(intent);
implement this method
#Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
super.onNewIntent(intent);
}

How to open browser in android app?

i'm doing a project where i have to call a browser via my android app, but when i call it, the app stops.
the code can be found here: https://github.com/coppetti/android-pulsometer
but for fast view, i have a "Pulsometro" class where
public void onPreviewFrame(byte[] data, Camera cam) {
...
Browser browser = new Browser();
browser.callBrowser(beats);
return;
...
}
and a Browser class where:
public class Browser extends Activity{
public void callBrowser(int beats){
String url = "http://www.higia.info/?q="+beats;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
return;
}
}
There's a way to call a browser and my app doesn't breaks?
Try this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onOpenWebBrowser(View v)
{
Intent webPageIntent = new Intent(Intent.ACTION_VIEW);
webPageIntent.setData(Uri.parse("https://www.google.co.in/"));
try {
startActivity(webPageIntent);
} catch (ActivityNotFoundException ex) {
}
}
Do not just randomly choose superclasses. Do not just create some subclass of Activity and expect it to work.
Move your callBrowser() method into some real Activity implementation, and get rid of Browser entirely.
Or, remove the superclass from Browser, have callBrowser() take a Context as a parameter, and call startActivity() on that Context.
Try this class. Call the callBrowser method and give it and Activity for the context parameter.
public class Browser{
public void callBrowser(Context context, int beats){
String url = "http://www.higia.info/?q="+beats;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
context.startActivity(i);
}
}

Calling another activity from AsyncTask

I'm new to android and I have a problem with this code. I'm trying to get a JSON String and start another activity to display it as a ListView.
I'm not able to start the activity. It says that the The constructor Intent(RequestJsonString, Class) is undefined and The constructor Intent(RequestJsonString, Class) is undefined .
Here:
Intent intent = new Intent(RequestJsonString.this,DisplayResults.class);
and Here:
RequestJsonString.this.startActivity(intent);
I have read many posts on this on stackoverflow and tried with activity, context and this. But still I'm not getting it right. I think I should be missing something. Any help is appreciated.
public class RequestJsonString extends AsyncTask<String, Void, JSONObject> {
#Override
protected JSONObject doInBackground(String... urls) {
// Code HTTP Get Request and get JSONObject
return jsonObject;
}
protected void onPostExecute(JSONObject jsonObj){
try {
Intent intent = new Intent(RequestJsonString.this,DisplayResults.class);
intent.putExtra("JSON_Object", jsonObj.toString());
RequestJsonString.this.startActivity(intent);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("Json_OutPut","Done");
}
}
To start the activity from AsyncTask.
Intent intent = new Intent(YourActivityName.this,DisplayResults.class);
or you can do same like below.
Declare the context instance variable and initialize it in onCreate method.
private Context context;
public void onCreate(Bundle bundle) {
............
context = this;
........
}
Start the activity like this.
Intent intent = new Intent(context,DisplayResults.class);
intent.putExtra("JSON_Object", jsonObj.toString());
startActivity(intent);
In your case you are referring to asynctask class context
Intent intent = new Intent(RequestJsonString.this,DisplayResults.class);
Use a Activity Context
Intent intent = new Intent(ActivityName.this,DisplayResults.class);
Check the link to know when to use getApplicationContext() and when to use Activity Context
When to call activity context OR application context?
Edit:
Pass the Activity context to the asynctask constructor
new RequestJsonString(ActivityName.this).execute(params..);
In your asynctask constructor
Context c;
public RequestJsonString( Context context)
{
c= context;
}
Then
Intent intent = new Intent(c,DisplayResults.class);
startActivity(intent);

How To Return To The Main Activity After Destroying A SurfaceView?

My Activity
protected void onDestroy(){
super.onDestroy();
finish();
}
public void onPause(){
super.onPause();
gv.gameLoopThread.setRunning(false);
finish();
}
public void redirectHome(){
onDestroy();
Intent intent=new Intent(PlayActivity.this, MainActivity.class);
startActivity(intent);
}
My View's On Click.
if(gameover){
//My Restart Button.
if(x>(getWidth()*.39375) && x<(getWidth()*.625) &&
y>(getHeight()*.583333333) && y<(getHeight()*.654166667)){
gameover=false;
createSprites();
destroyed=0;
}
//My Exit Button.
if(x>(getWidth()*.39375) && x<(getWidth()*.625) &&
y>(getHeight()*.729166667) && y<(getHeight()*.791666667)){
gameLoopThread.setRunning(false);
new PlayActivity().redirectHome();
}
}
My restart button works, but my exit button causes my app to crash pointing the error at 'Intent intent=new Intent(PlayActivity.this, MainActivity.class);' and 'new PlayActivity().redirectHome();
Any help is appreciated.
You do nt must ot call "OnDestroy()" callback directly and also to call finish() in onDestroy() method.
In your case it would be better to change your code like to something like this:
protected void onDestroy(){
super.onDestroy();
}
public void onPause(){
super.onPause();
gv.gameLoopThread.setRunning(false);
}
public void redirectHome(){
Intent intent=new Intent(PlayActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
Also one question: is this thing is really worked somehow? I'm asking this because finish() call in onPause() callback should close your activity even before it appears on the screen.
Anyway, check my code and comment about results)
EDIT: also you can't actually create instance of activity and call on of it's methods like new PlayActivity().redirectHome(); so you need a context of Аctivity to perform start of new activity or finish this one.
It seems that because you can onDestroy the activity reference PlayActivity.this becomes invalid or null
You can use the application context instead of PlayActivity.this to and start your activity with FLAG_ACTIVITY_NEW_TASK

Android - New Intent starts particular method

I want to start one of my existing activities and force the activity to call a specific method after it starts. Is this possible?
Can I define a method that should be called after creating the activity inside my Intent?
For example, something like:
Intent intent = new Intent(this, com.app.max.Home.class.myMethod);
No, I don't think you can have something like this:
Intent intent = new Intent(this, com.app.max.Home.class.method);
but you can do this:
Intent intent = new Intent(this, com.app.max.Home.class);
intent.putExtra("methodName","myMethod");
startActivity(intent);
and then in the called activity (where you need to start the method), you can take the intent and decide which method to call like this:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if(intent.getStringExtra("methodName").equals("myMethod")){
mymethod();
}
}
Hello You can't call a particular method from intent but alternately you can use a service from intent and your requirement will be done.
Intent intent = new Intent(this, MyService.class);
and in MyService.class
public class MyService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
yourParticularMethod(); //do your task and stop the service when your task is done for battery saving purpose
context.stopService(new Intent(context, MyService.class));
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
and register this service in your manifest file like this
<application>
<service android:name=".MyService" />
.
.
</application>
I solve this issue by using onCreate instead of onNewIntent.
Activity A:
Intent intent = new Intent(this, com.app.max.Home.class);
intent.putExtra("methodName","myMethod");
startActivity(intent);
com.app.max.Home Activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
if(savedInstanceState == null)
{
Bundle extras = getIntent().getExtras();
if (extras == null)
{
//Extra bundle is null
}else{
String method = extras.getString("methodName");
if (method.equals("myMethod"))
{
//Call method here!
}
}
}
Hope this solution solve your problem
You question seems interesting, but there is no way you can do it using Intent. You have to understand that when you start an activity, it goes through a life cycle which is : onCreate()->onStart()->OnResume(). So what you can do is start that method from onResume() like this:
#Override
protected void onResume() {
super.onResume();
myMethod();//start your method from here
}
I'm just trying to help,give me some more information about your problem if this approach does not solve your problem.

Categories

Resources