jeudi 5 novembre 2015

Display Data Based from the ID of the table Android SQLite

I'm developing an app composed of hospitals and doctors, when the user opens the app, list of hospital will display then when the user click one of the list, profile of the hospital will display and inside of that layout, theres a button that display the doctors and i dont know how to call the doctors based from the ID of hospital. I'll post my database helper and main activity code. I'll try the same approach of listview of hospital but i got error. As you can see in my code below, i created a query to display the doctor based on the KEY_HOSPITALID

DatabaseHelper

public class DatabaseHelper extends SQLiteOpenHelper {

    private static String DB_PATH = "/data/data/com.example.jathniel.doctorlist/databases/";
    private static String DB_NAME = "mydoctorfinder_new_migrate.sqlite";
    private SQLiteDatabase myDataBase;
    private Context myContext = null;


    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, 1);
        this.myContext = context;
    }

    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();

        if (dbExist) {
            // do nothing - database already exist
        } else {

            // By calling this method an empty database will be created into
            // the default system path
            // of your application so we are gonna be able to overwrite that
            // database with our database.
            this.getReadableDatabase();

            try {

                copyDataBase();

            } catch (IOException e) {

                throw new Error("Error copying database");
            }
        }
    }

    public void copyDataBase() throws IOException {
        InputStream myInput = this.myContext.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_NAME;
        FileOutputStream myOutput = new FileOutputStream(outFileName);
        byte[] buffer = new byte[1024];

        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

    public boolean checkDataBase() {
        SQLiteDatabase checkDB = null;

        try {
            String e = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(e, null, 0);
        } catch (SQLiteException e) {
            ;
        }

        if (checkDB != null) {
            checkDB.close();
        }

        return checkDB != null;
    }

    public void openDataBase() throws SQLException {
        String myPath = DB_PATH + DB_NAME;
        this.myDataBase = SQLiteDatabase.openDatabase(myPath, null, 0);
    }

    public synchronized void close() {
        if (this.myDataBase != null) {
            this.myDataBase.close();
        }

        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }


    public HospitalModel getHospital(int id){

        HospitalModel hospital = new HospitalModel();
        String selectQuery =
                "SELECT id,listing_type_id,listing_title,street,latitude,longitude FROM listing_hospitals WHERE id = "+id;
        Log.e("hospital query: ", selectQuery);
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            hospital.setid(cursor.getInt(cursor.getColumnIndex(KEY_HOSPITALID)));
            hospital.setlistingid(cursor.getInt(cursor.getColumnIndex(KEY_HOSPITALTYPEID)));
            hospital.sethospital(cursor.getString(cursor.getColumnIndex(KEY_HOSPITAL)));
            hospital.setstreet(cursor.getString(cursor.getColumnIndex(KEY_HOSPITALSTREET)));
            hospital.setlatitude(cursor.getString(cursor.getColumnIndex(KEY_HOSPITALLATITUDE)));
            hospital.setlongitude(cursor.getString(cursor.getColumnIndex(KEY_HOSPITALLONGITUDE)));
        } while (cursor.moveToNext());

        cursor.close();
        return hospital;
    }



    /****************************************************************************************
     *                                      HOSPITALS
     ****************************************************************************************/

    final static String KEY_HOSPITALID = "id",
            KEY_HOSPITALTYPEID = "listing_type_id",
            KEY_HOSPITAL = "listing_title",
            KEY_HOSPITALSTREET = "street",
            KEY_HOSPITALLATITUDE = "latitude",
            KEY_HOSPITALLONGITUDE = "longitude";

    public List<HospitalModel> getAllHospital(int index) {

        final int maxCount = 20;

        List<HospitalModel> hList = new ArrayList<HospitalModel>();

            String selectQuery =
                    "SELECT id,listing_type_id,listing_title,street,latitude,longitude FROM listing_hospitals LIMIT "+index+", "+maxCount;
            Log.e("hospital query: ", selectQuery);
            SQLiteDatabase db = this.getReadableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);
            // looping through all rows and adding to list
            if (cursor.moveToFirst()) {
                do {
                    HospitalModel hm = new HospitalModel();
                    hm.setid(cursor.getInt(cursor.getColumnIndex(KEY_HOSPITALID)));
                    hm.setlistingid(cursor.getInt(cursor.getColumnIndex(KEY_HOSPITALTYPEID)));
                    hm.sethospital(cursor.getString(cursor.getColumnIndex(KEY_HOSPITAL)));
                    hm.setstreet(cursor.getString(cursor.getColumnIndex(KEY_HOSPITALSTREET)));
                    hm.setlatitude(cursor.getString(cursor.getColumnIndex(KEY_HOSPITALLATITUDE)));
                    hm.setlongitude(cursor.getString(cursor.getColumnIndex(KEY_HOSPITALLONGITUDE)));
                    hList.add(hm);
                } while (cursor.moveToNext());
            }
            cursor.close();

        return hList;
    }

    public DoctorModel getDoctorHospital() {

        DoctorModel doctormodel = new DoctorModel();
        String selectQuery = "SELECT doctors.full_name FROM doctors_details LEFT JOIN doctors " +
                "ON doctors_details.doctor_id = doctors.id WHERE doctors_details.detail_type = 1 AND doctors_details.detail_id = "+KEY_HOSPITALID;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {

                doctormodel.setname(cursor.getString(cursor.getColumnIndex("full_name")));
        }
        cursor.close();
        return doctormodel;
    }
}

MainActivity

public class MainActivity extends AppCompatActivity {



    Button btnback, btnnext, btnbackprofile, btnwaze,btnprofileHospitalDoctorListButton;
    TextView profilehospital,profileaddress;




    List<HospitalModel> GetAllHospital;
    Context context = this;
    DatabaseHelper dbhelper;
    DatabaseHelper db = new DatabaseHelper(this);
    ListView lv;
    View HospitalListView,HospitalProfileView,HospitalDoctor;

    int index = 0;
    private int currentPageIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbhelper = new DatabaseHelper(MainActivity.this);

        try{
            dbhelper.createDataBase();
        }
        catch(IOException e){
            e.printStackTrace();
        }
        try {
            dbhelper.openDataBase();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //Till here
        GetAllHospital = dbhelper.getAllHospital(index);
        lv = (ListView) findViewById(R.id.hospital_list);
        lv.setAdapter(new ViewAdapter());


        /****************************************************************************************
         *                                  HOSPITAL PROFILE
         ****************************************************************************************/
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view,final int i, long l) {

                HospitalListView = findViewById(R.id.hospitallayout);
                ViewGroup parent = (ViewGroup) HospitalListView.getParent();
                parent.removeView(HospitalListView);
                // inflate your profile view (or get the reference to it if it's already inflated)
                HospitalProfileView = getLayoutInflater().inflate(R.layout.profile_hospital, parent, false);
                // add it to the parent
                parent.addView(HospitalProfileView);




                btnbackprofile = (Button) findViewById(R.id.profileHospitalBack);

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

                        if (HospitalProfileView != null && HospitalProfileView.getParent() != null) {
                            // remove your profile view
                            ViewGroup parent = (ViewGroup) HospitalProfileView.getParent();
                            parent.removeView(HospitalProfileView);

                            // a reference to yourListView has to be saved somewhere; just get it

                            // add your listview to the parent
                            parent.addView(HospitalListView);
                        } else {
                        }


                    }
                });

                profilehospital = (TextView) findViewById(R.id.profileHospitalName);
                profileaddress = (TextView) findViewById(R.id.profileHospitalAddress);
                profilehospital.setText(GetAllHospital.get(i).gethospital());
                profileaddress.setText(GetAllHospital.get(i).getstreet());


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

                        HospitalProfileView = findViewById(R.id.profilehospital);
                        ViewGroup parent = (ViewGroup) HospitalProfileView.getParent();
                        parent.removeView(HospitalProfileView);
                        // inflate your profile view (or get the reference to it if it's already inflated)
                        HospitalDoctor = getLayoutInflater().inflate(R.layout.hospitaldoctor, parent, false);
                        // add it to the parent
                        parent.addView(HospitalDoctor);

                    }
                });




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

                        try
                        {
                            String url = "waze://?ll="+GetAllHospital.get(i).getlatitude()+","+ GetAllHospital.get(i).getlongitude()+"&navigate=yes";
                            Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse( url ) );
                            startActivity( intent );
                        }
                        catch ( ActivityNotFoundException ex  )
                        {
                            Intent intent =
                                    new Intent( Intent.ACTION_VIEW, Uri.parse( "market://details?id=com.waze" ) );
                            startActivity(intent);
                        }
                    }
                });


            }
        });

        btnback = (Button) findViewById(R.id.hospitalBack);
        btnnext = (Button) findViewById(R.id.hospitalNext);

        btnback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View convertView) {

                currentPageIndex -= 20;
                GetAllHospital = dbhelper.getAllHospital(currentPageIndex);
                lv = (ListView) findViewById(R.id.hospital_list);
                lv.setAdapter(new ViewAdapter());

            }

        });

        btnnext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View convertView) {

                currentPageIndex += 20;
                GetAllHospital = dbhelper.getAllHospital(currentPageIndex);
                lv = (ListView) findViewById(R.id.hospital_list);
                lv.setAdapter(new ViewAdapter());

            }
        });

        /****************************************************************************************
         *                                      SEARCH BOX
         ****************************************************************************************/
        ImageButton search = (ImageButton) findViewById(R.id.search);
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final Dialog dialog = new Dialog(context);
                dialog.setContentView(R.layout.search_hospital);
                dialog.setTitle("Search Hospital");

                Spinner spinner = (Spinner) dialog.findViewById(R.id.spinnerdoctorspecialty);
                Button button = (Button) dialog.findViewById(R.id.btndoctorsearch);

                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });

                dialog.show();
            }
        });


    }

    /****************************************************************************************
     *                                      CUSTOM LIST
     ****************************************************************************************/
    public class ViewAdapter extends BaseAdapter {

        LayoutInflater mInflater;

        public ViewAdapter() {
            mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return GetAllHospital.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_hospital,null);
            }

            final TextView names = (TextView) convertView.findViewById(R.id.hospitallist_name);
            final TextView street = (TextView) convertView.findViewById(R.id.hospitallist_street);

            names.setText(GetAllHospital.get(position).gethospital());
            street.setText(GetAllHospital.get(position).getstreet());

            return convertView;
        }
    }

    @Override
    public void onBackPressed() {
        if(HospitalProfileView != null && HospitalProfileView.getParent() != null) {
            // remove your profile view
            ViewGroup parent = (ViewGroup) HospitalProfileView.getParent();
            parent.removeView(HospitalProfileView);

            // a reference to yourListView has to be saved somewhere; just get it

            // add your listview to the parent
            parent.addView(HospitalListView);
        }
        else if(HospitalDoctor != null && HospitalDoctor.getParent() != null ){

            ViewGroup parent = (ViewGroup) HospitalDoctor.getParent();
            parent.removeView(HospitalDoctor);

            parent.addView(HospitalProfileView);
        }

        else {
            new AlertDialog.Builder(this)
                    .setMessage("Are you sure you want to exit?")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            MainActivity.this.finish();
                        }
                    })
                    .setNegativeButton("No", null)
                    .show();
        }
    }

}

Aucun commentaire:

Enregistrer un commentaire