java.lang.NullPointerException : in androidstudio

标签 java android xml

我有一个 Android 应用程序。这个应用程序有 12 个 Activity ,第一个 Activity 是启动屏幕,第二个 Activity 是 intropage,第三个 Activity 是主要等当我运行应用程序时,它不会进入主 Activity 并且应用程序关闭。错误如下:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setAlpha(float)' on a null object reference

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setAlpha(float)' on a null object reference
        at com.github.hujiaweibujidao.wava.BaseViewAnimator.reset(BaseViewAnimator.java:78)
        at com.github.hujiaweibujidao.wava.BaseViewAnimator.start(BaseViewAnimator.java:55)
        at com.github.hujiaweibujidao.wava.YoYo$Builder.start(YoYo.java:128)
        at com.github.hujiaweibujidao.wava.YoYo$Builder.playOn(YoYo.java:115)
        at com.example.myapplication.MainActivity.onCreate(MainActivity.java:108)
        at android.app.Activity.performCreate(Activity.java:6679)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
        at android.app.ActivityThread.-wrap12(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:154) 
        at android.app.ActivityThread.main(ActivityThread.java:6119) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

感谢您的回答,但您给我的解决方案没有帮助。我检查了,但它仍然给了我同样的错误。我给你放了三激活码。你能帮我一下吗?

这是我的主要 Activity java代码:

package com.example.myapplication;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.akshay.library.CurveBottomBar;
import com.github.hujiaweibujidao.wava.Techniques;
import com.github.hujiaweibujidao.wava.YoYo;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import com.mxn.soul.flowingdrawer_core.ElasticDrawer;
import com.mxn.soul.flowingdrawer_core.FlowingDrawer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import uk.co.samuelwall.materialtaptargetprompt.MaterialTapTargetPrompt;

public class MainActivity extends AppCompatActivity {
    CurveBottomBar cbb;
    FlowingDrawer mDrawer;
    ImageView img_icon,imgtest,img_music,img_night,img_main,img_setting;
    TextView txt;
    String patch;

    boolean read=false,music=true,night_mode;
    Button btn_fehrest,btn_last_story,btn_fav;
    SharedPreferences sharedP;
    LinearLayout lin_main;
    Toast exit;
    boolean show_intropage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        cbb = findViewById(R.id.cbb);
        mDrawer = findViewById(R.id.drawerlayout);
        img_icon = findViewById(R.id.img_icon);
        imgtest = findViewById(R.id.imgtest);
        txt = findViewById(R.id.txt);
        btn_fehrest = findViewById(R.id.btn_fehrest);
        img_music = findViewById(R.id.img_music);
        lin_main = findViewById(R.id.lin_main);
        img_night = findViewById(R.id.img_night);
        img_main = findViewById(R.id.img_main);
        btn_last_story = findViewById(R.id.btn_last_story);
        btn_fav = findViewById(R.id.btn_fav);
        img_setting = findViewById(R.id.img_setting);

        cbb.inflateMenu(R.menu.menu_scrolling);
        sharedP = getSharedPreferences(Items.SETTINGS, Context.MODE_PRIVATE);
        show_intropage = sharedP.getBoolean(Items.INTROPAGE,true);


        cbb.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

                switch (menuItem.getItemId()){

                    case R.id.img_setting:
                        // kary ke mikhaym anjam bedim
                        break;

                    case R.id.img_music:
                        //
                        break;
                }

                return false;
            }
        });
        YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(btn_fehrest);
        YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(btn_last_story);
        YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(btn_fav);
        YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(img_music);
        YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(img_setting);

        get_night();
        permission();
        //createFile();
        if (show_intropage){
            taptarget();
        }



        img_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mDrawer.openMenu(true);
            }
        });

        mDrawer.setTouchMode(ElasticDrawer.TOUCH_MODE_BEZEL);
        mDrawer.setBackgroundColor(Color.WHITE);
        mDrawer.setOnDrawerStateChangeListener(new ElasticDrawer.OnDrawerStateChangeListener() {
            @Override
            public void onDrawerStateChange(int oldState, int newState) {
                if (newState == ElasticDrawer.STATE_CLOSED) {
                    Log.i("MainActivity", "Drawer STATE_CLOSED");
                }
            }

            @Override
            public void onDrawerSlide(float openRatio, int offsetPixels) {
                Log.i("MainActivity", "openRatio=" + openRatio + " ,offsetPixels=" + offsetPixels);
            }
        });
    }


    public void createFile(){

        try {

            patch = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Mbook/";

            File mfile = new File(patch);

            if (!mfile.exists()) {
                mfile.mkdir();
                mfile.createNewFile();
                CopyDB(getBaseContext().getAssets().open("Mbook.db"), new FileOutputStream(patch+"/Mbook.db"));
                //Toast.makeText(this, patch+"", Toast.LENGTH_LONG).show();
            }

        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    public void CopyDB (InputStream inputStream, OutputStream outputStream) throws IOException {

        byte[] buffer = new byte[1024];
        int file_length;
        while ((file_length = inputStream.read(buffer))>0){

            outputStream.write(buffer,0,file_length);
        }
        inputStream.close();
        outputStream.close();
    }

    public void fehrest_intent(View view) {
        mDrawer.closeMenu(true);
        YoYo.with(Techniques.Pulse).duration(800).playOn(btn_fehrest);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                Intent intent = new Intent(getBaseContext(), Fehrest.class);
                intent.putExtra("button","fehrest");
                startActivity(intent);

            }
        },1500);

    }

    private void permission(){

        Dexter.withContext(MainActivity.this)
                .withPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)

                .withListener(new PermissionListener() {
                    @Override
                    public void onPermissionGranted(PermissionGrantedResponse response) {

                        createFile();
                    }

                    @Override
                    public void onPermissionDenied(PermissionDeniedResponse response) {

                        if (response !=null && response.isPermanentlyDenied()){

                            AlertDialog.Builder Hoshdar = new AlertDialog.Builder(MainActivity.this);
                            Hoshdar.setMessage("جهت استفاده از برنامه دادن اجازه دسترسی ضروریست");
                            Hoshdar.setCancelable(false);
                            Hoshdar.setPositiveButton("رفتن به تنظیمات", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                    intent.setData(Uri.fromParts("package",getPackageName(),null));
                                    startActivity(intent);
                                }
                            });
                        }
                        Toast.makeText(MainActivity.this, "جهت استفاده از برنامه دادن اجازه دسترسی ضروریست", Toast.LENGTH_SHORT).show();
                        alert();
                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(PermissionRequest permission, final PermissionToken token) {
                        alert();
                    }
                }).check();

    }
    public void alert(){

        AlertDialog.Builder Hoshdar = new AlertDialog.Builder(MainActivity.this);
        Hoshdar.setTitle("توجه");
        Hoshdar.setMessage("جهت استفاده از برنامه دادن اجازه دسترسی ضروریست لطفا درقسمت تنظیمات اجازه دسترسی را فعال کنید");
        Hoshdar.setCancelable(false);
        Hoshdar.setPositiveButton("رفتن به تنظیمات", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.fromParts("package",getPackageName(),null));
                startActivity(intent);
            }
        });
        Hoshdar.create().show();
    }

    public void fav_intent(View view) {
        YoYo.with(Techniques.Pulse).duration(600).playOn(btn_fav);
        mDrawer.closeMenu(true);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                Intent intent = new Intent(getBaseContext(), Fehrest.class);
                intent.putExtra("button","fav");
                intent.putExtra("activity","main");
                startActivity(intent);

            }
        },1500);
    }



    public void text_intent(View view) {
        YoYo.with(Techniques.Pulse).duration(600).playOn(btn_last_story);
        if (read){
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {

                    Intent intent_movies = new Intent(getBaseContext(), Text_activity.class);
                    intent_movies.putExtra("activity","main");
                    startActivity(intent_movies);

                }
            },1500);
        }else {
            Toast.makeText(this, "هنوز هیچ داستانی مطالعه نکردید!", Toast.LENGTH_SHORT).show();
        }


    }

    public void setting_intent(MenuItem item) {
        mDrawer.closeMenu(true);
        YoYo.with(Techniques.Pulse).duration(600).playOn(img_setting);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                startActivity(new Intent(MainActivity.this,Setting.class));

            }
        },1500);

    }

    public void set_music(MenuItem item) {
        YoYo.with(Techniques.Pulse).duration(600).playOn(img_music);

        if (music){
            stopService(new Intent(MainActivity.this,PlayMusic.class));
            img_music.setBackgroundResource(R.drawable.music_off_icon);
            music=false;
            sharedP.edit().putBoolean(Items.MUSIC, false).apply();
        }else {
            startService(new Intent(MainActivity.this,PlayMusic.class));
            img_music.setBackgroundResource(R.drawable.music_on_icon);
            music=true;
            sharedP.edit().putBoolean(Items.MUSIC, true).apply();
        }
    }


    public void get_night(){

        music = sharedP.getBoolean(Items.MUSIC,true);
        night_mode = sharedP.getBoolean(Items.NIGHT_MODE,false);
        read = sharedP.getBoolean(Items.READ,false);

        if (night_mode){
            lin_main.setBackgroundResource(R.color.Black0);
            img_night.setBackgroundResource(R.drawable.sun_icon);
            img_main.setBackgroundResource(R.drawable.main2);

        }else {
            lin_main.setBackgroundResource(0);
            img_night.setBackgroundResource(R.drawable.moon_icon);
            img_main.setBackgroundResource(R.drawable.main);
        }

        if (!music){
            stopService(new Intent(MainActivity.this,PlayMusic.class));
            img_music.setBackgroundResource(R.drawable.music_off_icon);
        }else {
            startService(new Intent(MainActivity.this,PlayMusic.class));
            img_music.setBackgroundResource(R.drawable.music_on_icon);
        }
    }
    public void set_night(View view){

        YoYo.with(Techniques.RotateIn).duration(800).playOn(img_night);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                if (night_mode){
                    lin_main.setBackgroundResource(0);
                    img_night.setBackgroundResource(R.drawable.moon_icon);
                    img_main.setBackgroundResource(R.drawable.main);
                    sharedP.edit().putBoolean(Items.NIGHT_MODE, false).apply();
                    night_mode=false;

                }else {
                    lin_main.setBackgroundResource(R.color.Black0);
                    img_night.setBackgroundResource(R.drawable.sun_icon);
                    img_main.setBackgroundResource(R.drawable.main2);
                    sharedP.edit().putBoolean(Items.NIGHT_MODE, true).apply();
                    night_mode=true;
                }

            }
        },800);

    }

    @Override
    protected void onResume() {
        super.onResume();
        get_night();
    }


    @Override
    protected void onDestroy() {
        stopService(new Intent(MainActivity.this,PlayMusic.class));
        super.onDestroy();
    }

    public void finish(View view) {
        mDrawer.closeMenu(true);
        finish();
    }

    @SuppressLint("ResourceAsColor")
    private void taptarget(){

        new MaterialTapTargetPrompt.Builder(MainActivity.this)
                .setTarget(R.id.img_night)
                .setPrimaryText("فعال کردن حالت شب")
                .setSecondaryText("با زدن این دکمه میتوانید حالت مطالعه در شب را فعال یا غیر فعال کنید")
                //.setPrimaryTextColour(Color.parseColor("#13dc74"))
                // .setSecondaryTextColour(Color.parseColor("#13dc74"))
                .setFocalColour(R.color.mycolorGray)
                .setBackButtonDismissEnabled(false)
                .setBackgroundColour(Color.parseColor("#635B5B"))
                .setPromptStateChangeListener(new MaterialTapTargetPrompt.PromptStateChangeListener()
                {
                    @Override
                    public void onPromptStateChanged(MaterialTapTargetPrompt prompt, int state)
                    {
                        if (state == MaterialTapTargetPrompt.STATE_FOCAL_PRESSED|| state==MaterialTapTargetPrompt.STATE_NON_FOCAL_PRESSED)
                        {
                            // User has pressed the prompt target
                            //Toast.makeText(MainActivity.this, "اولی", Toast.LENGTH_SHORT).show();
                            txt_target();
                        }
                    }
                })
                .show();
    }

    private void txt_target(){
        new MaterialTapTargetPrompt.Builder(MainActivity.this)
                .setTarget(R.id.img_icon)
                .setFocalColour(R.color.mycolorGray)
                .setPrimaryText("منوی کشویی")
                .setSecondaryText("با زدن این دکمه منوی کشویی برنامه باز خواهد شد که شامل آیتم های مختلفی می باشد")
                .setBackgroundColour(Color.parseColor("#635B5B"))
                .setPromptStateChangeListener(new MaterialTapTargetPrompt.PromptStateChangeListener()
                {
                    @Override
                    public void onPromptStateChanged(MaterialTapTargetPrompt prompt, int state)
                    {
                        if (state == MaterialTapTargetPrompt.STATE_FOCAL_PRESSED || state==MaterialTapTargetPrompt.STATE_NON_FOCAL_PRESSED)
                        {
                            // User has pressed the prompt target
                            //Toast.makeText(MainActivity.this, "دومی", Toast.LENGTH_SHORT).show();
                            target3();
                        }
                    }
                })
                .show();
    }

    private void target3(){
        new MaterialTapTargetPrompt.Builder(MainActivity.this)
                .setTarget(R.id.img_music)

                .setPrimaryText("فعال/غیرفعال موزیک")
                .setSecondaryText("با زدن این دکمه میتوانید موزیک پس زمینه حین مطالعه را پخش یا قطع کنید")
                .setBackgroundColour(Color.parseColor("#635B5B"))
                .setPromptStateChangeListener(new MaterialTapTargetPrompt.PromptStateChangeListener()
                {
                    @Override
                    public void onPromptStateChanged(MaterialTapTargetPrompt prompt, int state)
                    {
                        if (state == MaterialTapTargetPrompt.STATE_FOCAL_PRESSED || state==MaterialTapTargetPrompt.STATE_NON_FOCAL_PRESSED)
                        {
                            // User has pressed the prompt target
                            //Toast.makeText(MainActivity.this, "دومی", Toast.LENGTH_SHORT).show();
                            target4();
                        }
                    }
                })
                .show();
    }

    private void target4(){
        new MaterialTapTargetPrompt.Builder(MainActivity.this)
                .setTarget(R.id.img_setting)

                .setPrimaryText("تنظیمات")
                .setSecondaryText("با زدن این دکمه بخش تنظیمات باز خواهد شد که شامل تغییر فونت متن ، سایز متن و ... می باشد")
                .setBackgroundColour(Color.parseColor("#635B5B"))
                .setPromptStateChangeListener(new MaterialTapTargetPrompt.PromptStateChangeListener()
                {
                    @Override
                    public void onPromptStateChanged(MaterialTapTargetPrompt prompt, int state)
                    {
                        if (state == MaterialTapTargetPrompt.STATE_FOCAL_PRESSED || state==MaterialTapTargetPrompt.STATE_NON_FOCAL_PRESSED)
                        {
                            // User has pressed the prompt target
                            //Toast.makeText(MainActivity.this, "دومی", Toast.LENGTH_SHORT).show();
                            sharedP.edit().putBoolean(Items.INTROPAGE, false).apply();
                        }
                    }
                })
                .show();
    }

    @Override
    public void onBackPressed() {


        if (!(exit ==null)){
            super.onBackPressed();
            //MainActivity.this.finish();
        }else {
            exit = Toast.makeText(this,"برای خروج دوباره بزنید",Toast.LENGTH_LONG);
            exit.show();
        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                exit= null;

            }
        },3000);
    }
}

这是我的主要 Activity xml 代码:

This is a photo of the main activity  XML  code part 1

This is a photo of the main activity  XML  code part  2

This is a photo of the main activity  XML  code part 3

This is a photo of the main activity  XML  code part 4

This is a photo of the main activity  XML  code part 5 This is a photo of the main activity  XML  code part 6 This is a photo of the main activity  XML  code part 7 This is a photo of the main activity  XML  code part 8 This is a photo of the main activity  XML  code part 9 This is a photo of the main activity  XML  code part 10 初始屏幕 Activity Run 进入介绍页面。点击拒绝或完成按钮后,程序不会进入 Activity 菜单,程序将关闭。

最佳答案

请遵循以下选项。希望您的问题能够得到解决。

1) 您的 list 必须更改,如下所示 Activity 名称必须指定为“.YourActivityname”

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

2)清理并重建项目并希望它能发挥作用。

关于java.lang.NullPointerException : in androidstudio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61701096/

相关文章:

java - java Datagram Socket处理数据的速度不够快

java - NullPointerException - JOptionPane

c# - 将 XML 发布到 WebAPI 并返回结果

Android java.lang.ClassCastException : android. widget.LinearLayout 无法转换为 android.widget.TextView

java - 如何解析 XML 以检索嵌入的文本节点

python - 使用python将数据从xml存储到数据库

java - Maven 构建 list 不包含类路径。

java - 这个在单独线程上绘图的具体示例有什么问题?

android - Android-垂直 ScrollView 内有两个Vertical RecyclerView,我需要为每个recyclerview执行更多加载

Android:如何在 Facebook 登录中 Conceal 进度圈