2017-04-23 3 views
0

내 mainactivity내 Bluetooth 응용 프로그램이 충돌 어떤 이유로

package com.example.vivek.trackblue; 
import android.bluetooth.BluetoothAdapter; 
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.Button; 
import android.widget.Toast; 

public class MainActivity extends AppCompatActivity { 
    BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter(); 
    Context context = getApplicationContext(); 
    CharSequence text = "Bluetooth is not supported"; 
    int duration = Toast.LENGTH_SHORT; 
    Toast toast1 = Toast.makeText(context, text, duration); 

    Button b1 = (Button)findViewById(R.id.button); 
    private final static int REQUEST_ENABLE_BT=1; 
@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     b1.setOnClickListener(new View.OnClickListener() 
     { 
      public void onClick(View view) 
      { 
       if(bt == null){ 
        toast1.show(); 
       } 
       if(bt.isEnabled()) 
       { 
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); 
       } 
      } 
     }); 

    } 
} 

이 내 AndroidManifest.xml을

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

package="com.example.vivek.trackblue"> 
<uses-permission android:name="android.permission.BLUETOOTH" /> 
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> 
<permission android:name="android.permission.BLUETOOTH" android:label="BLUETOOTH" /> 
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> 

<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    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> 

나는 사용자가 시작 버튼을 누르면 것입니다 응용 프로그램을 만들려고하고있다 블루투스.

내 코드는 ide에 오류가 표시되지 않지만 장치에 설치되면 "불행하게도 TrackBlue가 작동을 멈췄습니다."라는 오류 메시지와 함께 충돌합니다. 여기 trackblue는 내 응용 프로그램의 이름입니다.

+2

충돌의 구체적인 이유는 당신의 스택 트레이스에 아마 내부 같이 findViewById() 된 setContentView 후 라인()를 작성합니다. 그래서 귀하의 질문에 그것을 추가하십시오. – GVillani82

+0

스택 트레이스를 얻는 방법? –

+0

질문하기 전에 해당 대화 상자의 텍스트를 찾으려고 했습니까? http://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this –

답변

3

단순히 화면의 콘텐츠보기를 설정하기 전에 버튼 변수에 값을 할당했기 때문에 가능합니다.

오류는 화면에 설정되기 전에도 지정된 단추의 ID로보기를 찾으려고하기 때문에 발생합니다.

해결 방법 : 에서 onCreate()

+0

고마워요. id 속성을 선언하기 전에 id 속성에 액세스하려고 시도하는 것 같았습니다. 나 맞아? –

+0

예, 문제가있었습니다. –