setOnClickListener(this)导致错误?

时间:2016-10-30 13:38:20

标签: android onclicklistener

清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.user.foody">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".RestaurantDetail"></activity>
</application>
</manifest>

主要活动

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,
                                                           android.view.View.OnClickListener {
private boolean viewIsAtHome; // 每次 press back 都回到 about(初始頁面)
Button buttonEditAddYes,buttonEditUorD;
TextView restaurantID;

// ----------- 每當按下Button按下,則跑到OnClick()執行對應Function -----------

@override
public void onClick(View view) {
    if (view== findViewById(R.id.buttonEditAddYes)){ // 確定新增 (Edit_Add內)

        Intent intent = new Intent(MainActivity.this,RestaurantDetail.class);
        intent.putExtra("restaurantID",0);
        startActivity(intent);
    }

    else if (view== findViewById(R.id.buttonEditAddNo) ){ // 清除 (Edit_Add內)
    }

    else if (view== findViewById(R.id.buttonEditUorD)) { // 當按下 (Edit內)

        RestaurantRepo repo = new RestaurantRepo(this);

        ArrayList<HashMap<String, String>> restaurantList =  repo.getRestaurantList();
        if(restaurantList.size()!=0) {
            ListView lv = (ListView) findViewById(R.id.list);
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
                    restaurantID = (TextView) view.findViewById(R.id.restaurantID);
                    String idRestaurant = restaurantID.getText().toString();
                    Intent objIndent = new Intent(getApplicationContext(),RestaurantDetail.class);
                    objIndent.putExtra("restaurantID", Integer.parseInt(idRestaurant));
                    startActivity(objIndent);
                }
            });
            ListAdapter adapter = new SimpleAdapter( MainActivity.this,restaurantList, R.layout.edit_fragment_fix_view,
                    new String[] { "id","name","type","price","phone","addr"},
                    new int[] {R.id.restaurantID, R.id.restaurantNAME,R.id.restaurantTYPE,
                            R.id.restaurantPRICE,R.id.restaurantPHONE,R.id.restaurantADDR});
            lv.setAdapter(adapter);
        }else{
            Toast.makeText(this,"No restaurant!",Toast.LENGTH_SHORT).show();
        }
    }
}
// ------------------------------------------------------------------------

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setItemIconTintList(null); // 顯示Icon圖案,不會讓他黑黑的
    navigationView.setNavigationItemSelectedListener(this);
    displayView(R.id.menu_about); // 一開始看About

    // -------------------- 新增 / 修改 / 刪除  --------------------

    buttonEditAddYes = (Button)findViewById(R.id.buttonEditAddYes);  
    buttonEditAddYes.setOnClickListener(this);// !!!!!!!!!!!!!!!!!!!!!! Here got error

    buttonEditUorD = (Button)findViewById(R.id.buttonEditUorD);     
    buttonEditUorD.setOnClickListener(this); // !!!!!!!!!!!!!!!!!!!!!! because of ↑ , so this may cause error too

    // ------------------------------------------------------------
}

RestaurantDetail

public class RestaurantDetail extends Activity implements android.view.View.OnClickListener {

    Button buttonEditUpdate ,  buttonEditDelete;

    EditText editTextNAME;
    EditText editTextTYPE;
    EditText editTextPRICE;
    EditText editTextPHONE;
    EditText editTextADDR;
    //EditText editTextSCORE;

    private int _RestaurantID = 0;

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.edit_fragment_fix_uord);
            // buttonEditUorD按下時 跳到 edit_fragment_fix_uord去修改

            buttonEditUpdate = (Button) findViewById(R.id.buttonEditUpdate);
            buttonEditDelete = (Button) findViewById(R.id.buttonEditUpdate);

            editTextNAME = (EditText) findViewById(R.id.editTextUpdateName);
            editTextTYPE = (EditText) findViewById(R.id.editTextUpdateType);
            editTextPRICE = (EditText) findViewById(R.id.editTextUpdatePrice);
            editTextPHONE = (EditText) findViewById(R.id.editTextUpdatePhone);
            editTextADDR = (EditText) findViewById(R.id.editTextUpdateAddr);
            //editTextSCORE = (EditText) findViewById(R.id.ratingBarUpdate);

            buttonEditUpdate.setOnClickListener(this);
            buttonEditDelete.setOnClickListener(this);

            _RestaurantID =0;
            Intent intent = getIntent();
            _RestaurantID =intent.getIntExtra("restaurantID", 0);
            RestaurantRepo repo = new RestaurantRepo(this);
            Restaurant restaurant = new Restaurant();
            restaurant = repo.getRestaurantById(_RestaurantID);

            editTextNAME.setText(restaurant.name);
            editTextTYPE.setText(String.valueOf(restaurant.type));
            editTextPRICE.setText(String.valueOf(restaurant.price));
            editTextPHONE.setText(restaurant.phone);
            editTextADDR.setText(restaurant.addr);
            //editTextSCORE.setText(String.valueOf(restaurant.score));
        }

    @Override
        public void onClick(View view) {
            // TODO Auto-generated method stub
            if (view == findViewById(R.id.buttonEditUpdate)){
                RestaurantRepo repo = new RestaurantRepo(this);
                Restaurant restaurant = new Restaurant();

                restaurant.restautant_ID =_RestaurantID;
                restaurant.name = editTextNAME.getText().toString();
                restaurant.type =  Integer.parseInt(editTextTYPE.getText().toString()) ;
                restaurant.price = Integer.parseInt(editTextPRICE.getText().toString()) ;
                restaurant.phone = editTextPHONE.getText().toString();
                restaurant.addr = editTextADDR.getText().toString();
                //restaurant.score = Integer.parseInt(editTextSCORE.getText().toString());

                if (_RestaurantID==0){
                    _RestaurantID = repo.insert(restaurant);

                    Toast.makeText(this,"New Restaurant Insert",Toast.LENGTH_SHORT).show();
                    finish();
                }

                else{
                    repo.update(restaurant);
                    Toast.makeText(this,"Restaurant Record updated",Toast.LENGTH_SHORT).show();
                    finish();
                }
            }

            else if (view== findViewById(R.id.buttonEditDelete)){
                RestaurantRepo repo = new RestaurantRepo(this);
                repo.delete(_RestaurantID);
                Toast.makeText(this, "Restaurant Record Deleted", Toast.LENGTH_SHORT);
                finish();
            }
        }
}

我决定创建一个按钮,将信息插入我的SQLite数据库。

当我点击按钮(buttonEditAddYes)时,它会将参数传递给 另一项活动(RestaurantDetail)。

此行发生错误:

buttonEditAddYes.setOnClickListener(this);

我想也许我不想在我的MainActivity(?)

上扩展ListActivity

但我已经扩展了AppCompatActivity ..

Process: com.example.user.foody, PID: 4577
  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.foody/com.example.user.foody.RestaurantDetail}: java.lang.ClassCastException: android.widget.TableRow cannot be cast to android.widget.EditText
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
      at android.app.ActivityThread.access$900(ActivityThread.java:177)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
      at android.os.Handler.dispatchMessage(Handler.java:102)
      at android.os.Looper.loop(Looper.java:145)
      at android.app.ActivityThread.main(ActivityThread.java:5942)
      at java.lang.reflect.Method.invoke(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:372)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
   Caused by: java.lang.ClassCastException: android.widget.TableRow cannot be cast to android.widget.EditText
      at **com.example.user.foody.RestaurantDetail.onCreate(RestaurantDetail.java:39)
      at** android.app.Activity.performCreate(Activity.java:6288)
      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758) 
      at android.app.ActivityThread.access$900(ActivityThread.java:177) 
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448) 
      at android.os.Handler.dispatchMessage(Handler.java:102) 
      at android.os.Looper.loop(Looper.java:145) 
      at android.app.ActivityThread.main(ActivityThread.java:5942) 
      at java.lang.reflect.Method.invoke(Native Method) 
      at java.lang.reflect.Method.invoke(Method.java:372)

3 个答案:

答案 0 :(得分:0)

日志说:

Caused by: java.lang.ClassCastException: android.widget.TableRow cannot be cast to android.widget.EditText

你确定所有这些findViewById都引用了TextView吗?也许是android中的拼写错误:id?

另外,我认为你应该在你的onClick方法中使用case而不是ifs:

switch(view.getId) {
    case R.id.your_id:
    doSomething();
    break;
}

这为代码提供了更多的可读性;)

答案 1 :(得分:0)

@Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        if (view.getId() == R.id.buttonEditUpdate){
            RestaurantRepo repo = new RestaurantRepo(this);
            Restaurant restaurant = new Restaurant();

            restaurant.restautant_ID =_RestaurantID;
            restaurant.name = editTextNAME.getText().toString();
            restaurant.type =  Integer.parseInt(editTextTYPE.getText().toString()) ;
            restaurant.price = Integer.parseInt(editTextPRICE.getText().toString()) ;
            restaurant.phone = editTextPHONE.getText().toString();
            restaurant.addr = editTextADDR.getText().toString();
            //restaurant.score = Integer.parseInt(editTextSCORE.getText().toString());

            if (_RestaurantID==0){
                _RestaurantID = repo.insert(restaurant);

                Toast.makeText(this,"New Restaurant Insert",Toast.LENGTH_SHORT).show();
                finish();
            }

            else{
                repo.update(restaurant);
                Toast.makeText(this,"Restaurant Record updated",Toast.LENGTH_SHORT).show();
                finish();
            }
        }

        else if (view.getId()== R.id.buttonEditDelete){
            RestaurantRepo repo = new RestaurantRepo(this);
            repo.delete(_RestaurantID);
            Toast.makeText(this, "Restaurant Record Deleted", Toast.LENGTH_SHORT);
            finish();
        }
    }

将Onclick方法更改为abouve

答案 2 :(得分:0)

基本上,请查看堆栈跟踪

  

引起:java.lang.ClassCastException:android.widget.TableRow无法强制转换为android.widget.EditText

这意味着您正在构建错误类型的Object。 检查RestaurantDetail上的第39行。你的CastTow转换为EditText!

此致