2015-04-01 2 views
-1

У меня есть форма с одним редактором и автозаполнением. И кнопку для поиска вещей, основанных на этой форме. В этой форме я могу либо дать значение в edittext, и autocompleteview может быть пустым и наоборот. Исходя из этого, я передал значение этого представления другому действию, когда я сделал вызов webservice, а затем извлек результат.Исключение Null Pointer на кнопке onClick

Это деятельность, где их вид являются подарки:

@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); 
      } 
     } 
    }); 

} 

А в другой деятельности, я получаю эти дополнительные услуги от намерения и сделать WebService звонок в AsyncTask, но мое приложение разбивая. Пожалуйста, помогите мне, поскольку я новичок в андроиде.

Это моя другая деятельность

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); 
      } 
     } 
    } 
+0

где это грохот? трассировка стека исключения поможет. – Duiker101

+0

Просьба обмениваться журналами об ошибках/ошибках. – Satty

ответ

0

Согласно кода вы отправляете только одно значение в намерениях, которое «Название штата» или «Имя», а в другой деятельности, вы пытаетесь получить как значение, почему вы получаете исключение из null-указателя. Для решения этой проблемы используйте следующий код.

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); 
        } 
       } 
      }); 
Смежные вопросы