由旋转器引起的Android App崩溃

时间:2015-03-30 11:46:18

标签: android crash spinner

我的Android应用程序在启动时崩溃,它在我尝试添加微调器之前工作正常,所以我确定它是问题但我无法弄清楚这里是我的代码:

MainActivity.java

    package synctc.me.stormy;

    import android.content.Context;
    import android.graphics.drawable.Drawable;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.ProgressBar;
    import android.widget.RelativeLayout;
    import android.widget.Spinner;
    import android.widget.TextView;
    import android.widget.Toast;
    import com.squareup.okhttp.Call;
    import com.squareup.okhttp.Callback;
    import com.squareup.okhttp.OkHttpClient;
    import com.squareup.okhttp.Request;
    import com.squareup.okhttp.Response;

    import org.json.JSONException;
    import org.json.JSONObject;

    import java.io.IOException;

    import butterknife.ButterKnife;
    import butterknife.InjectView;


    public class MainActivity extends ActionBarActivity implements AdapterView.OnItemSelectedListener{
        public static final String TAG = MainActivity.class.getSimpleName();
       private CurrentWeather mCurrentWeather ;


        @InjectView(R.id.timeLabel) TextView mTimeLabel;
        @InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
        @InjectView(R.id.humidityValue) TextView mHumidityValue;
        @InjectView(R.id.precipValue) TextView mPrecipValue;
        @InjectView(R.id.iconImageView) ImageView mIconImageView;
        @InjectView(R.id.refreshImageView) ImageView mRefreshImageView;
        @InjectView(R.id.progressBar)ProgressBar mProgressBar;
        @InjectView(R.id.textView) TextView mTextView;
        @InjectView(R.id.locationLabel) TextView mTimeZone;
        Spinner spinner = (Spinner) findViewById(R.id.spinner);
         double latitude = 31.956578300000000000;
         double longitude = 35.945695099999966000;

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

            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                    R.array.Country_array, android.R.layout.simple_spinner_item);

            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner.setAdapter(adapter);

            setContentView(R.layout.activity_main);
            ButterKnife.inject(this);
            mProgressBar.setVisibility(View.INVISIBLE);
            mRefreshImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getForecast(latitude,longitude);
                }
            });



            getForecast(latitude,longitude);

                Log.d(TAG, "Main ui is running");
        }

        private void getForecast(double latitude, double longitude) {
            String apiKey="37ee485ed1ec27026ef5ff8948b6f94b";
            String forecastUrl="https://api.forecast.io/forecast/"+apiKey+"/"+latitude+","+longitude;
            if(isNetworkAvailable()){
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(forecastUrl)
                    .build();
            Call call=client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            toggleRefresh();
                        }
                    });
                    alertUserAboutError();
                }

                @Override
                public void onResponse(Response response) throws IOException {
                 runOnUiThread(new Runnable() {
                     @Override
                     public void run() {
                         toggleRefresh();
                     }
                 });
                    try {
                          String jsonData = response.body().string();
                        Log.v(TAG, jsonData);
                        if(response.isSuccessful()){
                         mCurrentWeather = getCurrentDetails(jsonData);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    updateDisplay();
                                }
                            });

                        }else{
                         alertUserAboutError();
                        }
                    } catch (IOException e) {
                        Log.e(TAG, "Exception Caught : ",e);

                    }
                    catch (JSONException e){

                        Log.e(TAG, "Exception Caught : ",e);
                    }

                }
            });}
            else{
                Toast.makeText(this
                        , getString(R.string.network_unavailable_messege)
                        , Toast.LENGTH_LONG).show();

            }
        }


        private void updateDisplay() {
            mTemperatureLabel.setText(mCurrentWeather.getTemperature()+"");
            mTimeLabel.setText("At" +mCurrentWeather.getFormattedTime()+"\n"+"  it will be ");
            mHumidityValue.setText(mCurrentWeather.getHumidity()+"");
            mPrecipValue.setText(mCurrentWeather.getPrecipChane()+"%");
            mTextView.setText(mCurrentWeather.getSummary()+"");
            Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
            mIconImageView.setImageDrawable(drawable);
            mTimeZone.setText(mCurrentWeather.getTimeZone()+"");


        }

        private CurrentWeather getCurrentDetails(String jsonData) throws JSONException{
            JSONObject forecast = new JSONObject (jsonData);
            String timezone = forecast.getString("timezone");
            Log.i(TAG,"From JSON To:"+timezone);
            JSONObject currently = new JSONObject(forecast.get("currently").toString());
            CurrentWeather currentWeather = new CurrentWeather();
            currentWeather.setHumidity(currently.getDouble("humidity"));
            currentWeather.setTime(currently.getLong("time"));
            currentWeather.setIcon(currently.getString("icon"));
            currentWeather.setPrecipChane(currently.getDouble("precipProbability"));
            currentWeather.setSummary(currently.getString("summary"));
            currentWeather.setTemperature(currently.getDouble("temperature"));
            double fehTemp = currentWeather.getTemperature();
            double celTemp = ((fehTemp-32)*5)/9;
            currentWeather.setTemperature(celTemp);
            currentWeather.setTimeZone(timezone);
            Log.d(TAG, currentWeather.getFormattedTime());

            return  currentWeather;
        }

        private boolean isNetworkAvailable() {

            toggleRefresh();


            ConnectivityManager manager = (ConnectivityManager)
                    getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = manager.getActiveNetworkInfo();
            boolean isAvailable = false;
            if(networkInfo != null &&networkInfo.isConnected()){
                isAvailable=true ;

            }
            return  isAvailable;

        }

        private void toggleRefresh() {
            if(mProgressBar.getVisibility()== View.INVISIBLE) {
                mProgressBar.setVisibility(View.VISIBLE);
                mRefreshImageView.setVisibility(View.INVISIBLE);
            }else{
                mProgressBar.setVisibility(View.INVISIBLE);
                mRefreshImageView.setVisibility(View.VISIBLE);

            }
        }

        private void alertUserAboutError() {
            AlertDialogFragment dialog = new AlertDialogFragment();
            dialog.show(getFragmentManager(), "error_dialog");

        }


        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            String text = spinner.getSelectedItem().toString();

            switch(text){

                case "Jordan":
                latitude = 31.956578300000000000;
                longitude = 35.945695099999966000;
    break;

                case "Palestine":
                   latitude = 31.952162000000000000;
                   longitude = 35.233154000000010000;
    break;

                case "KSA":
                    latitude = 23.885942000000000000;
                    longitude = 45.079162000000000000;
    break;
                case "UAE":
                    latitude = 25.241151000000000000;
                    longitude = 55.365769000000000000;
    break;

            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    }

AlertDialogFragment.java

package synctc.me.stormy;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.os.Bundle;


public class AlertDialogFragment extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Context context = getActivity();

        AlertDialog.Builder builder = new AlertDialog.Builder(context)
        .setTitle(context.getString(R.string.error_title))
                .setMessage(context.getString(R.string.error_messege))
                .setPositiveButton(context.getString(R.string.error_ok_button_text), null);
        AlertDialog dialog = builder.create();
        return dialog;
    }
}

CurrentWeather.java

package synctc.me.stormy;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;


public class CurrentWeather {
   private String mIcon;
    private long  mTime;
    private double mTemperature;
    private double mHumidity;




    private double mPrecipChane;
    private String mSummary;
    private String mTimeZone;

    public String getIcon() {
        return mIcon;
    }

    public void setIcon(String icon) {
        mIcon = icon;
    }
    public int getIconId(){
        int iconId = R.mipmap.clear_day;
        if (mIcon.equals("clear-day")) {
            iconId = R.mipmap.clear_day;
        }
        else if (mIcon.equals("clear-night")) {
            iconId = R.mipmap.clear_night;
        }
        else if (mIcon.equals("rain")) {
            iconId = R.mipmap.rain;
        }
        else if (mIcon.equals("snow")) {
            iconId = R.mipmap.snow;
        }
        else if (mIcon.equals("sleet")) {
            iconId = R.mipmap.sleet;
        }
        else if (mIcon.equals("wind")) {
            iconId = R.mipmap.wind;
        }
        else if (mIcon.equals("fog")) {
            iconId = R.mipmap.fog;
        }
        else if (mIcon.equals("cloudy")) {
            iconId = R.mipmap.cloudy;
        }
        else if (mIcon.equals("partly-cloudy-day")) {
            iconId = R.mipmap.partly_cloudy;
        }
        else if (mIcon.equals("partly-cloudy-night")) {
            iconId = R.mipmap.cloudy_night;
        }

        return iconId;
    }

    public long getTime() {
        return mTime;
    }

    public String getFormattedTime(){
        SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
        formatter.setTimeZone(TimeZone.getTimeZone(getTimeZone()));
        Date datetime = new Date(getTime()*1000);
        String timeString = formatter.format(datetime);
        return timeString;

    }


    public void setTime(long time) {
        mTime = time;
    }

    public int getTemperature() {
        return(int)  Math.round(mTemperature);
    }

    public void setTemperature(double temperature) {
        mTemperature = temperature;
    }

    public double getHumidity() {
        return mHumidity;
    }

    public void setHumidity(double humidity) {
        mHumidity = humidity;
    }

    public String getSummary() {
        return mSummary;
    }

    public void setSummary(String summary) {
        mSummary = summary;
    }

    public int getPrecipChane() {
        double precipPercentage = mPrecipChane * 100;
        return (int)Math.round(precipPercentage) ;
    }



    public String getTimeZone() {
        return mTimeZone;
    }

    public void setTimeZone(String timeZone) {
        mTimeZone = timeZone;
    }

    public void setPrecipChane(double precipChane) {
        mPrecipChane = precipChane;
    }
}

并且在strings.xml中我放了

<string-array name="Country_array">
        <item>Jordan</item>
        <item>Palestine</item>
        <item>UAE</item>
        <item>KSA</item>
    </string-array>

这是整个logcat:

03-30 11:40:59.238    1901-1901/synctc.me.stormy D/AndroidRuntime﹕ Shutting down VM
    --------- beginning of crash
03-30 11:40:59.239    1901-1901/synctc.me.stormy E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: synctc.me.stormy, PID: 1901
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{synctc.me.stormy/synctc.me.stormy.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
            at android.app.Activity.findViewById(Activity.java:2071)
            at synctc.me.stormy.MainActivity.<init>(MainActivity.java:50)
            at java.lang.reflect.Constructor.newInstance(Native Method)
            at java.lang.Class.newInstance(Class.java:1572)
            at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
03-30 11:41:08.206    2004-2004/synctc.me.stormy D/AndroidRuntime﹕ Shutting down VM
03-30 11:41:08.206    2004-2004/synctc.me.stormy E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: synctc.me.stormy, PID: 2004
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{synctc.me.stormy/synctc.me.stormy.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
            at android.app.Activity.findViewById(Activity.java:2071)
            at synctc.me.stormy.MainActivity.<init>(MainActivity.java:50)
            at java.lang.reflect.Constructor.newInstance(Native Method)
            at java.lang.Class.newInstance(Class.java:1572)
            at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:background="#FFFC970B"
    android:id="@+id/summaryLabel">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="100"
        android:id="@+id/temperatureLabel"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:textColor="@android:color/white"
        android:textSize="150sp"
        android:src="@mipmap/refresh"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/degreeImageView"
        android:layout_alignTop="@+id/temperatureLabel"
        android:layout_toRightOf="@+id/temperatureLabel"
        android:layout_toEndOf="@+id/temperatureLabel"
        android:src="@mipmap/degree"
        android:layout_marginTop="50dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="at 5:00pm it will be :"
        android:id="@+id/timeLabel"
        android:layout_above="@+id/temperatureLabel"
        android:layout_centerHorizontal="true"
        android:textColor="#80ffffff"
        android:textSize="18sp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Alcatraz Island, CA"
        android:id="@+id/locationLabel"
        android:layout_above="@+id/timeLabel"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="60dp"
        android:textColor="@android:color/white"
        android:textSize="24sp"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/iconImageView"
        android:layout_alignBottom="@+id/locationLabel"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:src="@mipmap/cloudy_night"/>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/temperatureLabel"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:weightSum="100"
        android:id="@+id/linearLayout">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="50"
            android:touchscreenBlocksFocus="false">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="HUMIDITY"
                android:id="@+id/humidityLabel"
                android:textColor="#80ffffff"
                android:gravity="center_horizontal"/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="0.88"
                android:id="@+id/humidityValue"
                android:textColor="@android:color/white"
                android:textSize="24sp"
                android:gravity="center_horizontal"/>
        </LinearLayout>

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="50">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="RAIN/SNOW?"
                android:id="@+id/precipLabel"
                android:textColor="#80ffffff"
                android:gravity="center_horizontal"/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="100%"
                android:id="@+id/precipValue"
                android:textColor="@android:color/white"
                android:textSize="24sp"
                android:gravity="center_horizontal"/>
        </LinearLayout>
    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stormy with a chance of meatballs"
        android:id="@+id/textView"
        android:layout_below="@+id/linearLayout"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:textColor="@android:color/white"
        android:textSize="18dp"
        android:gravity="center_vertical"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/refreshImageView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:src="@mipmap/refresh"/>

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/progressBar"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_alignBottom="@+id/refreshImageView"/>

    <Spinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/spinner"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_above="@+id/progressBar"
        android:entries="@array/country_arrays"
        />
</RelativeLayout>

2 个答案:

答案 0 :(得分:4)

Spinner spinner = (Spinner) findViewById(R.id.spinner);

永远不要在 findViewById()之后之前致电setContentView()。在onCreate()来电后,将初始化移至setContentView()方法。

答案 1 :(得分:1)

    @InjectView(R.id.textView) TextView mTextView;
    @InjectView(R.id.locationLabel) TextView mTimeZone;
    @InjectView(R.id.spinner) Spinner spinner;
     double latitude = 31.956578300000000000;
     double longitude = 35.945695099999966000;

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

    setContentView(R.layout.activity_main);
            ButterKnife.inject(this);

            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
        this,
                    R.array.Country_array, 
        android.R.layout.simple_spinner_item);

            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner.setAdapter(adapter);

            mProgressBar.setVisibility(View.INVISIBLE);

您需要注意调用setContentView()和Butterknife.inject()的顺序。