无法解决NullPointerException

时间:2016-03-27 04:39:03

标签: java android

Logcat显示运行时错误,我无法检测到问题 我的location_page.java

    package com.example.sunny.myapplication2;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;

/**
 * Created by sunny on 3/26/2016.
 */
public class location_page extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks
    ,GoogleApiClient.OnConnectionFailedListener,View.OnClickListener{


    //Declaring Variables
    protected GoogleApiClient myGoogleApiClient;

    private static final LatLngBounds myBounds = new LatLngBounds(
            new LatLng(-0,0),new LatLng(0,0));

    private EditText myATView;
    private RecyclerView myRecyclerView;
    private LinearLayoutManager myLinearLayoutManager;
    private AT_Adapter myATAdapter;
    Button clearText;


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

        // Assigning Values to Variables
        myATView = (EditText)findViewById(R.id.autocomplete_tv);
        clearText = (Button)findViewById(R.id.clear_text_Button);
        myATAdapter = new AT_Adapter(this,R.layout.search_row,myGoogleApiClient,myBounds,null);
        myRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
        myLinearLayoutManager = new LinearLayoutManager(this);
        myRecyclerView.setLayoutManager(myLinearLayoutManager);
        myRecyclerView.setAdapter(myATAdapter);
        clearText.setOnClickListener(this);

        //Setting the editText Listener
        myATView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if(!s.toString().equals("") && myGoogleApiClient.isConnected()) {

                    myATAdapter.getFilter().filter(s.toString());
                }

               else if(!myGoogleApiClient.isConnected())
                {
                    Toast.makeText(location_page.this, "Google Api Client is not connected",
                            Toast.LENGTH_SHORT).show();
                }
            }


            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // ToDO The Auto-Generated Stub
            }

            @Override
            public void afterTextChanged(Editable s) {
                // ToDo The Auto-Generated Stub
            }
        });



        myRecyclerView.addOnItemTouchListener(
                new Recycler_Listener(this,new Recycler_Listener.OnItemClickListener(){
                    @Override
                    public  void onItemClick(View view,int position){
                        final AT_Adapter.PlaceAutoComplete  item = myATAdapter.getItem(position);
                        final String placeId = String.valueOf(item.placeId);


                        PendingResult<PlaceBuffer>placeResult = (PendingResult<PlaceBuffer>)Places.GeoDataApi
                                .getPlaceById(myGoogleApiClient,placeId);
                        placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
                            @Override
                            public void onResult(PlaceBuffer places) {
                                if(places.getCount()==1){
                                    Toast.makeText(getApplicationContext(),String.valueOf(places.get(0).getLatLng()),
                                            Toast.LENGTH_LONG).show();
                                }
                            }
                        });
                    }
                }
                )
        );

    }



    protected synchronized void buildGoogleApiClient(){
        myGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .addApi(Places.GEO_DATA_API)
                .build();
    }

    @Override
    public void onConnected(Bundle bundle) {
     // ToDO The Auto-Generated Stub
    }

    @Override
    public void onConnectionSuspended(int i) {
        // ToDO The Auto-Generated Stub
    }

    @Override
    public void onClick(View v) {
        if(v == clearText){
            myATView.setText("");
        }

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        // ToDO The Auto-Generated Stub
    }

    @Override
    public void onResume(){
        super.onResume();
        if(!myGoogleApiClient.isConnected() && !myGoogleApiClient.isConnecting()){
            myGoogleApiClient.connect();
        }
    }
    @Override
    public void onPause(){
        super.onPause();
        if(myGoogleApiClient.isConnected())
            myGoogleApiClient.disconnect();

    }

    @Override
    public void onBackPressed(){
        super.onBackPressed();
    }
}

我的AT_Adapter.java文件是

    package com.example.sunny.myapplication2;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.AutocompleteFilter;
import com.google.android.gms.location.places.AutocompletePrediction;
import com.google.android.gms.location.places.AutocompletePredictionBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.model.LatLngBounds;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;

/**
 * Created by sunny on 3/26/2016.
 */
public class AT_Adapter extends RecyclerView.Adapter
    <AT_Adapter.PredictionHolder> implements Filterable{

    private ArrayList<PlaceAutoComplete>myResultList;
    private GoogleApiClient myGoogleApiClient;
    private LatLngBounds myBounds;
    private AutocompleteFilter myAutoCompleteFilter;

    private Context myContext;
    private int layout;
    private char[] description;

    public AT_Adapter(Context context,int resource,GoogleApiClient googleApiClient,
                      LatLngBounds latLngBounds,AutocompleteFilter autocompleteFilter){
        myContext = context;
        layout = resource;
        myGoogleApiClient = googleApiClient;
        myBounds = latLngBounds;
        myAutoCompleteFilter = autocompleteFilter;
    }
    /*
        ** Set the Bounds for all subsequent queries
     */
    public void setBounds(LatLngBounds bounds){
        myBounds =bounds;
    }

    /*
    ** Returns the filter for Current Set of AutoComplete Result
    */

    @Override
    public Filter getFilter(){
        Filter filter = new Filter(){
            @Override
            protected FilterResults performFiltering(CharSequence constraint){
                FilterResults results = new FilterResults();
                //Skip The AutoComplete query if no constraints are given
                if(constraint != null){
                    //Query The AutoComplete Api for constraint String
                    myResultList = getAutoComplete(constraint);
                    if(myResultList != null){
                        //Api successfully returned results.
                        results.values = myResultList;
                        results.count = myResultList.size();
                    }

                }
                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if(results != null && results.count > 0){
                    //The Api returned atleast one result,update the result
                    notifyDataSetChanged();
                }
                else {
                    //The Api did not return any result
                    //notifyDataSetInvalid();
                }

            }


        };
        return filter;
    }

    private ArrayList<PlaceAutoComplete> getAutoComplete(CharSequence constraint) {
        if(myGoogleApiClient.isConnected()){
            //Submit the query to the AutoComplete API and retrieve a PendingResult that
            //contain results when query completes
            PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi
                    .getAutocompletePredictions(myGoogleApiClient,constraint.toString(),
                            myBounds,myAutoCompleteFilter);

            // This method should have been called off the main UI thread. Block and wait for at most 60s
            // for a result from the API

            AutocompletePredictionBuffer autocompletePredictions = results.await(60, TimeUnit.SECONDS);
            // Confirm that the query completed successfully, otherwise return null
            final Status status = autocompletePredictions.getStatus();
            if(!status.isSuccess()){
                Toast.makeText(myContext,"Error Contacting Api"+status.toString(),
                        Toast.LENGTH_LONG).show();
                autocompletePredictions.release();
                return null;
            }
            // Copy the results into our own data structure, because we can't hold onto the buffer.
            // AutocompletePrediction objects encapsulate the API response (place ID and description).
            Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator();
            ArrayList resultlist = new ArrayList<>(autocompletePredictions.getCount());
            while (iterator.hasNext()){
                AutocompletePrediction prediction = iterator.next();
                // Get the details of this prediction and copy it into a new PlaceAutocomplete object.
                resultlist.add(new PlaceAutoComplete(prediction.getPlaceId(),
                        prediction.getDescription()));
            }
            // Release the buffer now that all data has been copied.
            autocompletePredictions.release();
            return resultlist;
        }
        return null;
    }


    @Override
    public PredictionHolder onCreateViewHolder(ViewGroup parent, int i) {
        LayoutInflater layoutInflater = (LayoutInflater)myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View convertView = layoutInflater.inflate(layout,parent,false);
        PredictionHolder myPredictionHolder = new PredictionHolder(convertView);
        return myPredictionHolder;
    }

    @Override
    public void onBindViewHolder(PredictionHolder holder, int i) {
     holder.myPrediction.setText(myResultList.get(i).description);
    }


    @Override
    public int getItemCount() {
        if(myResultList!=null){
            return myResultList.size();
        }
        else
        return 0;
    }

    public PlaceAutoComplete getItem(int position){
            return myResultList.get(position);
    }




    public class PredictionHolder extends RecyclerView.ViewHolder {
        private TextView myPrediction;
        private RelativeLayout myRow;
        public PredictionHolder(View itemView){
            super(itemView);
            myPrediction = (TextView)itemView.findViewById(R.id.address);
            myRow = (RelativeLayout)itemView.findViewById(R.id.autocomplete_row);

    }

}

    public class PlaceAutoComplete {
        public CharSequence placeId;
        public CharSequence description;

        PlaceAutoComplete(CharSequence placeId, CharSequence description) {
            this.placeId = placeId;
            this.description = description;
        }

        @Override
        public String toString() {
            return description.toString();
        }
    }
}

和Recycler_Listener.java是

package com.example.sunny.myapplication2;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by sunny on 3/26/2016.
 */
public class Recycler_Listener implements RecyclerView.OnItemTouchListener {

    private OnItemClickListener myOnItemClickListener;

    GestureDetector myGestureDetector;

    public interface OnItemClickListener{
        public void onItemClick(View view,int position);


    }

    public Recycler_Listener(Context context,OnItemClickListener listener){
        myOnItemClickListener = listener;
        myGestureDetector = new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
            @Override public boolean onSingleTapUp(MotionEvent e){
                return true;
            }
        }
        );
    }
    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
        View childView = rv.findChildViewUnder(e.getX(),e.getY());
        if(childView != null && myOnItemClickListener != null && myGestureDetector.onTouchEvent(e)){
            myOnItemClickListener.onItemClick(childView,rv.getChildLayoutPosition(childView));
            return true;
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {
    // TODO THE AUTO-GENERATED STUFF
    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
    // TODO THE AUTOGENERATED STUFF
    }


}

并且manifest.xml是

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sunny.myapplication2">
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Base.Theme.AppCompat.Light">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyC8kZ4aF38gKVfBB-9S8k5BZkj9vDrHLtc"/>
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />


        //Main_Activity
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        //Register
        <activity android:name=".register_final"
            android:label="register_final"
            android:theme="@style/Base.Theme.AppCompat.Light">
        </activity>

        //Location
        <activity android:name=".location_page">

        </activity>
    </application>

</manifest>

并且logcat错误是

03-27 00:29:22.999 16719-16719/com.example.sunny.myapplication2 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                  Process: com.example.sunny.myapplication2, PID: 16719
                                                                                  java.lang.RuntimeException: Unable to resume activity {com.example.sunny.myapplication2/com.example.sunny.myapplication2.location_page}: java.lang.NullPointerException
                                                                                      at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2774)
                                                                                      at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2803)
                                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2238)
                                                                                      at android.app.ActivityThread.access$800(ActivityThread.java:135)
                                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                                                                                      at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                      at android.os.Looper.loop(Looper.java:136)
                                                                                      at android.app.ActivityThread.main(ActivityThread.java:5001)
                                                                                      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:785)
                                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                                                                                      at dalvik.system.NativeStart.main(Native Method)
                                                                                   Caused by: java.lang.NullPointerException
                                                                                      at com.example.sunny.myapplication2.location_page.onResume(location_page.java:152)
                                                                                      at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1192)
                                                                                      at android.app.Activity.performResume(Activity.java:5310)
                                                                                      at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2764)
                                                                                      at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2803) 
                                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2238) 
                                                                                      at android.app.ActivityThread.access$800(ActivityThread.java:135) 
                                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
                                                                                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                      at android.os.Looper.loop(Looper.java:136) 
                                                                                      at android.app.ActivityThread.main(ActivityThread.java:5001) 
                                                                                      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:785) 
                                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
                                                                                      at dalvik.system.NativeStart.main(Native Method) 

当我尝试运行该程序时,发生了Logcat错误并且应用程序不幸停止

0 个答案:

没有答案