转换应用程序上下文会产生不可逆转的类型错误

时间:2014-09-22 17:34:56

标签: java android-activity android android-context

所以我正在构建一个购物车应用程序,因为我正在学习android开发,但是一行代码一直给我一个错误。

特别是这一行final Controller aController = (Controller) getApplicationContext();

我是Java和Android开发的新手,我尝试的每件事都没有用,所以我正在寻求帮助。

这是来自MainActivity,Controller类本身和Manifest文件的代码。

MainActivity.java

public class MainActivity extends Activity {

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

     final LinearLayout lm = (LinearLayout) findViewById(R.id.linearMain);
     final Button secondBtn = (Button) findViewById(R.id.second);

     //Get Global Controller Class object (see application tag in AndroidManifest.xml)
     // final Controller aController = new Controller();
     final Controller aController = (Controller) getApplicationContext(); // Line giving me problems.


     /******************  Create Dummy Products Data  ***********/

     Products productObject = null;
     for(int i=1;i<=4;i++)
     {
         int price = 10+i;
         // Create product model class object
         productObject = new Products("Product "+i,"Description "+i,price);

         //store product object to array list in controller
         aController.setProducts(productObject);

     }

     /******************  Products Data Creation End   ***********/


     /******* Create view elements dynamically and show on activity ******/

     //Product array list size
     int ProductsSize = aController.getProductsArraylistSize();

     // create the layout params that will be used to define how your
     // button will be displayed
     LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
             ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);

     /******** Dynamically create view elements - Start **********/

     for(int j=0;j< ProductsSize;j++)
     {
         // Get product data from product data array list
         String pName = aController.getProducts(j).getProductName();
         int pPrice   = aController.getProducts(j).getProductPrice();

         // Create LinearLayout to view elemnts
         LinearLayout ll = new LinearLayout(this);
         ll.setOrientation(LinearLayout.HORIZONTAL);

         TextView product = new TextView(this);
         product.setText(" "+pName+"    ");

         //Add textView to LinearLayout
         ll.addView(product);

         TextView price = new TextView(this);
         price.setText("  $"+pPrice+"     ");

         //Add textView to LinearLayout
         ll.addView(price);

         final Button btn = new Button(this);
         btn.setId(j+1);
         btn.setText("Add To Cart");

         // set the layoutParams on the button
         btn.setLayoutParams(params);

         final int index = j;

         //Create click listener for dynamically created button
         btn.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {

                 //Clicked button index
                 Log.i("TAG", "index :" + index);

                 // Get product instance for index
                 Products tempProductObject = aController.getProducts(index);

                 //Check Product already exist in Cart or Not
                 if(!aController.getCart().checkProductInCart(tempProductObject))
                 {
                     btn.setText("Added");

                     // Product not Exist in cart so add product to
                     // Cart product arraylist
                     aController.getCart().setProducts(tempProductObject);

                     Toast.makeText(getApplicationContext(),
                             "Now Cart size: " + aController.getCart().getCartSize(),
                             Toast.LENGTH_LONG).show();
                }
                else
                {
                    // Cart product arraylist contains Product
                    Toast.makeText(getApplicationContext(),
                            "Product "+(index+1)+" already added in cart.",
                            Toast.LENGTH_LONG).show();
                }
            }
        });

        //Add button to LinearLayout
        ll.addView(btn);

        //Add LinearLayout to XML layout
        lm.addView(ll);
    }

    /******** Dynamically create view elements - End **********/

    secondBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            Intent i = new Intent(getBaseContext(), SecondActivity.class);
            startActivity(i);
        }
    });
  }
}

Controller.java

public class Controller {

 private  ArrayList<Products> myProducts = new ArrayList<Products>();
 private  Cart myCart = new Cart();


 public Products getProducts(int pPosition) {

     return myProducts.get(pPosition);
 }

 public void setProducts(Products Products) {

     myProducts.add(Products);

 }

 public Cart getCart() {

     return myCart;

 }

 public int getProductsArraylistSize() {

     return myProducts.size();
  }
}

的AndroidManifest.xml

<application
   android:allowBackup="true"
   android:icon="@drawable/ic_launcher"
   android:label="@string/app_name"
   android:theme="@style/AppTheme"
   android:name="com.appdevy.projectestimation.Controller">
   <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

2 个答案:

答案 0 :(得分:2)

要将Controller设为全局应用程序类,您需要将Application扩展为:

public class Controller extends Application{
  //....
}

答案 1 :(得分:2)

您的Controller类需要扩展android.app.Application