Question

I am having a problem with my code here. I am trying to develop dictionary with search. The data are being fetched from the MySQl database. When typing words, it crashes. Please Help. I've been trying lots of modification until i arrive asking in SO. Anyone help?

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

        }

    }
}

This is the error log.

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)

and this is my 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>

and my 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>

could anyone help me what's wrong with my code?Hope you can help me.

Was it helpful?

Solution

Try this.

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

extract this adapter to filed in the class

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

for example

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

lv1.setAdapter(adapter);

then you can use that one in the listener and it should work

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top