在Intent上传递数据时出错

时间:2017-12-09 11:00:04

标签: android sqlite android-intent

我正在尝试在观看youtube教程后使用intent将ID从一个类传递到另一个类。但是,它总是超过默认值-1而不是我想要的值。

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            String homeTeam = adapterView.getItemAtPosition(i).toString();
            Log.d(TAG, "onItemClick: You Clicked on " + homeTeam);

            Cursor data = myDB.getMatch(homeTeam); //get the id associated with that name
            int itemID = -1;
            while(data.moveToNext()){
                itemID = data.getInt(0);
            }
            if(itemID > -1){
                //Log.d(TAG, "onItemClick: The ID is: " + itemID);
                Intent editScreenIntent = new Intent(ViewMatchesActivity.this, UpdateMatchActivity.class);
                editScreenIntent.putExtra("MatchId", itemID);
                editScreenIntent.putExtra("homeTeam",homeTeam);
                startActivity(editScreenIntent);
            }
            else{
                toastMessage("No ID associated with that name");
            }
        }
    });
}

它上课:

 //get the intent extra from the ListDataActivity
    Intent receivedIntent = getIntent();

    //now get the itemID we passed as an extra
    selectedID = receivedIntent.getIntExtra("matchId", -1); //NOTE: -1 is just the default value

    //now get the name we passed as an extra
    selectedName = receivedIntent.getStringExtra("homeTeam");

    //set the text to show the current selected name
    editable_item.setText(selectedName);

在他的教程中,它运行正常,但是当我在编辑匹配后尝试它时,在我的日志中它会出现MatchId = -1,当它不应该是。

我还将该方法包含在数据库中:

public void updateName(String newName, int id, String oldName){
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "UPDATE " + MATCH_TABLE + " SET " + MATCH_HOME_TEAM_COL +
            " = '" + newName + "' WHERE " + MATCH_ID_COL + " = '" + id + "'" +
            " AND " + MATCH_HOME_TEAM_COL + " = '" + oldName + "'";
    Log.d(TAG, "updateName: query: " + query);
    Log.d(TAG, "updateName: Setting name to " + newName);
    db.execSQL(query);
}

2 个答案:

答案 0 :(得分:0)

您传递的密钥是 MatchId ,并且您从 matchId 获取数据,这些数据不相同。

将代码替换为

 selectedID = receivedIntent.getIntExtra("MatchId", -1); //NOTE: -1 is just the default value

答案 1 :(得分:0)

在接收活动中更改代码

 //get the intent extra from the ListDataActivity
    Intent receivedIntent = getIntent();

    //now get the itemID we passed as an extra
    selectedID = receivedIntent.getIntExtra("MatchId", -1); //NOTE: -1 is just the default value

    //now get the name we passed as an extra
    selectedName = receivedIntent.getStringExtra("homeTeam");

    //set the text to show the current selected name
    editable_item.setText(selectedName);

您应该使用MatchId matchID的{​​{1}}。 Java是区分大小写的。