Android:添加微调器时获取nullpointer异常

时间:2014-07-28 08:43:07

标签: android nullpointerexception runtimeexception

当我在主要活动的oncreate方法中添加微调器时出现

错误,如果我删除那些行一切都很好......

MainActivity.java

package com.vibrator;

import android.annotation.SuppressLint;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

@SuppressLint("ShowToast")
public class MainActivity extends ActionBarActivity implements OnCheckedChangeListener, OnSeekBarChangeListener{

    ToggleButton tbutton;
    Vibrator v;
    int i;
    int j;
    TextView txt;
    SeekBar sb;
    TextView txt1;
    SeekBar sb1;
    Spinner spinner1;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActionBar bar = getSupportActionBar();
        bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#336699")));


        spinner1 = (Spinner) findViewById(R.id.spinner);
        Resources res=getResources();
        String str[]=res.getStringArray(R.array.spinner2);

        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, str);

        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        spinner1.setAdapter(adapter);



        //creating instance for vibrator
         v=(Vibrator) getSystemService(VIBRATOR_SERVICE);        
         //checking if the device has vibrator or not        
        if(v!=null){

            setContentView(R.layout.activity_main);
        }
        else {
            setContentView(R.layout.secound);
        }
            //Log.e("vibrate", "setcontentview");


        //creating instance of toggle buttton and setting listener
        tbutton=(ToggleButton) findViewById(R.id.tb1);
        tbutton.setOnCheckedChangeListener(this);

    }
    @Override
    public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
        Log.d("real status", ""+arg1);
        //if vibrator is ON
        if(arg1)
        {
            Log.d("vibrate", "if loop");
            Toast.makeText(this,"status: "+arg1, Toast.LENGTH_LONG).show();
            //creating instance of seekbar and textview
            sb=(SeekBar) findViewById(R.id.seekbar);
            txt=(TextView) findViewById(R.id.txt12);
            sb1=(SeekBar) findViewById(R.id.seekbar1);
            txt1=(TextView) findViewById(R.id.txt11);
            //changing visibility
            txt.setVisibility(View.VISIBLE);
            sb.setVisibility(View.VISIBLE);
            txt1.setVisibility(View.VISIBLE);
            sb1.setVisibility(View.VISIBLE);

            sb1.setOnSeekBarChangeListener(this);       
            sb.setOnSeekBarChangeListener(this);
            // Start without a delay
            // Vibrate for 100 j milliseconds
            // Sleep for 1000  (i) milliseconds         
            long[] pattern = {0, j, i};
            // The '0' here means to repeat indefinitely
            // '-1' would play the vibration once                       
            v.vibrate(pattern, 0);          
        }

        else {
            sb.setVisibility(View.INVISIBLE);
            txt.setVisibility(View.INVISIBLE);
            sb1.setVisibility(View.INVISIBLE);
            txt1.setVisibility(View.INVISIBLE);
            Log.d("vibrate", "else loop");
            Toast.makeText(this,"status: "+arg1, Toast.LENGTH_LONG).show();
            v.cancel();         
        }       
    }

    @Override
    public void onProgressChanged(SeekBar s, int v, boolean b) {
        tbutton.setChecked(false);
        switch (s.getId()) {
        case R.id.seekbar:
            i=v;            
            break;

        case R.id.seekbar1:
            j=v;
            break;

        }       
        txt.setText("Vibrator OFF time: "+i);
        txt1.setText("Vibrator ON time: "+j);

        tbutton.setChecked(true);

    }
    @Override
    public void onStartTrackingTouch(SeekBar arg0) {        
    }
    @Override
    public void onStopTrackingTouch(SeekBar arg0) {     
    }


}

当我运行项目时,我没有为微调器项设置任何监听器,它给出了运行时和nullpointer异常。

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#363636"
 >

    <ToggleButton
        android:id="@+id/tb1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textOn="OFF " 
        android:layout_marginTop="2dp"
        android:layout_marginBottom="2dp"
        android:textOff="ON"

        />

<RelativeLayout 
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <SeekBar
        android:id="@+id/seekbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txt12"
        android:max="100" 
        android:progress="15"
        android:visibility="gone"

        />

    <TextView
        android:id="@+id/txt12"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/sleep"
        android:textColor="#D5D5D5"
        android:visibility="gone" />

    </RelativeLayout>
    <RelativeLayout 
    android:id="@+id/rl1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <SeekBar
        android:id="@+id/seekbar1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txt11"
        android:max="100" 
        android:progress="15"
        android:visibility="gone"

        />

    <TextView
        android:id="@+id/txt11"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/wake"
        android:textColor="#D5D5D5"
        android:visibility="gone" />

    </RelativeLayout>
    <Spinner
    android:id="@+id/spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    android:visibility="visible"/>

</LinearLayout>

的strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Vibrator</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="notsupported">device not supported</string>
    <string name="sleep">Vibrator ON time: 15</string>
    <string name="wake">Vibrator OFF time: 15</string>
    <string-array name="spinner2">
        <item>Vibration Patterns</item>
        <item>Pattern 1</item>
        <item>Pattern 2</item>
        <item>Pattern 3</item>
        <item>Pattern 4</item>
        <item>Pattern 5</item>

    </string-array>

</resources>

logcat的

07-28 14:04:36.872: E/AndroidRuntime(739): FATAL EXCEPTION: main
07-28 14:04:36.872: E/AndroidRuntime(739): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.vibrator/com.vibrator.MainActivity}: java.lang.NullPointerException
07-28 14:04:36.872: E/AndroidRuntime(739):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
07-28 14:04:36.872: E/AndroidRuntime(739):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-28 14:04:36.872: E/AndroidRuntime(739):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-28 14:04:36.872: E/AndroidRuntime(739):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-28 14:04:36.872: E/AndroidRuntime(739):  at android.os.Handler.dispatchMessage(Handler.java:99)
07-28 14:04:36.872: E/AndroidRuntime(739):  at android.os.Looper.loop(Looper.java:123)
07-28 14:04:36.872: E/AndroidRuntime(739):  at android.app.ActivityThread.main(ActivityThread.java:4627)
07-28 14:04:36.872: E/AndroidRuntime(739):  at java.lang.reflect.Method.invokeNative(Native Method)
07-28 14:04:36.872: E/AndroidRuntime(739):  at java.lang.reflect.Method.invoke(Method.java:521)
07-28 14:04:36.872: E/AndroidRuntime(739):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-28 14:04:36.872: E/AndroidRuntime(739):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-28 14:04:36.872: E/AndroidRuntime(739):  at dalvik.system.NativeStart.main(Native Method)
07-28 14:04:36.872: E/AndroidRuntime(739): Caused by: java.lang.NullPointerException
07-28 14:04:36.872: E/AndroidRuntime(739):  at com.vibrator.MainActivity.onCreate(MainActivity.java:50)
07-28 14:04:36.872: E/AndroidRuntime(739):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-28 14:04:36.872: E/AndroidRuntime(739):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
07-28 14:04:36.872: E/AndroidRuntime(739):  ... 11 more

2 个答案:

答案 0 :(得分:0)

错误就在这里`

ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.array.spinner2,android.R.layout.simple_spinner_item)

` 您没有传递任何数组来向微调器添加项目,请执行以下代码片段

ArrayAdapter<String> myAdapter2=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,yourArray);//your array is holding the values to be displayedin the spinner,in arraylist

答案 1 :(得分:0)

我认为您的订单已更改。数组值(R.array.spinner2)应该在最后。请尝试以下代码。

    String[] spinner2Array = getResources().getStringArray(R.array.spinner2);
    ArrayAdapter<String> myAdapter2=new ArrayAdapter<String>  (this,android.R.layout.simple_spinner_item,spinner2Array);