代码之家  ›  专栏  ›  技术社区  ›  Harshit Bahri

Java语言lang.ClassCastException:com。实例harshitbahri。expensebook。无法将MainActivity转换为com。实例harshitbahri。expensebook。编辑器活动

  •  -2
  • Harshit Bahri  · 技术社区  · 7 年前

    我想更改 TextView 通过单击 Button buttonExpense 它还应打开编辑器活动并在中显示结果的值 EditText mAmountEditText .

    我正在 java.lang.ClassCastException 其中明确规定MainActivity不能转换为EditorActivity

    计算器Java语言

    package com.example.harshitbahri.expensebook;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.net.Uri;
    import android.os.Bundle;
    import android.support.v4.app.FragmentActivity;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    
    public class Calculator extends android.support.v4.app.Fragment {
    Button button0;
    Button button1;
    Button button2;
    Button button3;
    Button button4;
    Button button5;
    Button button6;
    Button button7;
    Button button8;
    Button button9;
    Button buttonAdd;
    Button buttonSubstract;
    Button buttonMul;
    Button buttonDiv;
    Button buttonClear;
    Button buttonEqual;
    Button buttonExpense;
    String result;
    String tmp;
    String operator;
    TextView resultTextView;
    FragmentActivity fa2;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        fa2 = (FragmentActivity) super.getActivity();
        final View RootView= inflater.inflate(R.layout.activity_calculator, container, false);
        button0 = (Button)RootView.findViewById(R.id.button0);
        button1 = (Button)RootView.findViewById(R.id.button1);
        ......
        buttonAdd = (Button)RootView.findViewById(R.id.buttonAdd);
        buttonClear = (Button)RootView.findViewById(R.id.buttonClear);
        buttonSubstract = (Button)RootView.findViewById(R.id.buttonSub);
        buttonMul = (Button)RootView.findViewById(R.id.buttonMul);
        buttonDiv = (Button)RootView.findViewById(R.id.buttonDiv);
        buttonEqual = (Button)RootView.findViewById(R.id.buttonEqual);
        buttonExpense= (Button)RootView.findViewById(R.id.buttonExp);
    
        resultTextView = (TextView)RootView.findViewById(R.id.text_view_result);
    
    
        button0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onNumberButtonClicked("0");
            }
        });
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onNumberButtonClicked("1");
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onNumberButtonClicked("2");
            }
        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onNumberButtonClicked("3");
            }
        });
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onNumberButtonClicked("4");
            }
        });
        button5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onNumberButtonClicked("5");
            }
        });
        button6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onNumberButtonClicked("6");
            }
        });
        button7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onNumberButtonClicked("7");
            }
        });
        button8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onNumberButtonClicked("8");
            }
        });
        button9.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onNumberButtonClicked("9");
            }
        });
    
        buttonClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClearButtonClicked();
            }
        });
        buttonSubstract.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v){
                onOperatorButtonClicked("-");
            }
        });
        buttonAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onOperatorButtonClicked("+");
            }
        });
        buttonMul.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onOperatorButtonClicked("X");
            }
        });
        buttonDiv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onOperatorButtonClicked("/");
            }
        });
        buttonEqual.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onEqualButtonClicked();
    
            }
        });
        buttonExpense.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(fa2, EditorActivity.class);
                startActivity(intent);
                ((EditorActivity) getActivity()).updateGoldTextView(result);
                /*Intent intent = new Intent(fa2, EditorActivity.class);
                intent.putExtra(, result);
                final int result2=1;
                startActivityForResult(intent, result2);*/
            }
    
    
        });
    
        return RootView;
    
    }
    
    
    
    
    private void onEqualButtonClicked() {
        int res = 0;
        try {
            int number = Integer.valueOf(tmp);
            int number2 = Integer.valueOf(resultTextView.getText().toString());
            switch (operator) {
                case "+":
                    res = number + number2;
                    break;
                case "/":
                    res = number / number2;
                    break;
                case "-":
                    res = number - number2;
                    break;
                case "X":
                    res = number * number2;
                    break;
            }
            result = String.valueOf(res);
            resultTextView.setText(result);
    
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void onOperatorButtonClicked(String operator) {
        ..
    }
    
    public void onClearButtonClicked() {
        ...
    }
    
    public void onNumberButtonClicked(String pos) {
        ..
    }
    
    
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
    
    
    
    }`
    

    编辑器活动。Java语言

    package com.example.harshitbahri.expensebook;
    
    import android.app.AlertDialog;
    import android.app.LoaderManager;
    ...
    import android.widget.EditText;
    import android.widget.Spinner;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class EditorActivity extends AppCompatActivity implements
        LoaderManager.LoaderCallbacks<Cursor> {
    
    
    private static final int EXISTING_EXPENSE_LOADER = 0;
    
    
    private Uri mCurrentExpenseUri;
    
    private EditText mAmountEditText;
    
    private EditText mDescEditText;
    
    private Spinner mCategorySpinner;
    
    
    
    private String mCategory = ExpenseEntry.CATEGORY_GENERAL;
    
    
    private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            mExpenseHasChanged = true;
            return false;
        }
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editor);
        // Examine the intent that was used to launch this activity,
        // in order to figure out if we're creating a new pet or editing an existing one.
        Intent intent = getIntent();
        mCurrentExpenseUri = intent.getData();
    
        // If the intent DOES NOT contain a pet content URI, then we know that we are
        // creating a new pet.
        if (mCurrentExpenseUri == null) {
            // This is a new pet, so change the app bar to say "Add a Pet"
            setTitle("Add Expense");
    
           yet.)
            invalidateOptionsMenu();
        } else {
            // Otherwise this is an existing pet, so change app bar to say "Edit Pet"
            setTitle("Edit Expense");
    
    
            getLoaderManager().initLoader(EXISTING_EXPENSE_LOADER, null, this);
        }
        mAmountEditText = (EditText) findViewById(R.id.exp_amount);
        mDescEditText = (EditText) findViewById(R.id.description);
        mCategorySpinner = (Spinner) findViewById(R.id.spinner_category);
    .....
    
    }
       ......
    
    finish();
    
     }
    
    public void updateGoldTextView(String goldAmount) {
        mAmountEditText.setText(goldAmount);
    }
    
    
    }
    

    主要活动。Java语言

    package com.example.harshitbahri.expensebook;
    import android.net.Uri;
    import android.support.design.widget.TabLayout;
    import android.support.v4.app.FragmentPagerAdapter;
    import android.support.v4.view.ViewPager;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity implements  
    Calculator.OnFragmentInteractionListener , 
    Entries.OnFragmentInteractionListener,Info.OnFragmentInteractionListener{
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        TabLayout tabLayout = (TabLayout)findViewById(R.id.tablayout);
        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    
        final ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
        final Pageradapter adapter = new Pageradapter(getSupportFragmentManager(),tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        viewPager.setCurrentItem(1, false);
    
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }
    
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
    
            }
    
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
    
            }
        });
    
    }
    
    @Override
    public void onFragmentInteraction(Uri uri) {
    
    }
    
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   karandeep singh    7 年前

    您的片段是从MainActivity而不是EditorActivity加载的,因此类强制转换异常。如果要在编辑器活动中预填充一些数据,可以将其传递到intent(在onclick侦听器上注释的代码)中,然后在EditorActivity中检索并设置UI元素。 已编辑

    buttonExpense.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(fa2, EditorActivity.class);
            intent.putExtra("result", result);
            startActivity(intent);
        }});
    

    在EditorActivity类中,在创建时

    String result=getIntent().getStringExtra("result")
    updateGoldTextView(result)