当前位置: 首页 > 知识库问答 >
问题:

如何解决无法启动activity错误?

许安邦
2023-03-14

请帮我解决这个问题。 我是Android Studio的新手。 我的代码一点错误都没有,但是我不知道为什么我的app每次启动都不停地崩溃。 请帮助我,我需要这个为我的项目。 谢谢。

这是我的日志猫中出现的内容

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mmtravelapp/com.example.mmtravelapp.MainActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

这是我的主要活动。java

public class MainActivity extends AppCompatActivity {
    private DatabaseHelper dbHelper;
    private ImageView pImageView;
    private EditText Pemail, Pname, PAge, Pphone, Ppassword;
    private TextView loginacclink, Ppreferenceselected;
    Button createacc, preferencebtn;
    ActionBar actionBar;
    String[] categories;
    boolean[] checkeditems;
    ArrayList<Integer> mUserItems = new ArrayList<>();
    private static final int CAMERA_REQUEST_CODE = 100;
    private static final int STORAGE_REQUEST_CODE = 101;
    private static final int IMAGE_PICK_CAMERA_CODE = 102;
    private static final int IMAGE_PICK_GALLERY_CODE = 103;
    private String[] cameraPermissions;
    private String[] storagePermissions;


    private Uri imageUri;
    private String name, age, phone,email, password;
    private String preferenceselected;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // this is the status bar
        actionBar = getSupportActionBar();
        actionBar.setTitle("Create Account");
        // this is for the check list
        categories = getResources().getStringArray(R.array.user_categories);
        checkeditems = new boolean[categories.length];
        // this is for the items in the xml file
        pImageView =  findViewById(R.id.personImage);
        Pemail = findViewById(R.id.email);
        Pname = findViewById(R.id.name);
        PAge = findViewById(R.id.age);
        Pphone = findViewById(R.id.phone);
        Ppassword = findViewById(R.id.password);
        createacc = findViewById(R.id.createacc);
        preferencebtn = findViewById(R.id.preferencebtn);
        loginacclink = findViewById(R.id.loginacclink);

        pImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imagePickDialog();

            }
        });

        preferencebtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick (View view){
                AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
                mBuilder.setTitle(R.string.dialog_title);
                mBuilder.setMultiChoiceItems(categories, checkeditems, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int position, boolean isChecked) {
                        if (isChecked) {
                            if (!mUserItems.contains(position)) {
                                mUserItems.add(position);
                            }
                        } else if (mUserItems.contains(position)) {
                            mUserItems.remove(position);
                        }
                    }

                });

                mBuilder.setCancelable(false);
                mBuilder.setPositiveButton(R.string.ok_label, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int which) {
                        String item = "";
                        for (int i = 0; i < mUserItems.size(); i++) {
                            item = item + categories[mUserItems.get(i)];
                            if (i != mUserItems.size() - 1) {
                                item = item + ",";
                            }
                        }
                        Ppreferenceselected.setText(item);
                    }
                });

                mBuilder.setNegativeButton(R.string.dismiss_label, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
                mBuilder.setNeutralButton(R.string.clear_all_label, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int which) {
                        for (int i = 0; i < checkeditems.length; i++) {
                            checkeditems[i] = false;
                            mUserItems.clear();
                            Ppreferenceselected.setText("");
                        }
                    }
                });
                AlertDialog mDialog = mBuilder.create();
                mDialog.show();

            }
        });


        loginacclink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, login.class);
                startActivity(intent);        }
        });




        Ppreferenceselected = (TextView) findViewById(R.id.preferenceselected);
        dbHelper = new DatabaseHelper(this);

        cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        storagePermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};

        createacc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // insert data into db
                getData();

            }
        });
    }

    private void getData() {
        email = "" + Pemail.getText().toString().trim();
        name = "" + Pname.getText().toString().trim();
        age = "" + PAge.getText().toString().trim();
        phone = "" + Pphone.getText().toString().trim();
        preferenceselected = "" + Ppreferenceselected.getText().toString().trim();
        password = "" + Ppassword.getText().toString().trim();


        if (email.isEmpty() || name.isEmpty() || age.isEmpty() || phone.isEmpty() || preferenceselected.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "Please fill all the information", Toast.LENGTH_SHORT).show();
            return;
        }
        if (dbHelper.userExists(email)){
            Toast.makeText(this, "User Exist", Toast.LENGTH_SHORT).show();
            return;
        }

        String timeStamp = "" + System.currentTimeMillis();

        boolean id = dbHelper.insertInfo(
                "" + imageUri,
                "" + email,
                "" + name,
                "" + age,
                "" + phone,
                "" + preferenceselected,
                "" + password,
                ""+timeStamp,
                ""+timeStamp

        );


        Toast.makeText(this, "Account Created", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(MainActivity.this, setting.class);
        startActivity(intent);


    }



    private void imagePickDialog() {

        String[] options = {"Camera", "Gallery"};

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Pick Image From");

        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                if (which == 0) {
                    if (!checkCameraPermission()) {
                        requestCameraPermission();
                    }
                    else {
                        pickFromCamera();
                    }
                }
                else if (which == 1) {
                    if (!checkStoragePermission()) {
                        requestStoragePermission();
                    }
                    else {
                        pickFromGallery();
                    }
                }

            }
        });

        builder.create().show();
    }

    private boolean checkCameraPermission() {

        boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                == (PackageManager.PERMISSION_GRANTED);

        boolean result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == (PackageManager.PERMISSION_GRANTED);

        return result && result1;
    }

    private void requestCameraPermission() {

        ActivityCompat.requestPermissions(this, cameraPermissions, CAMERA_REQUEST_CODE);
    }
    private void pickFromGallery() {

        Intent galleryIntent = new Intent(Intent.ACTION_PICK);
        galleryIntent.setType("image/*");
        startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_CODE);
    }

    private void pickFromCamera() {

        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, "Image title");
        values.put(MediaStore.Images.Media.DESCRIPTION, "Image description");

        imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);

    }

    private boolean checkStoragePermission() {

        boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == (PackageManager.PERMISSION_GRANTED);

        return result;
    }

    private void requestStoragePermission() {

        ActivityCompat.requestPermissions(this, storagePermissions, STORAGE_REQUEST_CODE);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {

            case CAMERA_REQUEST_CODE: {

                if (grantResults.length>0) {

                    boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    boolean storageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;

                    if (cameraAccepted && storageAccepted) {
                        pickFromCamera();
                    }

                    else {
                        Toast.makeText(this, "Camera permission required!", Toast.LENGTH_SHORT).show();
                    }

                }

            }
            break;
            case STORAGE_REQUEST_CODE:{

                if (grantResults.length>0) {

                    boolean storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;

                    if (storageAccepted) {
                        pickFromGallery();
                    }
                    else {
                        Toast.makeText(this, "Storage permission required!", Toast.LENGTH_SHORT).show();
                    }

                }
            }
            break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        if (resultCode == RESULT_OK) {

            if (requestCode == IMAGE_PICK_GALLERY_CODE) {

                CropImage.activity(data.getData())
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .setAspectRatio(1, 1)
                        .start(this);
            }

            else if (requestCode == IMAGE_PICK_CAMERA_CODE) {

                CropImage.activity(imageUri)
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .setAspectRatio(1, 1)
                        .start(this);
            }

            else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {

                CropImage.ActivityResult result = CropImage.getActivityResult(data);

                if (resultCode == RESULT_OK) {
                    Uri resultUri = result.getUri();
                    imageUri = resultUri;
                    pImageView.setImageURI(resultUri);
                }

                else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {

                    Exception error = result.getError();
                    Toast.makeText(this, ""+error, Toast.LENGTH_SHORT).show();
                }
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }


}

这是我的res/values/styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>



</resources>

提前感谢您的帮助!

共有1个答案

长孙作人
2023-03-14

您需要将theme.AppCompat主题(或后代)与此activity一起使用。

打开AndroidManifest.xml并查找MainActivity。 如果没有android:theme属性,就意味着activity正在使用该应用主题。 打开它并检查父属性是否是theme.appcompat可用的属性之一。 例如:

<style name="YourAppTheme" parent="Theme.AppCompat.Light"></style>
 类似资料:
  • 我正在为android创建一个移动应用程序,我有一个问题,当下载连接后,谷歌 应用程序崩溃。谁能给我一个理由,怎么附上? } 例外情况:

  • 本文向大家介绍MySQL启动错误解决方法,包括了MySQL启动错误解决方法的使用技巧和注意事项,需要的朋友参考一下 一般情况下mysql的启动错误还是很容易排查的,但是今天我们就来说一下不一般的情况。拿到一台服务器,安装完mysql后进行启动,启动错误如下: 有同学会说,哥们儿你是不是buffer pool设置太大了,设置了96G内存。这明显提示无法分配内存嘛。如果真是这样也就不在这里进行分享了,

  • 本文向大家介绍解决“无法启动mysql服务 错误1069”的方法,包括了解决“无法启动mysql服务 错误1069”的方法的使用技巧和注意事项,需要的朋友参考一下 今天还在路上的时候,同事就发来消息,说网站后台无法访问了,那个急啊! 赶到公司,登陆服务器,正常,还好,看来不是服务器自身的问题,看错误提示,应该是mysql的问题了。 到服务选项里已查看,果然,未启动状态,启动MYSQL的时候提示错误

  • 本文向大家介绍启动hadoop报如下错误,该如何解决?相关面试题,主要包含被问及启动hadoop报如下错误,该如何解决?时的应答技巧和注意事项,需要的朋友参考一下 --1.error org.apache.hadoop.hdfs.server.namenode.NameNode --找不到主类,应该是配置文件的hadoop的安装位置配置错误,对hadoop-env.sh文件进行检查修改 --2.o

  • 运行React Native APL有4种方法。 > < Li > react-本机运行-android < li>react-native run-iso < li>XCODE < li> Android Studio 适用于另一个终端屏幕,在、、上。但Android Studio不起作用,错误如下。 [ 12-14 14:02:59.506 2905: 2928 E/ ]无法从assets加载

  • 我得到这个错误: ntime:致命异常:主进程:com.example。puzzle\u项目,PID:4100 java.lang.RuntimeException:无法启动活动ComponentInfo{com.example.puzzle\u项目/com.example.puzzle\u项目.MainActivity}:java.lang.NullPointerException:尝试在空对象

  • json 0信息:如果以OK结尾,则工作 1详细cli['C:\Program Files\nodejs\node.exe', 1详细cli'C:\users\vkarutha\appdata\roaming\npm\node_modules\npm\bin\npm-cli.js', 1详细的cli“开始”] 2信息使用npm@4.2.0 3使用节点@v6.9.3的信息 4详细运行脚本['pres

  • 现在我正在尝试从git运行克隆应用程序https://github.com/frinder/frinder-app但问题是该应用程序制作了很长时间,所以应该改变bulid.gradle 但是当我尝试相同的同步实现“com.android.支持:动画矢量可绘制:28.0.0”,但如果我删除它,请继续向我显示错误28.0.0它显示如下 但我不知道是什么造成了不完全相同的版本 这是应用程序build.g