2014-01-23 2 views
0

여기에 제 코드에 문제가 있습니다. 검색 기능을 갖춘 사전을 개발하려고합니다. 데이터는 MySQl 데이터베이스에서 가져 오는 중입니다. 단어를 입력 할 때 충돌이 발생합니다. 도와주세요. 나는 내가 그렇게되기 위해 도착할 때까지 많은 수정을 시도하고 있었다. 누구 한테 도움이 되니?ListView에서 검색을 추가하면 단어를 입력 할 때 크래시가 발생합니다.

 package com.example.healthhelpv2; 

import java.sql.Blob; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 

import org.apache.http.NameValuePair; 
import org.apache.http.message.BasicNameValuePair; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import library.JSONParser2; 

import android.app.ListActivity; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.text.Editable; 
import android.text.TextWatcher; 
import android.util.Log; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.ArrayAdapter; 
import android.widget.AutoCompleteTextView; 
import android.widget.EditText; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.TextView; 

public class ListMedicineActivity extends ListActivity { 

    // Progress Dialog 
    private ProgressDialog pDialog; 

    // Creating JSON Parser object 
    JSONParser2 jParser = new JSONParser2(); 
    //private ArrayList arr_sort= new ArrayList(); 
    private ArrayList arr_sort= new ArrayList(); 
    ArrayList<HashMap<String, String>> patientsList; 
    ArrayAdapter<String> adapter; 
    //private ListView lv1; 
    private EditText et; 
    int textlength=0; 
    // url to get all products list 
    private static String url_all_medicine = "http://10.0.2.2/android_connect/get_all_medicines.php"; 
    private ListView lv; 
    // JSON Node names 
    private static final String TAG_SUCCESS = "success"; 
    private static final String TAG_MEDICINE = "medicine"; 
    private static final String TAG_MID = "mid"; 
    private static final String TAG_MED_NAME = "med_name"; 
    // private static final Blob TAG_IMG = "img"; 


    //private static final String TAG_MED_INFO = "med_info"; 


    // products JSONArray 
    JSONArray patients = null; 
    //ArrayAdapter adapter; 



    public void onBackPressed() { 
     super.onBackPressed(); 
     //userFunctions.logoutUser(getApplicationContext()); 
     Intent intent = new Intent(this, PatientHomeActivity.class); 
     startActivity(intent); 
    } 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.listmedicine); 


     // Hashmap for ListView 
     patientsList = new ArrayList<HashMap<String, String>>(); 
     //arr_sort = new ArrayList<HashMap<String, String>>(); 

     // Loading products in Background Thread 
     new LoadAllProducts().execute(); 

     // Get listview 
     lv = getListView(); 

     // on seleting single product 
     // launching Edit Product Screen 
     lv.setOnItemClickListener(new OnItemClickListener() { 

      @Override 
      public void onItemClick(AdapterView<?> parent, View view, 
        int position, long id) { 
       // getting values from selected ListItem 
       String mid = ((TextView) view.findViewById(R.id.mid)).getText() 
         .toString(); 

       // Starting new intent 
       Intent in = new Intent(getApplicationContext(), 
         MedInfoActivity.class); 
       // sending pid to next activity 
       in.putExtra(TAG_MID, mid); 

       // starting new activity and expecting some response back 
       startActivityForResult(in, 100); 
      } 
     }); 

     //search 
     lv=(ListView)findViewById(android.R.id.list); 
      et=(EditText)findViewById(R.id.searchtext); 

     //lv.setAdapter(new ArrayAdapter(this,android.R.layout.si mple_list_item_1 , patientsList)); 
     ArrayAdapter<String> adapter = new ArrayAdapter(this,R.layout.all_patient , R.id.med_name, patientsList); 

     lv.setAdapter(adapter);   


     et.addTextChangedListener(new TextWatcher() { 

      @Override 
      public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) { 
       // When user changed the Text 
       ListMedicineActivity.this.adapter.getFilter().filter(cs); 
      } 

      @Override 
      public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, 
        int arg3) { 
       // TODO Auto-generated method stub 

      } 
      @Override 
      public void afterTextChanged(Editable arg0) { 
       // TODO Auto-generated method stub       
      } 
      }); 

} 




    // Response from Edit Product Activity 
    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     // if result code 100 
     if (resultCode == 100) { 
      // if result code 100 is received 
      // means user edited/deleted product 
      // reload this screen again 
      Intent intent = getIntent(); 
      finish(); 
      startActivity(intent); 
     } 

    } 

    /** 
    * Background Async Task to Load all product by making HTTP Request 
    * */ 
    class LoadAllProducts extends AsyncTask<String, String, String> { 

     /** 
     * Before starting background thread Show Progress Dialog 
     * */ 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(ListMedicineActivity.this); 
      pDialog.setMessage("Loading medicines. Please wait..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(false); 
      pDialog.show(); 
     } 

     /** 
     * getting All products from url 
     * */ 
     protected String doInBackground(String... args) { 
      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 
      //params.add(new BasicNameValuePair("name","")); 
      // getting JSON string from URL 
      JSONObject json = jParser.makeHttpRequest(url_all_medicine, "GET", params); 

      // Check your log cat for JSON reponse 
      Log.d("All Medicines: ", json.toString()); 

      try { 
       // Checking for SUCCESS TAG 
       int success = json.getInt(TAG_SUCCESS); 

       if (success == 1) { 
        // products found 
        // Getting Array of Products 
        patients = json.getJSONArray(TAG_MEDICINE); 

        // looping through All Products 
        for (int i = 0; i < patients.length(); i++) { 
         JSONObject c = patients.getJSONObject(i); 

         // Storing each json item in variable 
         String id = c.getString(TAG_MID); 
         String name = c.getString(TAG_MED_NAME); 
    //     Blob img = c.getBlob(TAG_IMG); 

         // creating new HashMap 
         HashMap<String, String> map = new HashMap<String, String>(); 

         // adding each child node to HashMap key => value 
         map.put(TAG_MID, id); 
         map.put(TAG_MED_NAME, name); 
     //     map.put(TAG_IMG, img); 

         // adding HashList to ArrayList 
         patientsList.add(map); 
         //patientsList.add(json.getString("mid").toString()); 

        } 
       } else { 
        // no products found 
        // Launch Add New product Activity 
        Intent i = new Intent(getApplicationContext(), 
          RegisterActivity.class); 
        // Closing all previous activities 
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        startActivity(i); 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

      return null; 
     } 

     /** 
     * After completing background task Dismiss the progress dialog 
     * **/ 
     protected void onPostExecute(String file_url) { 
      // dismiss the dialog after getting all products 
      pDialog.dismiss(); 
      // updating UI from Background Thread 
      runOnUiThread(new Runnable() { 
       public void run() { 
        /** 
        * Updating parsed JSON data into ListView 
        * */ 
        ListAdapter adapter = new SimpleAdapter(
          ListMedicineActivity.this, patientsList, 
          R.layout.all_medicine, new String[] { TAG_MID, 
            TAG_MED_NAME}, 
          new int[] { R.id.mid, R.id.med_name}); 
        // updating listview 
        setListAdapter(adapter); 
       } 
      }); 

     } 

    } 
} 

이것은 오류 로그입니다.

01-26 09:30:56.372: E/AndroidRuntime(272): FATAL EXCEPTION: main 
01-26 09:30:56.372: E/AndroidRuntime(272): java.lang.NullPointerException 
01-26 09:30:56.372: E/AndroidRuntime(272): at com.example.healthhelpv2.ListMedicineActivity$2.onTextChanged(ListMedicineActivity.java:128) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.widget.TextView.sendOnTextChanged(TextView.java:6131) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.widget.TextView.handleTextChanged(TextView.java:6172) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:6316) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.text.SpannableStringBuilder.sendTextChange(SpannableStringBuilder.java:889) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:352) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:269) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:432) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:409) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:28) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.text.method.QwertyKeyListener.onKeyDown(QwertyKeyListener.java:195) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.text.method.TextKeyListener.onKeyDown(TextKeyListener.java:132) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.widget.TextView.doKeyDown(TextView.java:4304) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.widget.TextView.onKeyDown(TextView.java:4149) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.view.KeyEvent.dispatch(KeyEvent.java:1037) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.view.View.dispatchKeyEvent(View.java:3740) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:788) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:788) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:788) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:788) 
01-26 09:30:56.372: E/AndroidRuntime(272): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:1667) 
01-26 09:30:56.372: E/AndroidRuntime(272): at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1102) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.app.Activity.dispatchKeyEvent(Activity.java:2063) 
01-26 09:30:56.372: E/AndroidRuntime(272): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1643) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.view.ViewRoot.deliverKeyEventToViewHierarchy(ViewRoot.java:2471) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2441) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.view.ViewRoot.handleMessage(ViewRoot.java:1735) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.os.Handler.dispatchMessage(Handler.java:99) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.os.Looper.loop(Looper.java:123) 
01-26 09:30:56.372: E/AndroidRuntime(272): at android.app.ActivityThread.main(ActivityThread.java:4627) 
01-26 09:30:56.372: E/AndroidRuntime(272): at java.lang.reflect.Method.invokeNative(Native Method) 
01-26 09:30:56.372: E/AndroidRuntime(272): at java.lang.reflect.Method.invoke(Method.java:521) 
01-26 09:30:56.372: E/AndroidRuntime(272): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 
01-26 09:30:56.372: E/AndroidRuntime(272): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 
01-26 09:30:56.372: E/AndroidRuntime(272): at dalvik.system.NativeStart.main(Native Method) 

는이 내 listmedicine.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical"> 
    <!-- Main ListView 
     Always give id value as list(@android:id/list) 
    --> 

    <EditText 
     android:id="@+id/searchtext" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:ems="10" > 

     <requestFocus /> 
    </EditText> 

    <ListView 
     android:id="@android:id/list" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:divider="#b5b5b5" 
     android:dividerHeight="1dp" 
     android:listSelector="@drawable/list_selector" > 
    </ListView> 

</LinearLayout> 

누군가 내 코드 뭐가 잘못 나를 도울 수있는 내 all_medicine.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:background="@drawable/list_selector" 
    android:orientation="horizontal" 
    android:padding="5dip" > 

    <!-- Product id (pid) - will be HIDDEN - used to pass to other activity --> 


    <!-- Name Label --> 

    <TextView 
     android:id="@+id/med_name" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:textColor="#000000" 
     android:textSize="20dp" 
     android:textStyle="bold" /> 

    <TextView 
     android:id="@+id/mid" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:visibility="gone" /> 

<ImageView 
    android:id="@+id/imageView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentRight="true" 
    android:layout_centerVertical="true" 
    android:contentDescription="@string/app_name" 
    android:src="@drawable/arrow" /> 

</RelativeLayout> 

입니까? 당신이 날 도울 수 있기를 바랍니다.

+0

사용 AutoCompleteTextView에 작동합니다 수색. 그것은 어댑터에서 자동으로 검색합니다.이 링크를 확인 http://www.giantflyingsaucer.com/blog/?p=1342 ..이 링크는 sqlite와 autocomplete 텍스트 상자를 사용하는 방법을 보여줍니다. –

+0

나는 sqlite를 사용하지 않는다. xampp MySql Admin을 사용하고 있습니다. mySql을 사용하여 어떻게 할 수 있습니까? – user3226149

답변

0

시도해보십시오.

public void onTextChanged(CharSequence cs, int arg1, int arg2, 
      int arg3) { 
     // When user changed the Text 
     ListMedicineActivity.this.adapter.getFilter().filter(cs); 
    } 

추출물 예를

ArrayAdapter<String> adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1 , patientsList); 

lv1.setAdapter(adapter); 

의 클래스

 lv1.setAdapter(new ArrayAdapter(this,android.R.layout.simple_list_item_1 , patientsList)); 

제기에이 어댑터는 당신이 리스너에 하나를 사용할 수 있으며, 그것은을 위해

+0

만? 아직 자바에서 코드가 누락 되었습니까? ArrayAdapter coz에서와 같이 generic 형식에 대한 참조와 같은 경고를 표시합니다. arrayadapter를 매개 변수화해야합니까? – user3226149

+0

코드에 오류가 있습니다. 어댑터가 필드가 아닙니다. 미안 나는 안드로이드 프로 그램에서 초보자입니다. – user3226149

+0

내가 게시물을 편집하여 지금 확인하십시오. – Bri6ko

관련 문제