I want after a click on the OK button the MenuActivity to be shown. I have already searched on the Internet to find an answer and tried everything. I haave the activity declared in the AndroidManifest and I also tried to use Intent(this, MenuActivity.class) and also the one with the action inside but it doesn’t work.
MainActivity:
package com.jamesjohnson.chronos;
import android.app.AlertDialog;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.jamesjohnson.chronos.R;
public class MainActivity extends ActionBarActivity implements OnClickListener {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setTitle("Willkommen");
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch(id) {
case R.id.action_mainmenu:
startActivity(new Intent("com.jamesjohnson.chronos.MenuActivity"));
return true;
case R.id.action_settings:
showMessageBox("Es gibt leider noch keine Einstellungen. Wir arbeiten daran!", true, true);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
try {
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
Context ctx = this;
intent.setClassName(ctx, "com.jamesjohnson.chronos.MenuActivity");
intent.setAction("com.jamesjohnson.chronos.MenuActivity");
if ((intent.getAction() == "com.jamesjohnson.chronos.MenuActivity") || (intent.getClass() != null)) {
MainActivity.this.startActivity(intent);
showMessageBox("Button has been pressed " + intent.toString(), true, true);
}
else {
showMessageBox("Error : Hauptmenü ist nicht erreichbar", true, true);
}
}
catch (ActivityNotFoundException an) {
showMessageBox("Error :" + an.getMessage(), true, true);
}
catch (Exception e) {
showMessageBox("Error :" + e.getMessage(), true, true);
}
}
protected void showMessageBox(String message, boolean showOKbutton, boolean canceable) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(MainActivity.this);
dlgAlert.setMessage(message);
dlgAlert.setTitle("Chronos");
if (showOKbutton) {
dlgAlert.setPositiveButton("OK", null);
}
if (canceable) {
dlgAlert.setCancelable(true);
}
dlgAlert.create().show();
}
}
Here’s my AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jamesjohnson.chronos"
android:versionCode="1"
android:versionName="1.0.1
" >
<application
android:allowBackup="true"
android:debuggable="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
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=".MenuActivity"
android:label="@string/title_activity_menu"
android:parentActivityName=".MainActivity" >
<intent-filter>
<action android:name="com.jamesjohnson.chronos.MenuActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.jamesjohnson.chronos.MainActivity" />
</activity>
</application>
</manifest>
And finally here’s the MenuActivity:
package com.jamesjohnson.chronos;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MenuActivity extends ListActivity {
private static final String TAG = "MenuActivity";
static final String[] ENTRIES = new String[] {"Kunden", "Projekte", "Leistungen", "Zeiten"};
ListView listView = getListView();
@Override
protected void onCreate(Bundle savedInstanceState) {
showMessageBox("Activity is beeing created", true, true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
this.setTitle("Hauptmenü");
this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ENTRIES));
listView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
showMessageBox("Kunden", true, true);
break;
case 1:
showMessageBox("Projekte", true, true);
break;
case 2:
showMessageBox("Leistungen", true, true);
break;
case 3:
showMessageBox("Zeiten", true, true);
break;
default:
showMessageBox("Error: Undefined index", true, true);
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
protected void showMessageBox(String message, boolean showOKbutton, boolean canceable) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(MenuActivity.this);
dlgAlert.setMessage(message);
dlgAlert.setTitle("Chronos");
if (showOKbutton) {
dlgAlert.setPositiveButton("OK", null);
}
if (canceable) {
dlgAlert.setCancelable(true);
}
dlgAlert.create().show();
}
}
Unfortunately I can’t show you my Logcat because it doesn’t work on my computer. (I always have to export the APK to test the App).
P.S. I am working with Android Studio 1.0.1
…Please HELP ME !
All solutions to this problem here did not help, so I ask in a new question.
I need to open an activity from an OnItemClickListener method of a ListView, but it simply does nothing… New activity is neither opened nor thrown an exception.
This is the code that tries to show the activity:
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView <? > parent, View v, int position, long id) {
try {
ImageGalleryItem item = (ImageGalleryItem) parent.getItemAtPosition(position);
//Create intent
Intent intent = new Intent(v.getContext(), DetailsActivity.class);
intent.putExtra("title", item.getTitle());
intent.putExtra("image", item.getImage());
//Start details activity
startActivity(intent);
} catch (Exception e) {
Auditing.LogError(e);
}
}
});
This is the Manifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cl.virtualice.tdc">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-feature android:name="android.hardware.Camera" android:required="true" />
<application
android:label="@string/app_title"
android:icon="@drawable/ic_tdc"
android:theme="@style/AppTheme"
android:allowBackup="true">
<activity
android:name=".activities.MainActivity"
android:theme="@style/AppTheme"
android:label="@string/app_title">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".activities.FormActivity"
android:parentActivityName=".activities.MainActivity">
</activity>
<activity
android:name=".activities.GalleryActivity"
android:parentActivityName=".activities.FormActivity">
</activity>
<activity
android:name=".activities.DetailsActivity"
android:parentActivityName=".activities.GalleryActivity">
</activity>
</application>
</manifest>
And this is the new Activity code:
package cl.virtualice.tdc.activities;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import cl.virtualice.tdc.R;
/**
* Created by Jaime on 23-10-2015.
*/
public class DetailsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
String title = getIntent().getStringExtra("title");
Bitmap bitmap = getIntent().getParcelableExtra("image");
TextView titleTextView = (TextView) findViewById(R.id.title);
titleTextView.setText(title);
ImageView imageView = (ImageView) findViewById(R.id.image);
imageView.setImageBitmap(bitmap);
}
}
Any help please?
Делаю такую логику приложения: переход в другую активность при нажатии элемента RecyclerView. Слушатель добавил в onBindViewHolder, срабатывает нормально, тестовое сообщение появляется после нажатия. Но при написании кода студия красит красным метод startActivity, не могу понять почему. Подскажите пожалуйста возможные причины, может кто сталкивался с таким/ Код адаптера привожу полностью:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private List<Book> booksList;
public RecyclerAdapter(List<Book> booksList) {
this.booksList = booksList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.card, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
Book book = booksList.get(position);
/**
* Загрузка обложки из интернета. Сссылки в MainActivity
*/
Picasso
.with(holder.imgObl.getContext())
.load(book.getResId())
.into(holder.imgObl);
/**
* обработка нажатия на элемент списка RecyclerView
*/
holder.imgObl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Toast.makeText(holder.imgObl.getContext(),
// "Пойдем читать " + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(holder.imgObl.getContext(), SliderActivity.class);
startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return booksList.size();
} //считает количество элементов в списке
public static class ViewHolder extends RecyclerView.ViewHolder {
ImageView imgObl;
CardView cv;
public ViewHolder(View itemView) {
super(itemView);
imgObl = (ImageView) itemView.findViewById(R.id.iv_recycler_item);
cv = (CardView) itemView.findViewById(R.id.card_view);
}
}
}
I want after a click on the OK button the MenuActivity to be shown. I have already searched on the Internet to find an answer and tried everything. I haave the activity declared in the AndroidManifest and I also tried to use Intent(this, MenuActivity.class) and also the one with the action inside but it doesn’t work.
MainActivity:
package com.jamesjohnson.chronos;
import android.app.AlertDialog;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.jamesjohnson.chronos.R;
public class MainActivity extends ActionBarActivity implements OnClickListener {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setTitle("Willkommen");
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch(id) {
case R.id.action_mainmenu:
startActivity(new Intent("com.jamesjohnson.chronos.MenuActivity"));
return true;
case R.id.action_settings:
showMessageBox("Es gibt leider noch keine Einstellungen. Wir arbeiten daran!", true, true);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
try {
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
Context ctx = this;
intent.setClassName(ctx, "com.jamesjohnson.chronos.MenuActivity");
intent.setAction("com.jamesjohnson.chronos.MenuActivity");
if ((intent.getAction() == "com.jamesjohnson.chronos.MenuActivity") || (intent.getClass() != null)) {
MainActivity.this.startActivity(intent);
showMessageBox("Button has been pressed " + intent.toString(), true, true);
}
else {
showMessageBox("Error : Hauptmenü ist nicht erreichbar", true, true);
}
}
catch (ActivityNotFoundException an) {
showMessageBox("Error :" + an.getMessage(), true, true);
}
catch (Exception e) {
showMessageBox("Error :" + e.getMessage(), true, true);
}
}
protected void showMessageBox(String message, boolean showOKbutton, boolean canceable) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(MainActivity.this);
dlgAlert.setMessage(message);
dlgAlert.setTitle("Chronos");
if (showOKbutton) {
dlgAlert.setPositiveButton("OK", null);
}
if (canceable) {
dlgAlert.setCancelable(true);
}
dlgAlert.create().show();
}
}
Here’s my AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jamesjohnson.chronos"
android:versionCode="1"
android:versionName="1.0.1
" >
<application
android:allowBackup="true"
android:debuggable="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
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=".MenuActivity"
android:label="@string/title_activity_menu"
android:parentActivityName=".MainActivity" >
<intent-filter>
<action android:name="com.jamesjohnson.chronos.MenuActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.jamesjohnson.chronos.MainActivity" />
</activity>
</application>
</manifest>
And finally here’s the MenuActivity:
package com.jamesjohnson.chronos;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MenuActivity extends ListActivity {
private static final String TAG = "MenuActivity";
static final String[] ENTRIES = new String[] {"Kunden", "Projekte", "Leistungen", "Zeiten"};
ListView listView = getListView();
@Override
protected void onCreate(Bundle savedInstanceState) {
showMessageBox("Activity is beeing created", true, true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
this.setTitle("Hauptmenü");
this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ENTRIES));
listView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
showMessageBox("Kunden", true, true);
break;
case 1:
showMessageBox("Projekte", true, true);
break;
case 2:
showMessageBox("Leistungen", true, true);
break;
case 3:
showMessageBox("Zeiten", true, true);
break;
default:
showMessageBox("Error: Undefined index", true, true);
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
protected void showMessageBox(String message, boolean showOKbutton, boolean canceable) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(MenuActivity.this);
dlgAlert.setMessage(message);
dlgAlert.setTitle("Chronos");
if (showOKbutton) {
dlgAlert.setPositiveButton("OK", null);
}
if (canceable) {
dlgAlert.setCancelable(true);
}
dlgAlert.create().show();
}
}
Unfortunately I can’t show you my Logcat because it doesn’t work on my computer. (I always have to export the APK to test the App).
P.S. I am working with Android Studio 1.0.1
…Please HELP ME !
28
Answers 1 : of The startactivity(intent) method causes an error. Why
To open a new activity you simply have to call it like this inside the onClick method.
Intent intent = new Intent(v.getContext(), MenuActivity.class);
startActivity(intent);
So your onClick method will look like this.
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), MenuActivity.class);
startActivity(intent);
}
Hope this helps.
Answer Link
mRahman
6
Answers 2 : of The startactivity(intent) method causes an error. Why
Is because you say MainActivity.this, but you aren’t in the MainActivity context.
You could make a reference of your current context in onCreate() and save it in a field:
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
context = this;
//rest of your code here
}
and use it as:
Intent intent = new Intent(context, MenuActivity.class);
//Something else
context.startActivity(intent);
Answer Link
raja
6
Answers 3 : of The startactivity(intent) method causes an error. Why
Go to your manifest file, you will for your MainActivity manifest:
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
Just copy them and paste them for your MenuActivity.
I had the same same problem than you and it worked for me, but I don’t know why.
Good luck!
Answer Link
raja
2
Answers 4 : of The startactivity(intent) method causes an error. Why
first make sure your AndroidManifest.xml file contain declaration of all Activities in your app, like
<activity android:name=".MenuActivity"/>
then you create new intent and start it where you need to start the second Activity
Intent intent = new Intent(v.getContext(), MenuActivity.class);
startActivity(intent);
Answer Link
raja
In the above video you will find – Solving Calling startActivity() from outside of an Activity context issue.
While trying to open a browser intent (webpage), when clicking an item in the recycler view of my test app, I faced the following exception:
Calling startActivity() from outside of an Activity context ...
In the video above I provide you with the line of the code that solved the problem in this particular case.
The video shows the part of the code that generates the exception. Basically, I was trying to open a new web page when clicking one particular item in the Recycler View of my Android application.
I try to open the web page by creating a new intent and using the Intent.ACTION_VIEW flag. Then in the context (using the mContext variable), I call the startActivity method, and pass the new Intent variable.
When running the application it crashes and gives me the “Application keeps stopping” dialog box.
So basically, in the video above you will see how to solve the “Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag” issue in Android Studio.
The above is an Android Runtime Exception and it is raised when trying to load a browser intent from a Recycler View.
To fix the error, you will need to add the following line, in between the Intent creation line and the line that calls the startActivity method:
browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
The FLAG_ACTIVITY_NEW_TASK flag, clears the error and you can load the web page successfully:
So, after you apply the line above, you will see that the web page or the browser intent will load correctly and the app won’t crash anymore.
This solution worked on this particular case, but might not be suitable in different situation.
The above flag is required in these particular situation, like the case when loading a new web page from Recycler View.
Leave your questions and comments in the section below.
Thank you!
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.