2

Esto teniendo el siguiente error cuando instalo la apk en mi dispositivo el log arroja este error:

Error de Logcat

09-11 11:59:11.218 16688-16688/com.example.g_talent.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.g_talent.myapplication, PID: 16688
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.g_talent.myapplication/com.example.g_talent.myapplication.MainActivity}: java.lang.NullPointerException
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
    at android.app.ActivityThread.access$800(ActivityThread.java:139)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5102)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
    at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
    at com.example.g_talent.myapplication.MainActivity.onCreate(MainActivity.java:37)
    at android.app.Activity.performCreate(Activity.java:5248)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269) 
    at android.app.ActivityThread.access$800(ActivityThread.java:139) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:136) 
    at android.app.ActivityThread.main(ActivityThread.java:5102) 
    at java.lang.reflect.Method.invokeNative(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:515) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
    at dalvik.system.NativeStart.main(Native Method) 

Código:

package com.example.g_talent.myapplication;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.nio.charset.CharacterCodingException;
import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    CheckBox enable_bt, visible_bt;
    TextView name_bt;
    ImageView search_bt;
    ListView list_view;

    private BluetoothAdapter BA;
    private Set<BluetoothDevice> pairedDevice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        enable_bt.findViewById(R.id.enable_bt);
        visible_bt.findViewById(R.id.visible_bt);
        name_bt.findViewById(R.id.name_bt);
        search_bt.findViewById(R.id.search_bt);
        list_view.findViewById(R.id.list_view);

        name_bt.setText(getLocalBluetoothName());
        BA = BluetoothAdapter.getDefaultAdapter();



        if(BA == null) {
            Toast.makeText(MainActivity.this,"No soportado",Toast.LENGTH_SHORT).show();
            finish();

        }
        if (BA.isEnabled()){
            enable_bt.setChecked(true);
        }
        enable_bt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {


                if(!isChecked){
                    BA.disable();
                    Toast.makeText(MainActivity.this,"Apagado",Toast.LENGTH_SHORT).show();
                }else{
                    Intent intentoOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(intentoOn,0);
                    Toast.makeText(MainActivity.this,"Activado",Toast.LENGTH_SHORT).show();
                }


            }
        });

        visible_bt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(!isChecked){
                    Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                    startActivityForResult(getVisible,0);
                    Toast.makeText(MainActivity.this,"Activo por un momento",Toast.LENGTH_SHORT).show();
                }
            }
        });

        search_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            list();
            }
        });
    }


    private void list() {
        pairedDevice = BA.getBondedDevices();
        ArrayList listar = new ArrayList();

        for(BluetoothDevice bt : pairedDevice){
            listar.add(bt.getName());

        }
        Toast.makeText(MainActivity.this,"Activo por un momento",Toast.LENGTH_SHORT).show();
        ArrayAdapter adapter;
        adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, listar);
        list_view.setAdapter(adapter);
    }
    public String getLocalBluetoothName(){
        if (BA == null){
            BA = BluetoothAdapter.getDefaultAdapter();
        }
        String name;
        name = BA.getName();
        if (name == null){
            name = BA.getAddress();

        }
        return name;
    }

}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.g_talent.myapplication">

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

7
  • Podrias mostrar tu AndroidManifest.xml
    – Carlosgub
    el 11 sep. 2018 a las 15:07
  • @Carlosgub ahi lo edite el 11 sep. 2018 a las 15:10
  • te dije AndroidManifest.xml no el activity :D
    – Carlosgub
    el 11 sep. 2018 a las 15:11
  • @Carlosgub ahora si perdon xd el 11 sep. 2018 a las 15:15
  • 1
    Buenas @JuanManosalva según probé el código editado la única excepción que se me genera es al definir los componente del xml ya que veo que los estas colocando de esta forma enable_bt.findViewById(R.id.enable_bt); en donde yo los remplaze estos por lo siguiente enable_bt = (CheckBox) findViewById(R.id.enable_bt); visible_bt = (CheckBox) findViewById(R.id.visible_bt); name_bt = (TextView) findViewById(R.id.name_bt); search_bt = (ImageView) findViewById(R.id.search_bt); list_view = (ListView) findViewById(R.id.list_view); fíjate si no es por esto el error el 11 sep. 2018 a las 15:41

1 respuesta 1

3

Para obtener las referencias de los elementos debes usar el contexto que en este caso es la misma Activity para usar el método findViewById(), en realidad esto es incorrecto y es la línea donde se genera el error:

 enable_bt.findViewById(R.id.enable_bt);

si te encuentras en una Activity (como es tu caso) debe ser:

 enable_bt = (CheckBox)findViewById(R.id.enable_bt);

o también :

 enable_bt = (CheckBox)this.findViewById(R.id.enable_bt);

realiza lo mismo para los demás elementos.


si te encontraras dentro de un Fragment lo realizarías de esta forma usando como contexto la Activity que contiene el Fragment mediante el método getActivity():

enable_bt = (CheckBox)getActivity().findViewById(R.id.enable_bt);

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.