-1

I am trying to retrieve data from the data base and displaying it on the listView. The data will first be sent to the database and the retrieved and displayed. I am not getting any error but I but the app stops as soon as I try to run the emulator. I really do not know where the problem is

activity.main <

RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="368dp"
        android:layout_height="495dp"
        tools:context="com.instinctcoder.sqlitedb.MainActivity$PlaceholderFragment"
        tools:layout_editor_absoluteY="8dp"
        tools:layout_editor_absoluteX="8dp">

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Add"
                android:id="@+id/btnAdd"
                android:layout_alignParentBottom="true"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true" />

            <ListView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/list"
                android:layout_centerHorizontal="true"
                android:layout_alignParentTop="true"
                android:layout_above="@+id/btnAdd" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="List All"
                android:id="@+id/btnGetAll"
                android:layout_alignParentBottom="true"
                android:layout_toRightOf="@+id/btnAdd" />

        </RelativeLayout>

activity_treatment_details

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="Treatment Name"
                android:id="@+id/treatmentName"
                android:layout_alignParentTop="true"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_marginTop="30dp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="Treatment Type"
                android:id="@+id/treatmentType"
                android:layout_below="@+id/treatmentName"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_marginTop="29dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Treatment Number"
            android:id="@+id/treatmentNumber"
            android:layout_below="@+id/treatmentType"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="29dp" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/editTextTreatmentName"
            android:layout_above="@+id/treatmentType"
            android:layout_toRightOf="@+id/treatmentName"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textEmailAddress"
            android:ems="10"
            android:id="@+id/editTextTreatmentType"
            android:layout_above="@+id/treatmentNumber"
            android:layout_toRightOf="@+id/treatmentName"
            android:layout_alignRight="@+id/editTextTreatmentName"
            android:layout_alignEnd="@+id/editTextTreatmentName" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:ems="10"
            android:id="@+id/editTextTreatmentNumber"
            android:layout_alignBottom="@+id/treatmentNumber"
            android:layout_alignLeft="@+id/editTextTreatmentType"
            android:layout_alignStart="@+id/editTextTreatmentType"
            android:layout_alignRight="@+id/editTextTreatmentType"
            android:layout_alignEnd="@+id/editTextTreatmentType" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Save"
            android:id="@+id/btnSave"
            android:layout_alignParentBottom="true"
            android:layout_toLeftOf="@+id/btnClose" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Close"
            android:id="@+id/btnClose"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Delete"
            android:id="@+id/btnDelete"
            android:layout_alignTop="@+id/btnSave"
            android:layout_toLeftOf="@+id/btnSave" />

    </RelativeLayout>

view_treatment_entry

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/treatment_Id"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:visibility="gone" />

        <TextView
            android:id="@+id/treatment_name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="6dip"
            android:paddingTop="6dip"
            android:textSize="22sp"
            android:textStyle="bold" />

    </LinearLayout>

Treatment.java

     public class Treatment {


    // Labels table name
    public static final String TABLE = "Treatment";

    // Labels Table Columns names
    public static final String KEY_TreatmentID = "TreatmentId";
    public static final String KEY_TreatmentName = "TreatmentName";
    public static final String KEY_TreatmentType = "TreatmentType";
    public static final String KEY_TreatmentNumber = "TreatmentNumber";

    // property help us to keep data
    public int treatment_ID;
    public String treatmentName;
    public String treatmentType;
    public int treatmentNumber;
}

DBHelper.java

    `enter code here`public class DBHelper extends SQLiteOpenHelper {


        //version number to upgrade database version
        //each time if you Add, Edit table, you need to change the
        //version number.
        private static final int DATABASE_VERSION = 4;

        // Database Name
        private static final String DATABASE_NAME = "AbovePostnatalDepression.db";

        public DBHelper(Context context ) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            //All necessary tables you like to create will create here

            String CREATE_TABLE_TREATMENT = "CREATE TABLE " + Treatment.TABLE  + "("
                    + Treatment.KEY_TreatmentID  + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
                    + Treatment.KEY_TreatmentName + " TEXT, "
                    + Treatment.KEY_TreatmentNumber + " INTEGER, "
                    + Treatment.KEY_TreatmentType + " TEXT )";

            db.execSQL(CREATE_TABLE_TREATMENT);

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // Drop older table if existed, all data will be gone!!!
            db.execSQL("DROP TABLE IF EXISTS " + Treatment.TABLE);

            // Create tables again
            onCreate(db);

        }


}

TreatmentRepo

     public class TreatmentRepo {

        private DBHelper dbHelper;

        public TreatmentRepo(Context context) {
            dbHelper = new DBHelper(context);
        }

        public int insert(Treatment treatment) {

            //Open connection to write data
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(Treatment.KEY_TreatmentNumber, 
   treatment.treatmentNumber);
            values.put(Treatment.KEY_TreatmentType,treatment.treatmentType);
            values.put(Treatment.KEY_TreatmentName, treatment.treatmentName);

            // Inserting Row
            long treatment_ID = db.insert(Treatment.TABLE, null, values);
            db.close(); // Closing database connection
            return (int) treatment_ID;
        }

        public void delete(int treatment_ID) {

            SQLiteDatabase db = dbHelper.getWritableDatabase();
            // It's a good practice to use parameter ?, instead of concatenate string
            db.delete(Treatment.TABLE, Treatment.KEY_TreatmentID + "= ?", new String[] { String.valueOf(treatment_ID) });
            db.close(); // Closing database connection
        }

        public void update(Treatment treatment) {

            SQLiteDatabase db = dbHelper.getWritableDatabase();
            ContentValues values = new ContentValues();

            values.put(Treatment.KEY_TreatmentNumber, treatment.treatmentNumber);
            values.put(Treatment.KEY_TreatmentType,treatment.treatmentType);
            values.put(Treatment.KEY_TreatmentName, treatment.treatmentName);

            db.update(Treatment.TABLE, values, Treatment.KEY_TreatmentID + "= ?", new String[] { String.valueOf(treatment.treatment_ID) });
            db.close(); // Closing database connection
        }

        public ArrayList<HashMap<String, String>>  getTreatmentList() {
            //Open connection to read only
            SQLiteDatabase db = dbHelper.getReadableDatabase();
            String selectQuery =  "SELECT  " +
                    Treatment.KEY_TreatmentID + "," +
                    Treatment.KEY_TreatmentName + "," +
                    Treatment.KEY_TreatmentType + "," +
                    Treatment.KEY_TreatmentNumber +
                    " FROM " + Treatment.TABLE;


            ArrayList<HashMap<String, String>> treatmentList = new ArrayList<HashMap<String, String>>();

            Cursor cursor = db.rawQuery(selectQuery, null);
            // looping through all rows and adding to list

            if (cursor.moveToFirst()) {
                do {
                    HashMap<String, String> treatment = new HashMap<String, 
    String>();
                    treatment.put("TreatmentId", 
    cursor.getString(cursor.getColumnIndex(Treatment.KEY_TreatmentID)));
                    treatment.put("TreatmentName", 
    cursor.getString(cursor.getColumnIndex(Treatment.KEY_TreatmentName)));
                    treatmentList.add(treatment);

                } while (cursor.moveToNext());
            }

            cursor.close();
            db.close();
            return treatmentList;

        }

        public Treatment getTreatmentById(int Id){
            SQLiteDatabase db = dbHelper.getReadableDatabase();
            String selectQuery =  "SELECT  " +
                    Treatment.KEY_TreatmentID + "," +
                    Treatment.KEY_TreatmentName + "," +
                    Treatment.KEY_TreatmentType + "," +
                    Treatment.KEY_TreatmentNumber +
                    " FROM " + Treatment.TABLE
                    + " WHERE " +
                    Treatment.KEY_TreatmentID + "=?";// It's a good practice to 
    use parameter ?, instead of concatenate string

            int iCount =0;
            Treatment treatment = new Treatment();

            Cursor cursor = db.rawQuery(selectQuery, new String[] { 
    String.valueOf(Id) } );

            if (cursor.moveToFirst()) {
                do {
                    treatment.treatment_ID 
    =cursor.getInt(cursor.getColumnIndex(Treatment.KEY_TreatmentID));
                    treatment.treatmentName 
    =cursor.getString(cursor.getColumnIndex(Treatment.KEY_TreatmentName));
                    treatment.treatmentType  
    =cursor.getString(cursor.getColumnIndex(Treatment.KEY_TreatmentType));
                    treatment.treatmentNumber 
    =cursor.getInt(cursor.getColumnIndex(Treatment.KEY_TreatmentNumber));

                } while (cursor.moveToNext());
            }

            cursor.close();
            db.close();
            return treatment;
        }

TreatmentDetail

    public class TreatmentDetail extends AppCompatActivity implements 
    android.view.View.OnClickListener {


        Button btnSave ,  btnDelete;
        Button btnClose;
        EditText editTextTreatmentName;
        EditText editTextTreatmentType;
        EditText editTextTreatmentNumber;
        private int _Treatment_Id=0;

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

            btnSave = (Button) findViewById(R.id.btnSave);
            btnDelete = (Button) findViewById(R.id.btnDelete);
            btnClose = (Button) findViewById(R.id.btnClose);

            editTextTreatmentName = (EditText) 
     findViewById(R.id.editTextTreatmentName);
            editTextTreatmentType = (EditText) 
    findViewById(R.id.editTextTreatmentType);
            editTextTreatmentNumber = (EditText) 
    findViewById(R.id.editTextTreatmentNumber);

            btnSave.setOnClickListener(this);
            btnDelete.setOnClickListener(this);
            btnClose.setOnClickListener(this);


            _Treatment_Id =0;
            Intent intent = getIntent();
            _Treatment_Id =intent.getIntExtra("treatment_Id", 0);
            TreatmentRepo repo = new TreatmentRepo(this);
            Treatment treatment = new Treatment();
            treatment = repo.getTreatmentById(_Treatment_Id);


     editTextTreatmentNumber.setText(String.valueOf(treatment.treatmentNumber));
            editTextTreatmentName.setText(treatment.treatmentName);
            editTextTreatmentType.setText(treatment.treatmentType);
        }



        public void onClick(View view) {
            if (view == findViewById(R.id.btnSave)){
                TreatmentRepo repo = new TreatmentRepo(this);
                Treatment treatment = new Treatment();
                treatment.treatmentNumber= 
    Integer.parseInt(editTextTreatmentNumber.getText().toString());

    treatment.treatmentType=editTextTreatmentType.getText().toString();

    treatment.treatmentName=editTextTreatmentName.getText().toString();
                treatment.treatment_ID=_Treatment_Id;

                if (_Treatment_Id==0){
                    _Treatment_Id = repo.insert(treatment);

                    Toast.makeText(this,"New Student 
    Insert",Toast.LENGTH_SHORT).show();
                }else{

                    repo.update(treatment);
                    Toast.makeText(this,"Student Record 
   updated",Toast.LENGTH_SHORT).show();
                }
            }else if (view== findViewById(R.id.btnDelete)){
                TreatmentRepo repo = new TreatmentRepo(this);
                repo.delete(_Treatment_Id);
                Toast.makeText(this, "Student Record Deleted", 
    Toast.LENGTH_SHORT);
                finish();
            }else if (view== findViewById(R.id.btnClose)){
                finish();
            }


        }


     }

Mainactivity

 public class MainActivity extends ListActivity  implements 
 android.view.View.OnClickListener {


    Button btnAdd,btnGetAll;
    TextView treatment_Id;

    @Override
    public void onClick(View view) {
        if (view== findViewById(R.id.btnAdd)){

            Intent intent = new Intent(this,TreatmentDetail.class);
            intent.putExtra("treatment_Id",0);
            startActivity(intent);

        }else {

            TreatmentRepo repo = new TreatmentRepo(this);

            ArrayList<HashMap<String, String>> treatmentList =  
   repo.getTreatmentList();
            if(treatmentList.size()!=0) {
                ListView lv = getListView();
                lv.setOnItemClickListener(new 
AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View v 
view,int position, long id) {
                        treatment_Id = (TextView) 
view.findViewById(R.id.treatment_Id);
                        String treatmentId = 
treatment_Id.getText().toString();
                        Intent objIndent = new 
Intent(getApplicationContext(),TreatmentDetail.class);
                        objIndent.putExtra("treatment_Id", Integer.parseInt( 
treatmentId));
                        startActivity(objIndent);
                    }
                });
                ListAdapter adapter = new SimpleAdapter( 
 MainActivity.this,treatmentList, R.layout.activity_view_treatment_entry, new 
 String[] { "TreatmentId","TreatmentName"}, new int[] {R.id.treatment_Id, 
 R.id.treatment_name});
                setListAdapter(adapter);
            }else{
                Toast.makeText(this,"No student!",Toast.LENGTH_SHORT).show();
            }

        }
    }



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

    btnAdd = (Button) findViewById(R.id.btnAdd);
    btnAdd.setOnClickListener(this);

    btnGetAll = (Button) findViewById(R.id.btnGetAll);
    btnGetAll.setOnClickListener(this);
 }




 }
Cœur
  • 37,241
  • 25
  • 195
  • 267
Omade
  • 47
  • 2
  • 13

1 Answers1

1

ListActivity has it's own layout(consist ListView) so if you want to customize the layout by calling setContentView() then you have to use id as "@android:id/list" for ListView

Docs link

ListActivity has a default layout that consists of a single, full-screen list in the center of the screen. However, if you desire, you can customize the screen layout by setting your own view layout with setContentView() in onCreate(). To do this, your own view MUST contain a ListView object with the id "@android:id/list"

so replace this

 android:id="@+id/list"

with

 android:id="@android:id/list"

and use view.getId() == R.id.btnAdd instead of view== findViewById(R.id.btnAdd) it is an expensive function call

or

Alternatively you can extends AppCompatActivity or Activity and use setOnItemClickListener

setOnItemClickListener on custom ListView

Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
  • and also read https://stackoverflow.com/questions/14713539/android-listactivity-row-click `to implement click` in `ListActivity` – Pavneet_Singh Aug 31 '17 at 16:56
  • Thanks for your comment. I tried the suggestion but when I click on the btnAdd it closes the app – Omade Aug 31 '17 at 20:06
  • now you have other issue , if you are still using listActivity then override `onListItemClick()` to don't use your own listener and also alway post the error details from logcat so get help from anyone on stackoverflow – Pavneet_Singh Sep 01 '17 at 10:13