I'm sure this is a failure in my understanding of intents but I have an ExpandableListView of items and when I click on an item it launches the first one OK but for each time after that it only launches the first one again no matter which on I click on. The request debugs as OK but the received intent always debugs as if the first one was sent. After a half a day stuck on it and Google failing me, I need some help.
Activity #1 Mainfest
<activity
android:name="com.h17.gpm.ActivityToDoList"
android:launchMode="singleInstance"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.h17.gpm.TODO" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Activity #1 Code
Intent launch = new Intent(ActivityToDoList.this, ActivityToDoEdit.class);
launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
launch.putExtra("Action._ID", a.get_ID());
Log.d("ACTIVITYLAUNCHTEST", "Launch["+a.get_ID()+"]");
startActivity(launch);
Activity #2 Mainfest
<activity
android:name="com.h17.gpm.ActivityToDoEdit"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.h17.gpm.TODO.EDIT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Activity Code #2
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo_edit);
Intent i = getIntent();
Bundle extras = null;
if(i != null)
extras = i.getExtras();
if (extras != null){
action_id = extras.getLong("Action._ID");
Log.d("ACTIVITYLAUNCHTEST", "Receive["+action_id+"]");
}
}
I've read from other posts that getIntent returns the first Intent so also tried
#Override
protected void onNewIntent(Intent intent){
Bundle extras = null;
if(intent != null)
extras = intent.getExtras();
if (extras != null){
action_id = extras.getLong("Action._ID");
Log.d("ACTIVITYLAUNCHTEST", "Receive New Intent["+action_id+"]");
}
setIntent(intent);
}
I've also tried a lot of combinations of Intent Flags and Launch Modes in the Manifest but for the life of me the first time always comes up as
Launch[1]
Receive[1]
and the second time
Launch[2]
Receive[1]
and from then on no matter what value I send the activity launches with the first value, 1 and the onNewIntent never seems to fire.
The complete function that generates the intent
private void loadLists(){
ExpandableListView expandableList = (ExpandableListView) findViewById(R.id.expandableListViewToDoLists);
expandableList.setClickable(true);
adapter = new ActionListsExpandableAdapter(getApplicationContext());
expandableList.setAdapter(adapter);
expandableList.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Action a = (Action) parent.getExpandableListAdapter().getChild(groupPosition, childPosition);
if (startedForResult){
Intent data = new Intent();
data.putExtra("Action._ID", a.get_ID());
data.putExtra("Action.SUBJECT", a.getSUBJECT());
setResult(RESULT_OK, data);
finish();
}else{
ActionList al = (ActionList) parent.getExpandableListAdapter().getGroup(groupPosition);
Intent launch = new Intent(ActivityToDoList.this, ActivityToDoEdit.class);
launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
launch.putExtra("Action._ID", a.get_ID());
Log.d("ACTIVITYLAUNCHTEST", "Launching activity with intent for Action ID ["+a.get_ID()+"]");
launch.putExtra("ActionList._ID", al.get_ID());
launch.putExtra("ActionList.position", childPosition);
startActivity(launch);
}
return false;
}
});
}
May be this is a good reference for you.
To me it seems like onNewIntent (with FLAG_ACTIVITY_SINGLE_TOP) like onCreate will be called if app is not destroyed. Hope is helpful to you. It works for me in my case.
For further reference see
Android: get most recent intent
Related
I have an app with two activities: MainActivity, which contains a URL entry field where the user can enter a YouTube video URL and press a submit button, to start the second activity, VideoActivity, which displays some information about this video (fetched from another web server).
The app also has a feature to receive intent via the Youtube application. When user presses the share button within the Youtube app, my app appears in the share list. Upon pressing share from the Youtube app, MainActivity should be brought to the front, and the URL should be posted within the MainActivity's URL field.
However, this only happens correctly on the first share. If the app is in the background when user shares from Youtube app, they are taken to whatever the last visible activity was, whether it is MainActivity or VideoActivity, (and even if it is MainActivity, the URL is not posted into the URL field, but the field is left in whatever state it was in when the app was last visible).
Here is my current AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.youcmt.youdmcapp">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
<activity
android:name=".VideoActivity"
android:parentActivityName=".MainActivity"/>
<service
android:name=".FetchVideoService"
android:exported="false"/>
</application>
</manifest>
Here is my MainActivity.java code:
public class MainActivity extends AppCompatActivity {
private ResponseReceiver mReceiver;
private EditText mUrlEditText;
private Button mSearchButton;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
mUrlEditText = findViewById(R.id.url_search_et);
Intent intent = getIntent();
if (intent.getType()!=null &&
intent.getType().equals("text/plain")) {
Bundle extras = getIntent().getExtras();
String value = extras.getString(Intent.EXTRA_TEXT);
if(value!=null)
{
mUrlEditText.setText(value);
}
}
mProgressBar = findViewById(R.id.progress_bar);
mSearchButton = findViewById(R.id.search_button);
mSearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
askForVideo(mUrlEditText.getText().toString());
mSearchButton.setVisibility(View.INVISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
} catch (Exception e) {
mUrlEditText.setText("");
mUrlEditText.setHint(e.getMessage());
e.printStackTrace();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
//register the ResponseReceiver
mReceiver = new ResponseReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(FETCH_VIDEO_INFO);
registerReceiver(mReceiver, intentFilter);
}
private void askForVideo (String url) throws Exception {
try {
Intent intent = FetchVideoService.newIntent(this, url);
startService(intent);
} catch (Exception e) {
mUrlEditText.setText(e.getMessage());
}
}
public class ResponseReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(EXTRA_VIDEO_STATUS, FAIL);
mProgressBar.setVisibility(View.INVISIBLE);
mSearchButton.setVisibility(View.VISIBLE);
if(status==FAIL)
{
mUrlEditText.setText("");
mUrlEditText.setHint("Error retrieving video!");
}
else if(status==SUCCESS) {
Video video = intent.getParcelableExtra(EXTRA_VIDEO);
Intent videoActivityIntent =
VideoActivity.newIntent(getApplicationContext(), video);
startActivity(videoActivityIntent);
}
}
}
#Override
protected void onPause() {
unregisterReceiver(mReceiver);
super.onPause();
}
}
I do not think any of the other files will be useful in understanding the problem. Although this seems like something many app creators should have to deal with, I can find no answers to this problem. Please comment if you feel I should add any additional information and thank you in advance for any help!
Update: testing demonstrates that after the first use of "Share" from YouTube (and considering app remains in the background), the MainActivity no longer receives any new intent on further shares. However, my app is still brought to the foreground somehow. This is very confusing to me.
When you share from another app, your MainActivity is brought to the front and onNewIntent() is called on it. You don't override onNewIntent() so you never see the share Intent.
I want to open login_activity on first time entering app, and then on the second entering to app open main_activity.
I create something but it wont work. so I wonder what I'm doing wrong?
this is my LoginActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userName = (EditText) findViewById(R.id.username);
userPhone = (EditText) findViewById(R.id.userPhone);
loginBtn = (Button) findViewById(R.id.buttonLogin);
dbHandler = new LogsDBHandler(this);
loginBtn.setOnClickListener(this);
setTitle("AMS - biomasa | prijava");
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if (pref.getBoolean("activity_executed", false)) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
} else {
SharedPreferences.Editor edt = pref.edit();
edt.putBoolean("activity_executed", true);
edt.commit();
}
}
public void insert() {
User user = new User (
userName.getText().toString(),
userPhone.getText().toString());
dbHandler.addUser(user);
Toast.makeText(getBaseContext(), "Prijavljeni ste!", Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
if (v == loginBtn && validateUser()) {
insert();
}
}
In main activity i have only image and two buttons.
And in manifest I add launcher to main and login activity.
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"></action>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"></action>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
What am I doing wrong here?
Create one start-up activity call it as SplashActivity
public class SplashActivity extends Activity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
// decide here whether to navigate to Login or Main Activity
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if (pref.getBoolean("activity_executed", false)) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
} else {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
}
}
In your LoginActivity simply set activity_executed to true
public void insert() {
User user = new User (
userName.getText().toString(),
userPhone.getText().toString());
dbHandler.addUser(user);
Toast.makeText(getBaseContext(), "Prijavljeni ste!", Toast.LENGTH_SHORT).show();
//set activity_executed inside insert() method.
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
SharedPreferences.Editor edt = pref.edit();
edt.putBoolean("activity_executed", true);
edt.commit();
}
change manifest as below-
<activity android:name=".MainActivity"/>
<activity android:name=".LoginActivity" />
<activity android:name=".SplashActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
you can change launcher activity as main activity.so that when you open the application it is starting from main activity there you can check whether he is logged in or not.if he is not logged in you must navigate him to login activity or else you just do it as it is.Following is manifest file..
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"></action>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".LoginActivity"></activity>
You should add another empty activity (with no UI) that loads before anything.
Then use SharedPreferences to store some value. Thus if the user has already opened your app once, the value is stored. And then use a condition to check this value. If its the value you saved skip login_activity and direct to main_activity else direct to login_activity.
Problem about the line
if (pref.getBoolean("activity_executed", false)) {
You can Implement this method to call inside if(appIsLoggedIn)
public boolean appIsLoggedIn(){
return pref.getBoolean("activity_executed", false);
}
I have a class called ShowBoardList where I check if user has logged in. If user hasn't logged in, then I want to return to the MainActivity which provides the user with buttons to login into different services.
My AndroidManifests.xml looks like this:
<application
<activity android:name="im.chaitanya.TaskTimer.MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="im.chaitanya.TaskTimer.WebViewActivity" >
</activity>
<activity android:name="im.chaitanya.TaskTimer.ShowBoardList"
android:label="Your Tasks">
</activity>
</application>
ShowBoardList.java looks like this:
...
Intent mainActivityIntent = new Intent(ShowBoardList.this, im.chaitanya.TaskTimer.MainActivity.class);
Intent intent = getIntent();
String url = intent.getStringExtra(WebViewActivity.EXTRA_MESSAGE); //url can be null here
Keys keys = new Keys(); //this gets an API key
SharedPreferences settings = getSharedPreferences("mySettings", 0);
String savedToken = settings.getString("token", "Empty");
if (MyUtils.equalsWithNulls(url,"tasktimer://oauthresponse#token=")) {
Log.d("From ME:", "I've reached inside url check");
mainActivityIntent.putExtra(caller, "ShowBoardList");
//caller is a String. I'm storing the name of the current activity (ShowBoardList) in it.
//So that the main activity (which I'm trying to call) will know where the call came from.
startActivity(mainActivityIntent);
}
if(savedToken.equals("Empty") || savedToken.equals("")) {
String searchString = "#token=";
int tokenIndex = url.indexOf(searchString) + searchString.length(); //Since url can be null there can be an error here
String token = url.substring(tokenIndex);
savedToken = token;
SharedPreferences.Editor editor = settings.edit();
editor.putString("token", token);
editor.apply();
}
...
Condtion equalsWithNulls checks if url is null OR equal to the string in the argument. I have log statements there to check whether control reaches inside the if statement. The main activity however doesn't start.
Edit: onCreate() of MainActivity.java looks like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences settings = getSharedPreferences("mySettings", 0);
String token = settings.getString("token", "Empty");
Intent intent = new Intent(this, ShowBoardList.class);
if(token != "Empty") {
startActivity(intent);
}
intent = getIntent();
String callerActivity = intent.getStringExtra(ShowBoardList.caller);
View coordinatorLayoutView = findViewById(R.id.snackbarPosition);
if (callerActivity!=null && callerActivity == "ShowBoardList") {
Snackbar
.make(coordinatorLayoutView, "Permission Denied", Snackbar.LENGTH_LONG)
.show();
}
setContentView(R.layout.activity_main);
}
Try to define your new Intent wherever you required.
Intent newIntent = new Intent(ShowBoardList.this, im.chaitanya.TaskTimer.MainActivity.class);
newIntent .putExtra(caller, "ShowBoardList");
startActivity(newIntent );
My solution is based on Sourabh's comment on the question. I realised from my logs that the activity was indeed being started.
What I didn't realise was that when startActivity() is called, the calling activity (in this case ShowBoardList) is paused and when ShowBoardList was being called again, it would resume from after startActivity().
Therefore the solution here was to call finish() and then return immediately after the startActivity() which ensures that onCreate is called the next time. I hope that makes sense if anyone is in the same situation.
These questions helped me understand more about finish():
about finish() in android
onCreate flow continues after finish()
Right now I am getting a force close on my android emulator.
Upon finishing this app, I will want to put a custom field in instead of just test, but for now I just want test to show up from the http activity.
Any help would be great!
MainActivity:
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.main.MESSAGE";
/*#SuppressLint("ParserError")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private Button searchBtn;
#Override
protected void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.activity_main);
searchBtn = (Button) findViewById(R.id.button1);
searchBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent(null, http.class);
startActivity(intent);
}
});
}
}
Http:
public class http extends Activity {
public http(){
httpMethod();
}
public void httpMethod(){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://api.site.com/api/");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
;
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String test = "hello";
TextView myTextView = (TextView) findViewById(R.id.myTextView);
myTextView.setText(test);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
Manifest:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.main.DisplayMessageActivity"/>
<activity android:name="com.example.main.http"/>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
There are whole lot of issues in the code:
1) Intent intent = new Intent(null, http.class);
Use first parameter as MainActivity.class instead of null
2) httpActivity should have onCreate (or) onResume life cycle activity methods to create activity for startActivity
Not but the least, please spend some time on reading documentation and doing example programs instead of just type-in something and post on SO. By going through all your questions it is something like SO community did your app for you.
You have to initialize Intent like this
Intent intent = new Intent(MainActivity.this, http.class);
You need to pass Context as first parameter not null.
start as:
searchBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent(MainActivity.this, http.class);
startActivity(intent);
}
});
instead of passing null as First parameter in Intent Constructor
for more information see here
http://developer.android.com/reference/android/content/Intent.html
I trully advice you to read some Android basics beacause you have some issues in the code:
You have a null context when you're initializing the intent at the button's listener. You should have: Intent intent = new Intent(getApplicationContext(), http.class); or Intent intent = new Intent(MainActivity.this, http.class);
You need to create your ativity and set it's content. You must override at least the onCreate method.
It's not so important, but its a good practice to write code that anyone might understand instead of write code for the machine! I'm telling this because you have *activity_main* sml file where you define your main activity layout and menu. I suggest you to refractor these file names to something like main.xml, for the layout, and *main_mnu.xml*.
I am using getHotelName() and setHotelName() to store data in the application and then access it. In my main activity that is categorized as Launcher both the methods and the getApplication() works in this activity. But when I try to access the getApplication from a different activity which is called from the main activity it gives a force close error.
This is my manifest file :
<application android:icon="#drawable/icon" android:label="#string/app_short_name" android:name="RestaurantNetwork" android:allowClearUserData="true" android:theme="#android:style/Theme.Black" >
<activity android:name="RestaurantActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="NetworkCommunication"></activity>
<uses-permission android:name="android.permission.INTERNET" />
</application>
In the main activity
RestaurantNetwork application = (RestaurantNetwork) getApplication();
application.setHotelName(this.hotelname.getText().toString());
Intent intent = new Intent(view.getContext(), NetworkCommunication.class);
startActivity(intent);
In the NetworkCommunication activity
public class NetworkCommunication extends Activity {
RestaurantNetwork application = (RestaurantNetwork) getApplication();
String hotelname = application.getHotelName().toString();
#Override
public void onCreate(Bundle savedInstanceState) {
I solved it using intent.extra, yes i had to get rid of the getApplication(). Would still like to know why there was an error in the prev method
in my main activity
this.hotelname = (EditText) findViewById(R.id.HotelName);
//RestaurantNetwork application = (RestaurantNetwork)getApplication();
//application.setHotelName(this.hotelname.getText().toString());
Intent intent = new Intent(view.getContext(), NetworkCommunication.class);
intent.putExtra("hotelName",this.hotelname.getText().toString());
startActivity(intent);
in my second activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchresults);
String value = null;
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
value = extras.getString("hotelName");
}
Toast.makeText(getApplicationContext(),value, Toast.LENGTH_SHORT).show();