简体   繁体   中英

Nothing happens when click button

I have two Activities, A and B. Data comes From activity B to A through OnActivityResult method, and I want to display them to ListView. But when I click the button from B Activity, nothing happens.

public class MainActivity extends ActionBarActivity implements View.OnClickListener {
    Button btnadd;
    LinearLayout llMain;
Time today = new Time(Time.getCurrentTimezone());
DBAdapter myDb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {



        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar = getSupportActionBar();
        actionBar.hide();
        btnadd = (Button) findViewById(R.id.button);
        //llMain = (LinearLayout) findViewById(R.id.llMain);
        btnadd.setOnClickListener(this);
        openDB();
        populateListView();
    }


        public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.button:
                Intent intent = new Intent(this, result.class);
                startActivityForResult(intent, 1);
                break;

            }
        }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {


        String name = data.getStringExtra("name");
        String grup = data.getStringExtra("grup");
today.setToNow();
    String timestamp  = today.format("%Y-%m-%d %H:%M:%S");
myDb.insertRow(name,timestamp,grup);
populateListView();





            }

private void openDB(){
    myDb = new DBAdapter(this);
myDb.open();
}
private void populateListView()    {
        Cursor cursor = myDb.getAllRows();
        String[] fromFieldNames = new String[]{DBAdapter.KEY_ROWID,DBAdapter.KEY_TASK};
        int[] toViewIDs = new int[]{R.id.textView3,R.id.textView6};
        SimpleCursorAdapter myCursorAdapter;
        myCursorAdapter = new SimpleCursorAdapter(getBaseContext(),R.layout.item_layout,cursor,fromFieldNames,toViewIDs,0);
        ListView myList = (ListView) findViewById(R.id.listView);

        myList.setAdapter(myCursorAdapter);
    }

    }

Activity B:

public class result extends ActionBarActivity implements View.OnClickListener {
    EditText etName;
    Button btnOk;
    EditText etData;
    boolean bIcon = true;
ImageButton star;
    String grup;
    Intent intent = new Intent();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        ActionBar actionBar = getSupportActionBar();
        actionBar.hide();
        etName = (EditText) findViewById(R.id.editText);
        btnOk = (Button) findViewById(R.id.button2);
star = (ImageButton) findViewById(R.id.imageButton);
        btnOk.setOnClickListener(this);
        star.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_result, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button2:

            intent.putExtra("task", etName.getText().toString());

            setResult(RESULT_OK, intent);
            finish();
                break;
            case R.id.imageButton:
                if (bIcon) {
                    star.setImageResource(R.drawable.star1);
                    grup = "top";

                }
                else

                    star.setImageResource(R.drawable.star);
                grup = null;
                intent.putExtra("grup",grup);
                bIcon = !bIcon;
                break;
        }
    }
}

DBAdapter class:

    public class DBAdapter {

    private static final String TAG = "DBAdapter"; //used for logging database version changes

    // Field Names:
    public static final String KEY_ROWID = "_id";
    public static final String KEY_TASK = "task";
    public static final String KEY_DATE = "date";
    public static final String KEY_GRUPS = "grup";

    public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_TASK, KEY_DATE,KEY_GRUPS};

    // Column Numbers for each Field Name:
    public static final int COL_ROWID = 0;
    public static final int COL_TASK = 1;
    public static final int COL_DATE = 2;
    public static final int COL_GRUPS = 3;

    // DataBase info:
    public static final String DATABASE_NAME = "dbToDo";
    public static final String DATABASE_TABLE = "mainToDo";
    public static final int DATABASE_VERSION = 2; // The version number must be incremented each time a change to DB structure occurs.

    //SQL statement to create database
    private static final String DATABASE_CREATE_SQL = 
            "CREATE TABLE " + DATABASE_TABLE 
            + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + KEY_TASK + " TEXT NOT NULL, " +KEY_GRUPS + " TEXT, "
            + KEY_DATE + " TEXT"
            + ");";

    private final Context context;
    private DatabaseHelper myDBHelper;
    private SQLiteDatabase db;


    public DBAdapter(Context ctx) {
        this.context = ctx;
        myDBHelper = new DatabaseHelper(context);
    }

    // Open the database connection.
    public DBAdapter open() {
        db = myDBHelper.getWritableDatabase();
        return this;
    }

    // Close the database connection.
    public void close() {
        myDBHelper.close();
    }

    // Add a new set of values to be inserted into the database.
    public long insertRow(String task, String date,String grup) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_TASK, task);
        initialValues.put(KEY_DATE, date);
        initialValues.put(KEY_GRUPS, grup);

        // Insert the data into the database.
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    // Delete a row from the database, by rowId (primary key)
    public boolean deleteRow(long rowId) {
        String where = KEY_ROWID + "=" + rowId;
        return db.delete(DATABASE_TABLE, where, null) != 0;
    }

    public void deleteAll() {
        Cursor c = getAllRows();
        long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
        if (c.moveToFirst()) {
            do {
                deleteRow(c.getLong((int) rowId));              
            } while (c.moveToNext());
        }
        c.close();
    }

    // Return all data in the database.
    public Cursor getAllRows() {
        String where = null;
        Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }

    // Get a specific row (by rowId)
    public Cursor getRow(long rowId) {
        String where = KEY_ROWID + "=" + rowId;
        Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, 
                        where, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }

    // Change an existing row to be equal to new data.
    public boolean updateRow(long rowId, String task, String date,String grup) {
        String where = KEY_ROWID + "=" + rowId;
        ContentValues newValues = new ContentValues();
        newValues.put(KEY_TASK, task);
        newValues.put(KEY_DATE, date);
        newValues.put(KEY_GRUPS, grup);
        // Insert it into the database.
        return db.update(DATABASE_TABLE, newValues, where, null) != 0;
    }


    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase _db) {
            _db.execSQL(DATABASE_CREATE_SQL);           
        }

        @Override
        public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading application's database from version " + oldVersion
                    + " to " + newVersion + ", which will destroy all old data!");

            // Destroy old database:
            _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

            // Recreate new database:
            onCreate(_db);
        }
    }


}

In protected void onActivityResult(int requestCode, int resultCode, Intent data) { String name = data.getStringExtra("name"); String grup = data.getStringExtra("grup"); today.setToNow(); String timestamp = today.format("%Y-%m-%d %H:%M:%S"); myDb.insertRow(name,timestamp,grup); populateListView(); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { String name = data.getStringExtra("name"); String grup = data.getStringExtra("grup"); today.setToNow(); String timestamp = today.format("%Y-%m-%d %H:%M:%S"); myDb.insertRow(name,timestamp,grup); populateListView(); }

You are reading intent data from "name or grup" but in your activity B those string extras never been set correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM