java - 在我的应用程序中获取 java.lang.ClassCastException

标签 java android exception

我正在制作一个电子商务应用程序,并且正在为该应用程序制作购物车,这是我的代码

Controller .java

package com.example.android.namkeen;

import android.app.Application;

import java.util.ArrayList;

/**
 * Created by SONY on 02-10-2016.
 */
public class Controller extends Application
{
    private ArrayList<ModelProducts> myproducts = new ArrayList<ModelProducts>();
    private ModelCart myCart = new ModelCart();
    public ModelProducts getProducts(int pPosition){
        return myproducts.get(pPosition);
    }
    public void  setProducts(ModelProducts products){
        myproducts.add(products);
    }
    public ModelCart getCart(){
        return myCart;
    }
    public int  getProductArraylistsize(){
        return myproducts.size();
    }
}

ModelCart.java

package com.example.android.namkeen;

import java.util.ArrayList;

public class ModelCart {
    private ArrayList<ModelProducts> cartItems = new ArrayList<ModelProducts>();
    public ModelProducts getProducts(int position){
        return cartItems.get(position);
    }
    public void setProducts(ModelProducts Products){
        cartItems.add(Products);
    }
    public int getCartsize(){

        return cartItems.size();
    }
    public boolean CheckProductInCart(ModelProducts aproduct){
        return cartItems.contains(aproduct);
    }
}

模型产品.java

package com.example.android.namkeen;

/**
 * Created by SONY on 02-10-2016.
 */
public class ModelProducts {
    private String productName;
    private String productDesc;
    private int productPrice;
    public ModelProducts(String productName,String productDesc,int productPrice){
        this.productName = productName;
        this.productDesc = productDesc;
        this.productPrice = productPrice;
    }

    public String getProductName(){
        return productName;
    }

    public String getProductDesc(){
        return productDesc;
    }

    public int getProductPrice(){
        return productPrice;
    }
}

这是我制作自定义 View 并使用 Controller 类添加产品的主要 Activity

 package com.example.android.namkeen;

    import android.content.Intent;
    import android.graphics.Typeface;
    import android.os.Bundle;
    import android.support.v7.app.ActionBar;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.util.TypedValue;
    import android.view.View;
    import android.widget.Button;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    import android.widget.Toast;


    public class CartMain extends AppCompatActivity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);







            final LinearLayout layout = (LinearLayout)findViewById(R.id.linearMain);
            final Button btn = (Button)findViewById(R.id.second);
            final Controller ct = (Controller) getApplicationContext();//getting error in this line 
            ModelProducts products = null;
            int Price=30;
            products = new ModelProducts("Plain Maath", "Plain salted \n big sized mathri", Price);
            ct.setProducts(products);
         /*   for(int i= 1; i<=7;i++)
            {
                int Price = 15+ i;
                products = new ModelProducts("Product Item" +i, "Description"+i, Price);
                ct.setProducts(products);
            }*/
            int productsize = ct.getProductArraylistsize();
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
            for (int j=0;j< productsize;j++){
                String pName = ct.getProducts(j).getProductName();
                int pPrice = ct.getProducts(j).getProductPrice();
                String desc = ct.getProducts(j).getProductDesc();
                LinearLayout la = new LinearLayout(this);
                la.setOrientation(LinearLayout.HORIZONTAL);

                LinearLayout la1 = new LinearLayout(this);
                la1.setOrientation(LinearLayout.VERTICAL);





                TextView tv = new TextView(this);
                tv.setText(" " + pName + " ");
                tv.setTypeface(null, Typeface.BOLD);
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22F);
                la1.addView(tv);


                TextView des = new TextView(this);
                des.setText(" " + desc + " ");

                la1.addView(des);


                TextView tv1 = new TextView(this);
                tv1.setText(" "+"Rs"+pPrice+"/250gm"+" ");
                la1.addView(tv1);
                la.addView(la1);

                final Button btn1 = new Button(this);
                btn1.setId(j+1);
                btn1.setText("Add to Cart");
                btn1.setLayoutParams(params);
                final int index = j;
                btn1.setOnClickListener(new View.OnClickListener()
                {
                    public void onClick(View v) {
    // TODO Auto-generated method stub
                        Log.i("TAG", "index:"+index);
                        ModelProducts productsObject = ct.getProducts(index);
                        if(!ct.getCart().CheckProductInCart(productsObject)){
                            btn1.setText("Item Added");
                            ct.getCart().setProducts(productsObject);
                            Toast.makeText(getApplicationContext(), "New CartSize:" +ct.getCart().getCartsize(),Toast.LENGTH_LONG).show();
                        }else{
                            Toast.makeText(getApplicationContext(), "Products"+(index+1)+"Already Added",Toast.LENGTH_LONG ).show();
                        }
                    }
                });
                la.addView(btn1);
                layout.addView(la);
            }
            btn.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v) {
    // TODO Auto-generated method stub
                    Intent in = new Intent(getBaseContext(),Screen2.class);
                    startActivity(in);
                }
            });
        }
    }

这是在购物车 Activity 中单击结帐按钮时将起作用的代码 Screen2.java

package com.example.android.namkeen;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

/**
 * Created by SONY on 02-10-2016.
 */
public class Screen2 extends AppCompatActivity
{
    /* (non-Javadoc)
    * @see android.app.Activity#onCreate(android.os.Bundle) */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen2);




        TextView showCartContent = (TextView)findViewById(R.id.showcart);
        final Controller ct = (Controller)getApplicationContext();
        final int CartSize = ct.getCart().getCartsize();
        String show = "";
        for(int i=0;i<CartSize;i++){
            String pName = ct.getCart().getProducts(i).getProductName();
            int  pPrice = ct.getCart().getProducts(i).getProductPrice();
            String pDisc = ct.getCart().getProducts(i).getProductDesc();
            show += "Product Name:"+pName+" "+"Price : "+pPrice+""+"Discription : "+pDisc+""+    "-----------------------------------";
        }
        showCartContent.setText(show);
    }
}

我做的一切都是正确的,但是当我运行这段代码时,它给出了这个异常错误

java.lang.RuntimeException:无法启动 Activity ComponentInfo{com.example.android.namkeen/com.example.android.namkeen.CartMain}:java.lang.ClassCastException:android.app.Application 无法转换为 com .example.android.namkeen.Controller

引起:java.lang.ClassCastException:android.app.Application无法转换为com.example.android.namkeen.Controller 在 com.example.android.namkeen.CartMain.onCreate(CartMain.java:32)

我无法理解我应该在哪里更改我的代码 请帮忙提前致谢

最佳答案

当您想要检索应用程序实例时,应该使用 getApplication() 而不是 getApplicationContext()。

还希望您在 list 文件中将 Controller 类声明为 Application 类。

此外,仅仅为了在其中存储数据而子类化您的 Application 类也不是最好的主意...您应该使用单例类。

关于java - 在我的应用程序中获取 java.lang.ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40388501/

相关文章:

Java用两个空格替换数字包围的一个空格

Java - 已检查与未检查异常 - 仅从代码中判断?

android - 在 BuildConfig.DEBUG 时删除 ActionbarSherlock 日志

c# - 集合被修改异常 linq-to-objects

java - 如何统计线程抛出异常的数量?

java - 从 Activity 调用 Fragment 的适配器时出现 NullPointerException

java - 无法运行 'Hello World"Spring MVC 代码

每个设备都可以升级 Android?

android - 水平格子线android textview

java - 有效地使用 UncaughtExceptionHandler