Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android Firebase空指针异常_Android_Firebase_Firebase Realtime Database - Fatal编程技术网

Android Firebase空指针异常

Android Firebase空指针异常,android,firebase,firebase-realtime-database,Android,Firebase,Firebase Realtime Database,我正在尝试从用户检索用户电子邮件,然后使用它从其他firebase数据库节点(如Shared_With节点)获取数据。但由于一些奇怪的原因,我得到了空指针异常。我不知道为什么电子邮件要么没有被检索,要么被设置为空。这是我的班级,我正在做所有这些: private static Context context = null; //new name for android devices private EditText result;

我正在尝试从用户检索用户电子邮件,然后使用它从其他firebase数据库节点(如Shared_With节点)获取数据。但由于一些奇怪的原因,我得到了空指针异常。我不知道为什么电子邮件要么没有被检索,要么被设置为空。这是我的班级,我正在做所有这些:

        private static Context context = null;

        //new name for android devices
        private EditText result;
        FirebaseAuth auth = FirebaseAuth.getInstance();
        static SharedPreferences deviceListSharedPreferences;
        //widgets
       // Button btnPaired;
        static ListView devicelist;
        static ImageView iv;
        private static DBHandler mdb;
        private static Set<BluetoothDevice> pairedDevices;

        String name;
        static String pass;
        private String mEmail;
        String emaill;
        String mNameRec;
        String mPassRec;
        String mMacRec;
        private static BluetoothAdapter myBluetooth = null;
        static TextView mName;
        static TextView mMac;
        static TextView mNameRecDev;
        static TextView mMacRecDev;
        private static ProgressDialog progress;
        private static String address = "";
        private FirebaseAuth mAuth;
        private FirebaseAuth.AuthStateListener mAuthListener;
        User userModel = new User();
        private static final String TAG ="USER STATUS" ;

        private OnFragmentInteractionListener mListener;

        static BluetoothSocket btSocket = null;
        private static boolean isBtConnected = false;
        //SPP UUID. Look for it
        static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
        private String encPass;
        String decPass;
    /*Class begins here, other methods omitted due to charectar limit*/
   public main() {
        }
        @Override
        public void onViewCreated(View view, Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            iv = (ImageView) view.findViewById(R.id.change);
            //Calling widgets
    //       // btnPaired = (Button) view.findViewById(R.id.button);
            devicelist = (ListView) view.findViewById(R.id.listView);
            mNameRecDev = (TextView)view.findViewById(R.id.nameRec);
            mMacRecDev = (TextView)view.findViewById(R.id.macRec);
            try {
                emaill = mAuth.getCurrentUser().getEmail();
                emaill = emaill.replace(".", "<");
                System.out.println("Email add:" + emaill);
            }catch(NullPointerException n){
                System.out.println(n.getMessage());
            }

            if (myBluetooth.isEnabled()) { // bluetooth is connected
                pairedDevicesList();
            }




            iv.setEnabled(false);
            iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Get the device MAC address, the last 17 chars in the View
                    String device_name = deviceListSharedPreferences.getString(address, mdb.getDeviceName(address));
                    if (v.getContentDescription().toString().equals("green")) {
                        iv.setImageResource(R.drawable.red);
                        mdb.addLog(new SimpleDateFormat("HH:mm:ss, dd/MM/yyyy").format(new Date().getTime())
                                + "", MainActivity.name, MainActivity.email, device_name, "0");
                        iv.setContentDescription("red");
                        try{
                            sendCommand("~"+pass);
                        }catch(NullPointerException e){
                            Toast.makeText(getContext(), "Set password first", Toast.LENGTH_SHORT);
                        }//method to turn on
                    } else {
                        iv.setImageResource(R.drawable.green);
                        mdb.addLog(new SimpleDateFormat("HH:mm:ss, dd/MM/yyyy").format(new Date().getTime())
                                + "", MainActivity.name, MainActivity.email, device_name, "1");
                        iv.setContentDescription("green");
                        try{
                            sendCommand("`"+pass);
                        }catch(NullPointerException e){
                            Toast.makeText(getContext(), "Set password first", Toast.LENGTH_SHORT);
                        }//method to turn off
                    }
                }
            });
            System.out.println(emaill+"HEH");
            DatabaseReference mdShare = FirebaseDatabase.getInstance().getReference().child("Shared_With");
            mdShare.child(emaill).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    mNameRec = dataSnapshot.child("Device_Name").getValue().toString();
                            mMacRec = dataSnapshot.child("Device_MAC").getValue().toString();
                            mPassRec = dataSnapshot.child("Password").getValue().toString();
                            decPassrd(mPassRec);

                            mNameRecDev.setText(mNameRec);
                            mMacRecDev.setText(mMacRec);

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

    //    

            mNameRecDev.setOnClickListener(this);
            mMacRecDev.setOnClickListener(this);

        }

        private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                final String action = intent.getAction();

                if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                    final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                            BluetoothAdapter.ERROR);
                    switch (state) {
                        case BluetoothAdapter.STATE_OFF:
                            Toast.makeText(getActivity(), "Bluetooth needs to be on", Toast.LENGTH_LONG).show();
                            break;
                   //     case BluetoothAdapter.STATE_TURNING_OFF:
                           // do something if needed
                 //           break;
                        case BluetoothAdapter.STATE_ON:
    //                        pairedDevicesList();
                            break;
                    //    case BluetoothAdapter.STATE_TURNING_ON:
                 //          do something if needed
                    //        break;
                    }
                }
            }
        };

        private static class ConnectBT extends AsyncTask<Void, Void, Void>  // UI thread
        {
            private boolean ConnectSuccess = true; //if it's here, it's almost connected

            @Override
            protected void onPreExecute() {
                progress = ProgressDialog.show(context, "Connecting...", "Please wait!!!");  //show a progress dialog
            }

    //        if(iterator.getAddress().equals(DEVICE_ADDRESS)) //Replace with iterator.getName() if comparing Device names.
    //
    //        {
    //
    //            device=iterator; //device is an object of type BluetoothDevice
    //
    //            found=true;
    //        socket = device.createRfcommSocketToServiceRecord(PORT_UUID); socket.connect();

            @Override
            protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
            {
                try {
                    if (btSocket == null || !isBtConnected) {
                        myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
                        BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
    //                    btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(UUID.fromString(dispositivo.getUuids()[0].toString()));//create a RFCOMM (SPP) connection
                        btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
                        BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
                        btSocket.connect();//start connection
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    ConnectSuccess = false;//if the try failed, you can check the exception here
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
            {
                super.onPostExecute(result);

                if (!ConnectSuccess) {
                    Toast.makeText(context, "Connection Failed. Are you sure the device is in range and on, or another device is not connected already?", Toast.LENGTH_LONG).show();
                } else {
                    //Ahmed: BLUETOOTH IS CONNECTED
                    iv.setEnabled(true);
                    Toast.makeText(context, "Connected.", Toast.LENGTH_SHORT).show();

                    try{
                        sendTimedCommand("^"+pass);
                    }catch(NullPointerException e){
                        Toast.makeText(context, "Set password first", Toast.LENGTH_SHORT);
                    }//tell arduino device is connected //
                    isBtConnected = true;
                }
                progress.dismiss();
            }
        }

        public static ArrayList list = new ArrayList();

        public static void pairedDevicesList() {
            pairedDevices = myBluetooth.getBondedDevices();
            list.clear();

            if (pairedDevices.size() > 0) {
                for (BluetoothDevice bt : pairedDevices) { //loop
                    // handling custom names for devices, address => custom name
                    // reading already stored custom names
                    String customName;
                    // Toast.makeText(getActivity(), bt.getAddress() + " =>  " + bt.getName(), Toast.LENGTH_LONG).show(); //annoying

                    if (mdb.getDeviceName(bt.getAddress()).length() < 2) {
                        customName = deviceListSharedPreferences.getString(bt.getAddress(), bt.getName() + "\n" + bt.getAddress());
                    }
                    else {
                        customName = deviceListSharedPreferences.getString(bt.getAddress(), mdb.getDeviceName(bt.getAddress()));
                    }

                    list.add(customName); //add the appropriate name to ListView
                    SharedPreferences.Editor editor = listIndexToDeviceAddress.edit();
                    editor.putString(String.valueOf(list.size() - 1), bt.getAddress()); // puts position => address
                    editor.commit();

                }
            } else {
                Toast.makeText(context, "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
            }

            final ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, list);
            devicelist.setAdapter(adapter);
            devicelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

                    address = listIndexToDeviceAddress.getString(String.valueOf(position), "address not available");

                    if (address.equals("address not available")){
                        Toast.makeText(context, "Something went wrong, address not found", Toast.LENGTH_LONG).show();
                    }else {
                        new ConnectBT().execute(); //Call the class to connect
                    }
                }
            }); //Method called when the device from the list is clicked

            //handling long click
            devicelist.setOnItemLongClickListener (new AdapterView.OnItemLongClickListener() {

                public boolean onItemLongClick(AdapterView parent,final View view, final int position, long id) {

                    // TODO Auto-generated method stub

                    android.support.v7.app.AlertDialog.Builder builderSingle = new android.support.v7.app.AlertDialog.Builder(context);

                    // can be used for icon and label:
                    //builderSingle.setIcon(R.drawable.ic_logo);
                    // builderSingle.setTitle("Select One Name:-");

                    final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.select_dialog_singlechoice);

                    // hardcoded options
                    arrayAdapter.add("Enter New Name");
                    arrayAdapter.add("Set Password");

                    builderSingle.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

                    builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String strName = arrayAdapter.getItem(which);

                            if (which == 0){ // delete
                                //do your stuff here
                                // get prompts.xml view
                                LayoutInflater li = LayoutInflater.from(context);
                                View promptsView = li.inflate(R.layout.name_prompt, null);

                                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                                        context);

                                // set prompts.xml to alertdialog builder
                                alertDialogBuilder.setView(promptsView);

                                final EditText userInput = (EditText) promptsView
                                        .findViewById(R.id.editTextDialogUserInput);

                                // set dialog message
                                alertDialogBuilder
                                        .setCancelable(false)
                                        .setPositiveButton("OK",
                                                new DialogInterface.OnClickListener() {
                                                    public void onClick(DialogInterface dialog, int id) {
                                                        // get user input and set it to result
                                                        // edit text
                                                        Log.d("length", String.valueOf(userInput.getText().toString().length()));
                                                        if (userInput.getText().toString().length() > 0) {
                                                            SharedPreferences.Editor editor = deviceListSharedPreferences.edit();
                                                            String device_address = listIndexToDeviceAddress.getString(String.valueOf(position), "address not available");
                                                            if (!device_address.equals("address not available")) {
                                                                editor.putString(device_address, userInput.getText().toString());
                                                                editor.commit();
                                                                pairedDevicesList();
                                                                Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
                                                            }
                                                        } else {
                                                            Toast.makeText(context, "Name empty", Toast.LENGTH_SHORT).show();
                                                        }
                                                    }
                                                })
                                        .setNegativeButton("Cancel",
                                                new DialogInterface.OnClickListener() {
                                                    public void onClick(DialogInterface dialog, int id) {
                                                        dialog.cancel();
                                                    }
                                                });

                                // create alert dialog
                                AlertDialog alertDialog = alertDialogBuilder.create();

                                // show it
                                alertDialog.show();

                            }else if (which == 1){ // share
                                //do your stuff here
                                // get prompts.xml view
                                LayoutInflater li = LayoutInflater.from(context);
                                View promptsView = li.inflate(R.layout.name_prompt, null);

                                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                                        context);

                                // set prompts.xml to alertdialog builder
                                alertDialogBuilder.setView(promptsView);

                                final TextView tv = (TextView) promptsView.findViewById(R.id.name_prompt_label);
                                tv.setText("Enter New Password");

                                final EditText userInput = (EditText) promptsView
                                        .findViewById(R.id.editTextDialogUserInput);

                                // set dialog message
                                alertDialogBuilder
                                        .setCancelable(false)
                                        .setPositiveButton("OK",
                                                new DialogInterface.OnClickListener() {
                                                    public void onClick(DialogInterface dialog, int id) {
                                                        // get user input and set it to result
                                                        // set password
                                                        Log.d("length", String.valueOf(userInput.getText().toString().length()));
                                                        if (userInput.getText().toString().length() > 0) {
                                                            // are you sure this is the new password?
                                                            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(DialogInterface dialog, int which) {
                                                                    switch (which){
                                                                        case DialogInterface.BUTTON_POSITIVE:
                                                                            //Yes button clicked
                                                                            // update or create new password

                                                                            String device_address = listIndexToDeviceAddress.getString(String.valueOf(position), "address not available");
                                                                            String device_name    = deviceListSharedPreferences.getString(device_address, ((String)devicelist.getItemAtPosition(position)).split("\n")[0]); //get saved name otherwise get first line from ListView string
                                                                            if (!device_address.equals("address not available")) {
                                                                                Log.v("address and name", device_address);
                                                                                mdb.updateOrSetNewPassword(device_name, device_address, userInput.getText().toString(), true);
                                                                                Toast.makeText(context, "New Password Set", Toast.LENGTH_SHORT).show();
                                                                            }

                                                                            dialog.dismiss();
                                                                            break;

                                                                        case DialogInterface.BUTTON_NEGATIVE:
                                                                            //No button clicked
                                                                            dialog.dismiss();
                                                                            break;
                                                                    }
                                                                }
                                                            };

                                                            android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(context);
                                                            builder.setMessage("Are you sure you want to change the password to " + userInput.getText().toString() + "?").setPositiveButton("Yes", dialogClickListener)
                                                                    .setNegativeButton("No", dialogClickListener).show();
                                                        } else {
                                                            Toast.makeText(context, "Password field empty empty", Toast.LENGTH_SHORT).show();
                                                        }
                                                    }
                                                })
                                        .setNegativeButton("Cancel",
                                                new DialogInterface.OnClickListener() {
                                                    public void onClick(DialogInterface dialog, int id) {
                                                        dialog.cancel();
                                                    }
                                                });

                                // create alert dialog
                                AlertDialog alertDialog = alertDialogBuilder.create();

                                // show it
                                alertDialog.show();

                            }

                        }
                    });
                    builderSingle.show();

                    return true;
                }
            });

        }

    }
private静态上下文=null;
//android设备的新名称
私人编辑文本结果;
FirebaseAuth auth=FirebaseAuth.getInstance();
静态SharedReferences设备ListSharedReferences;
//小部件
//按钮btnPaired;
静态列表视图设备列表;
静态图像视图iv;
私有静态DBHandler-mdb;
私有静态集合对设备;
字符串名;
静态串通;
私有字符串mEmail;
字符串email;
字符串mNameRec;
字符串mPassRec;
字符串mMacRec;
专用静态蓝牙适配器myBluetooth=null;
静态文本视图mName;
静态文本视图mMac;
静态文本视图mNameRecDev;
静态文本视图mMacRecDev;
私有静态进程对话框进程;
私有静态字符串地址=”;
私人消防队;
私有FirebaseAuth.AuthStateListener mAuthListener;
User userModel=新用户();
私有静态最终字符串TAG=“用户状态”;
私有OnFragmentInteractionListener mListener;
静态BluetoothSocket btSocket=null;
私有静态布尔值isBtConnected=false;
//SPP-UUID。找找看
静态最终UUID myUUID=UUID.fromString(“00001101-0000-1000-8000-00805F9B34FB”);
私人密码;
串解传;
/*类从这里开始,由于charectar限制,省略了其他方法*/
公用干管(){
}
@凌驾
已创建视图上的公共void(视图,捆绑保存状态){
super.onViewCreated(视图,savedInstanceState);
iv=(ImageView)view.findViewById(R.id.change);
//调用小部件
////btnPaired=(Button)view.findviewbyd(R.id.Button);
devicelist=(ListView)view.findViewById(R.id.ListView);
mNameRecDev=(TextView)view.findviewbyd(R.id.nameRec);
mMacRecDev=(TextView)view.findViewById(R.id.macRec);
试一试{
emaill=mAuth.getCurrentUser().getEmail();
emaill=emaill.replace(“.”,“+bt.getName(),Toast.LENGTH_LONG).show();//烦人
if(mdb.getDeviceName(bt.getAddress()).length()<2){
customName=DeviceListSharedReferences.getString(bt.getAddress(),bt.getName()+“\n”+bt.getAddress());
}
否则{
customName=DeviceListSharedReferences.getString(bt.getAddress(),mdb.getDeviceName(bt.getAddress());
}
list.add(customName);//将适当的名称添加到ListView
SharedReferences.Editor=listIndexToDeviceAddress.edit();
editor.putString(String.valueOf(list.size()-1),bt.getAddress());//放置位置=>地址
commit();
}
}否则{
Toast.makeText(上下文,“未找到配对的蓝牙设备”,Toast.LENGTH_LONG.show();
}
最终的ArrayAdapter=新的ArrayAdapter(上下文,android.R.layout.simple\u列表\u项目\u 1,列表);
devicelist.setAdapter(适配器);
devicelist.setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父视图、视图v、整型位置、长id){
address=listIndexToDeviceAddress.getString(String.valueOf(位置),“地址不可用”);
if(地址等于(“地址不可用”)){
Toast.makeText(上下文,“出错,找不到地址”,Toast.LENGTH_LONG.show();
}否则{
new ConnectBT().execute();//调用类进行连接
}
}
}); //单击列表中的设备时调用的方法
//处理长点击
devicelist.setOnItemLongClickListener(新的AdapterView.OnItemLongClickListener(){
公共布尔长单击(AdapterView父视图、最终视图、最终整型位置、长id){
//TODO自动生成的方法存根
android.support.v7.app.AlertDialog.Builder builderSingle=新的android.support.v7.app.AlertDialog.Builder(上下文);
//可用于图标和标签:
//builderSingle.setIcon(R.drawable.ic_徽标);
//setTitle(“选择一个名称:-”);
final ArrayAdapter ArrayAdapter=新的ArrayAdapter(上下文,android.R.layout.select_dialog_singlechoice);
//硬编码选项
arrayAdapter.add(“输入新名称”);
arrayAdapter.add(“设置密码”);
builderSingle.setNegativeButton(“取消”,新建DialogInterface.OnClickListener()){
@凌驾
public void onClick(DialogInterface dialog,int which){
dialog.dismise();
}
});
setAdapter(arrayAdapter,新的DialogInterface.OnClickListener(){
@凌驾
public void onClick(DialogInterface dialog,int which){
字符串strName=arrayAdapter.getItem(which);
如果(which==0){//delete
//在这里做你的事
//通用电气
mdShare.child(emaill).addValueEventListener(new ValueEventListener() {...}
System.out.println("Email add:" + emaill);
...
System.out.println(emaill+"HEH");
try {
    emaill = mAuth.getCurrentUser().getEmail();
    emaill = emaill.replace(".", "<");
    System.out.println("Email add:" + emaill);
}catch(NullPointerException n){
    System.out.println(n.getMessage());
}
mAuth = FirebaseAuth.getInstance();