Button上的空指针异常onClick

时间:2015-04-01 10:33:35

标签: android

我有一个包含一个edittext和一个autocompleteview的表单。以及一个基于此表单搜索内容的按钮。在这种形式中,我可以在edittext中给出值,而autocompleteview可以是空的,反之亦然。在此基础上,我将这些视图的值传递给另一个活动,在那里我进行了webservice调用,然后获取结果。

这是展示这些观点的活动:

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

    searchByNameEditText = (EditText) findViewById(R.id.searchByNameEditText);

    searchByAddressEditText = (EditText) findViewById(R.id.searchByAddressEditText);

    searchButton = (Button) findViewById(R.id.searchButton);

    autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.selectStateSpinner);
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
            android.R.layout.simple_dropdown_item_1line,
            getResources().getStringArray(R.array.state_arrays));
    autoCompleteTextView.setAdapter(adapter);

    patientUtilityButton = (Button) findViewById(R.id.patientUtilityButton);
    patientUtilityButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            PopupMenu popupMenu = new PopupMenu(PatientSectionActivity.this, patientUtilityButton);

            popupMenu.getMenuInflater().inflate(R.menu.patient_utility_button_popmenu, popupMenu.getMenu());
            popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    String patientUtilityMenuItem = item.toString();
                    patientUtilityButton.setText(patientUtilityMenuItem);
                    return true;
                }
            });

            popupMenu.show();
        }
    });

    autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectedStateValue = (String) parent.getItemAtPosition(position);
        }
    });

    doctorName = searchByNameEditText.getText().toString();

    // Search Button
    searchButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (!selectedStateValue.equals(" ") || doctorName.equals(" ")){
                Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
                intent.putExtra("State Name", selectedStateValue);
                startActivity(intent);
            } else if (!doctorName.equals(" ") || selectedStateValue.equals(" ")){
                Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
                intent.putExtra("Name", doctorName);
                startActivity(intent);
            }
        }
    });

}

在其他活动中,我从intent获取这些额外内容并在AsyncTask中调用webservice,但我的应用程序崩溃了。请任何人帮助我,因为我是android的新手。

这是我的其他活动

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class DoctorNameActivity extends ActionBarActivity {

    ArrayAdapter<String> doctorAdapter;
    ListView listView;
    ProgressBar progressBar;
    String doctorName;
    String selectedStateValue;

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

        progressBar = (ProgressBar) findViewById(R.id.progress);

        listView = (ListView) findViewById(R.id.listView);

        Intent intent = getIntent();


        selectedStateValue = intent.getStringExtra("State Name");

        doctorName = intent.getStringExtra("Name");

        if (!selectedStateValue.equals(" ") || doctorName.equals(" ")){
            FetchDoctorName fetchDoctorName = new FetchDoctorName();
            fetchDoctorName.execute(selectedStateValue);
        }else if (!doctorName.equals(" ") || selectedStateValue.equals(" ")){
            FetchDoctorName fetchDoctorName = new FetchDoctorName();
            fetchDoctorName.execute(doctorName);

        }

    }


    private class FetchDoctorName extends AsyncTask<String, Void, String[]>{

        private final String LOG_TAG = FetchDoctorName.class.getSimpleName();

        public String[] parseDoctorName(String jsonString) throws JSONException{
            final String DOCTOR_NAME_ARRAY = "name";
            JSONObject object = new JSONObject(jsonString);
            JSONArray array = object.getJSONArray(DOCTOR_NAME_ARRAY);

            String[] doctorNamesResult = new String[array.length()];
            for (int i = 0 ; i < array.length(); i++){

                String doctorName = array.getString(i);
                Log.v(LOG_TAG, doctorName);

                doctorNamesResult[i] = doctorName;
            }
            return doctorNamesResult;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBar.setVisibility(ProgressBar.VISIBLE);
        }

        @Override
        protected String[] doInBackground(String... params) {

            // These two need to be declared outside the try/catch
            // so that they can be closed in the finally block.
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;

            // Will contain the raw JSON response as a string.
            String doctorJsonString = null;

            try {

                final String BASE_URL = "http://mycityortho.com/display_result.php";
                final String NAME_PARAM = "name";
                final String STATE_PARAM = "state";

                URL url = null;
                if (params[0].equals(doctorName)){
                    Uri uri = Uri.parse(BASE_URL).buildUpon()
                            .appendQueryParameter(NAME_PARAM, params[0])
                            .build();
                    url = new URL(uri.toString());
                    Log.v(LOG_TAG, url.toString());
                }else if (params[0].equals(selectedStateValue)){
                    Uri uri = Uri.parse(BASE_URL).buildUpon()
                            .appendQueryParameter(STATE_PARAM, params[0])
                            .build();
                    url = new URL(uri.toString());
                    Log.v(LOG_TAG, url.toString());
                }

                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                // Read the input stream into a String
                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                    // Nothing to do.
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                    // But it does make debugging a *lot* easier if you print out the completed
                    // buffer for debugging.
                    buffer.append(line + "\n");
                }

                if (buffer.length() == 0) {
                    // Stream was empty.  No point in parsing.
                    return null;
                }
                doctorJsonString = buffer.toString();
                Log.v(LOG_TAG, doctorJsonString);

            } catch (IOException e) {
                Log.e(LOG_TAG, "Error ", e);
                // If the code didn't successfully get the weather data, there's no point in attemping
                // to parse it.
                return null;
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e(LOG_TAG, "Error closing stream", e);
                    }
                }
            }

            try {
                return parseDoctorName(doctorJsonString);
            }catch (JSONException e){
                Log.e(LOG_TAG, e.getMessage(), e);
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String[] result) {

            progressBar.setVisibility(ProgressBar.GONE);
            if (result != null){
                doctorAdapter = new ArrayAdapter<>(DoctorNameActivity.this, android.R.layout.simple_list_item_1, result);
                listView.setAdapter(doctorAdapter);
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

根据您的代码,您只发送一个意图值,即#34;州名称&#34;或&#34;名称&#34;但在其他活动中,您尝试接收两个值,这就是为什么您会得到空指针异常。 因此,请使用以下代码来解决此错误。

    searchButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (!selectedStateValue.equals(" ") || doctorName.equals(" ")){
                        Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
                        intent.putExtra("State Name", selectedStateValue);
                        intent.putExtra("Name", " ");
                        startActivity(intent);
                    } else if (!doctorName.equals(" ") || selectedStateValue.equals(" ")){
                        Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
                        intent.putExtra("State Name", " ");
                        intent.putExtra("Name", doctorName);
                        startActivity(intent);
                    }
                }
            });