2017-04-23 111 views
0

我mainactivity我的藍牙應用程序崩潰的某些原因

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

墜機的具體原因可能是你的堆棧跟蹤。所以請把它添加到你的問題中。 – GVillani82

+0

如何獲取堆棧跟蹤? –

+0

在問這個問題之前,您是否嘗試過在對話框中搜索文本? http://stackoverflow.com/questions/23353173/uncomfort-myapp-has-stopped-how-can-i-solve-this –

回答

3

只是因爲您已經在設置屏幕的內容視圖之前爲按鈕變量賦值。

錯誤是因爲它甚至在它被設置爲屏幕之前試圖通過給定按鈕的ID來查找視圖。

解決方案: 寫findViewById()後的setContentView線()的onCreate()

+0

謝謝你的工作。就像我在聲明它們之前試圖訪問id屬性一樣。我對麼? –

+0

是的,這是問題所在。 –

相關問題