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

时间:2016-11-02 19:45:49

标签: 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);
    }
}

ModelProducts.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;
    }
}

这是我正在制作自定义视图的主要活动,我使用控制器类来添加产品

 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);
                }
            });
        }
    }

这是在购物车活动中点击结帐按钮时可以使用的代码 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:无法启动活动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)

我无法理解在应该更改代码的地方应该怎么做 请提前帮助谢谢

1 个答案:

答案 0 :(得分:1)

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

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

将Application类子类化为仅存储数据并不是最好的想法......你应该使用单例类。