在andriod studio

时间:2017-08-31 16:26:21

标签: java android listview

我正在尝试从数据库中检索数据并将其显示在listView上。数据将首先发送到数据库并检索和显示。我没有收到任何错误,但我只是在尝试运行模拟器时应用停止。我真的不知道问题出在哪里

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




 }

1 个答案:

答案 0 :(得分:1)

ListActivity拥有自己的布局(由ListView组成),因此如果您想通过调用setContentView()来自定义布局,则必须使用id作为"@android:id/list" } ListView

Docs link

  

ListActivity has a default layout由单个组成,   屏幕中央的全屏列表。但是,如果你愿意,   you can customize the screen layout setting您自己的视图布局   在onCreate()中使用setContentView()。为此,您自己的观点MUST   contain a ListView object with the id "@android:id/list"

所以替换这个

 android:id="@+id/list"

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

并使用view.getId() == R.id.btnAdd代替view== findViewById(R.id.btnAdd)这是一项昂贵的函数调用

您也可以extends AppCompatActivityActivity使用setOnItemClickListener

setOnItemClickListener on custom ListView