I get an ActivityNotFoundException when I use this code:
public void addListenerOnButton3(){
button3 = (Button) findViewById(R.id.btnSettings);
button3.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intentSettings = new Intent("net.stuffilike.kanaflash.Settings");
showToast("Settings clicked,");
try{
startActivity(intentSettings);
}
catch(Exception e){
showToastL("Exception" + e);
}
return;
}
});
}
Fair enough, except I can't tell how it wants me to tell it where the Activity is. Here is the relevant section of the Manifest:
<activity
android:name="net.stuffilike.kanaflash.Settings"
android:label="#string/settings" >
<intent-filter>
<action android:name="android.intent.action.SETTINGS" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
How can I be sure the compiler finds my Settings.java file?
Oh, my package is named
package net.stuffilike.kanaflash;
try this
#Override
public void onClick(View arg0) {
Intent intentSettings = new Intent(X.this,Settings.class);
showToast("Settings clicked,");
try{
startActivity(intentSettings);
}
catch(Exception e){
showToastL("Exception" + e);
}
return;
}
});
replace X with your current activity name ..
The constructor for new Intent(String action) takes action as paramter.
As per your manifest, the action you are using is android.intent.action.SETTINGS,
1.So your Intent should be as below
Intent intentSettings = new Intent("android.intent.action.SETTINGS");
or
2.You can directly invoke the activity by using the Activity name,
Intent intentSettings = new Intent(this, Settings.class);
or
3.You can also define a custom action like net.stuffilike.intent.action.SETTINGS and then use this to create your Intent like
Intent intentSettings = new Intent("net.stuffilike.intent.action.SETTINGS");
There's 2 ways you can do this.
Use the action String to let the system see what Activitys can resolve the action on the Intent. If there is more than one Activity that can resolve the action, the user will get an option to pick which one they want.
Intent intentSettings = new Intent("android.intent.action.SETTINGS");
Open the Activity using its class directly (can only be done if both Activitys are in the same app).
Intent intentSettings = new Intent(this, Settings.class);
Related
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()
This question already has answers here:
How to start new activity on button click
(28 answers)
Closed 7 years ago.
I want to start a new activity when i press the button, but when i press it my app crashes!
Where is the Problem?
Here is the code!
public void onClickButtonListener() {
button_play = (Button)findViewById(R.id.play_button);
button_play.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(".SecPage");
startActivity(intent);
}
}
);
}
Your Intent should have two parameters. The current activity and the activity it is going to.
Intent intent = new Intent(this, SecPage.class);
startActivity(intent);
Please consider the following issues,
Make sure you have specified your source and destination classes,
Intent intent = new Intent(ActivityA.this, ActivityB.class);
startActivity(intent);
Make sure you have added an activity tag in the manifest file,
<activity
android:name=".ActivityA"
android:theme="#style/FullscreenTheme" >
</activity>
If you are using the Activity class in a different package add the full package name,
<activity
android:name="com.silverlining.bionot.ActivityA"
android:theme="#style/FullscreenTheme" >
</activity>
You are probably trying to invoke a custom action with this constructor for Intent:
public Intent (String action)
Make sure you are using the full custom action string, something like com.google.app.myapp.SecPage.
According to android documentation,
public Intent (String action)
Create an intent with a given action. All other fields (data, type,
class) are null. Note that the action must be in a namespace because
Intents are used globally in the system -- for example the system VIEW
action is android.intent.action.VIEW; an application's custom action
would be something like com.google.app.myapp.CUSTOM_ACTION.
Every time I try to start new activity, an error occurs (Java null pointer exception) and the app fc's: I tried every single way and it just doesn't work! Here's an example for the code : MainAct is the first activity and NewAct is the activity to launch...
1- manifest:
<activity
android:name="com.example.app.NewAct"
android:label="#string/title_activity_newact" >
<intent-filter>
<action android:name="android.intent.action.NewAct" />
</intent-filter>
</activity>
2-MainAct:
Button bt;
bt = (Button) findViewById (R.id.bt);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i= new Intent ("com.example.app.NewAct");
startActivity(i);
}
});
I also tried other forms of intent such as
Intent i= new Intent ("android.intent.action.NewAct");
Intent i= new Intent (this, NewAct.class);
Intent i= new Intent (view.getContext(), StudentInfoActivity.class);
Don't get the context from the "view" get the context from the Activity. Wherever you need a context use getApplicationContext(), getActivity(), or this. But if you are inside of an Anonymous Inner Class, such as a View.OnClickListener() (as you are in the code you posted) you cannot use this because this will be referring to the Anonymous Inner Class that you are in.
A common practice would be storing the Context away in a private member variable, do this inside of onCreate()...
Ex.
....
private Context mContext;
...
#Override
onCreate(Bundle savedInstanceState){
mContext = this;
}
^By doing this you have a context variable to use freely throughout your activity without having to worry.
Try something like this to start your new Activity, after you have your Context variable:
Intent i = new Intent(mContext,
NewAct.class);
startActivity(i);
^You can use this code from within your OnClickListener().
Intent i = new Intent(MainAct.this, NewAct.class);
startActivity(i);
I think the problem is not with your Intent.please check your onCreate() of the second Activity[NewAct.java].
So I want to launch a service from a shortcut. I know that this is not possible to do directly, so I've set up a activity with the sole purpose of starting the service.
The aim of my service is to send an intent to another app and then 5 seconds later send another so I've used a CountDownTimer to do this.
However, when I launch the Activity that starts the service from the shortcut (this is getting confusing) it launches the apps UI. I don't want this, as I want it to be a background service.
What am I doing wrong. I've only just got into development, so it could be something obvious, but I've been battling with this for a few days now.
For some reason when I run it from the service it just launches the app straight away...
When I run it straight from the invisible activity it runs properly for the 1st 5 seconds fine and then loads the app...
I can't figure out why it's loading the app at all.
I've included as much info as I can that would be relevant.
Any help is appreciated!
My service:
public class Pop1_5Service extends IntentService {
public Pop1_5Service() {
super("Pop1_5Service");
}
#Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
new CountDownTimer(5000, 2500) {
public void onTick(long millisUntilFinished) {
Intent i = new Intent(INTENT_ACTION);
Bundle b = new Bundle();
b.putInt(BUNDLE_VERSION_CODE, 1);
b.putString(BUNDLE_STRING_NAME, "POP1");
b.putString(BUNDLE_STRING_VALUE, "1");
i.putExtra(BUNDLE_NAME, b);
sendBroadcast(i); }
public void onFinish() {
Intent i = new Intent(INTENT_ACTION);
Bundle b = new Bundle();
b.putInt(BUNDLE_VERSION_CODE, 1);
b.putString(BUNDLE_STRING_NAME, "POP1");
b.putString(BUNDLE_STRING_VALUE, "1");
i.putExtra(BUNDLE_NAME, b);
sendBroadcast(i); }
}
}.start();
}
}
Activity that launches service:
public class Pop1_5Activity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, Pop1_5Service.class);
startService(intent);
finish();
}
}
Subsection of Manifest:
<activity
android:name=".Pop1_5Activity"
android:theme="#android:style/Theme.NoDisplay">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".Pop1_5Service" />
And the 'Create a Shortcut' Activity:
public class CreateShortcutActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent shortcutintent = new Intent(this, Pop1_5Activity.class);
ShortcutIconResource iconResource = Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutintent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Pop1_5");
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
setResult(RESULT_OK, intent);
finish();
}
}
From the look of things, it looks like CreateShortcutActivity does nothing.
Your LAUNCHER is Pop1_5Activity, so when the user presses the app icon, this Activity will run, and it launches the Service.
All the code you have showed us are "invisible", the two Activities finish() themselves, and the Service is a Service.
You might want to look at how your BroadcastReceiver handles your broadcast. For instance, does it create another Activity through PendingIntent? Is the Activity created invisible?
Maybe you should try creating a pending Service instead of pending Activity in the BroadcastReceiver.
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*.