startactivity(intent)方法会导致错误。为什么?

时间:2015-12-29 11:22:02

标签: android android-intent android-activity start-activity

我想在单击OK按钮后显示MenuActivity。我已经在互联网上搜索了一个答案并尝试了一切。我在AndroidManifest中声明了活动,我也尝试使用Intent(这个,MenuActivity.class)以及内部操作的那个但是它不起作用。

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();
}
}

这是我的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>

最后这里是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();
    }
}

不幸的是我无法向您展示我的Logcat,因为它无法在我的计算机上运行。 (我总是要导出APK来测试应用程序。)

P.S。我正在使用Android Studio 1.0.1 ...请帮助我!

4 个答案:

答案 0 :(得分:1)

是因为您说MainActivity.this,但您不在MainActivity环境中。 您可以在onCreate()中引用当前上下文并将其保存在字段中:

private Context context;

@Override
    protected void onCreate(Bundle savedInstanceState) {
      context = this;
      //rest of your code here
    }

并将其用作:

Intent intent = new Intent(context, MenuActivity.class);
//Something else
context.startActivity(intent);

答案 1 :(得分:0)

要打开一个新活动,您只需在onClick方法中调用它。

Intent intent = new Intent(v.getContext(), MenuActivity.class);
startActivity(intent);

所以你的onClick方法看起来像这样。

@Override
public void onClick(View v) {
    Intent intent = new Intent(v.getContext(), MenuActivity.class);
    startActivity(intent);
}

希望这有帮助。

答案 2 :(得分:0)

首先请确保您的AndroidManifest.xml文件包含您应用中所有活动的声明,例如

<activity android:name=".MenuActivity"/>

然后创建新的意图,并在需要启动第二个活动的地方启动它

Intent intent = new Intent(v.getContext(), MenuActivity.class);
startActivity(intent);

希望您能理解我的意思,希望对您有所帮助,

对不起,我的语言不好

答案 3 :(得分:0)

转到清单文件,您将输入MainActivity manifest

android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">

只需复制它们并将其粘贴到您的MenuActivity中即可。 我遇到了与您相同的问题,并且对我有用,但我不知道为什么。 祝你好运!