fadelakin
fadelakin

Reputation: 3833

Casting application context gives an inconvertible type error

So I'm building a shopping cart application as I'm learning android development but one line of code keeps giving me an error over and over again.

It's specifically this line final Controller aController = (Controller) getApplicationContext();

I'm new to Java and Android development and every thing I've tried didn't work so I'm on SO looking for help.

This is my code from the MainActivity, the Controller class itself and the Manifest file.

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>

Upvotes: 0

Views: 1619

Answers (2)

Michael Krause
Michael Krause

Reputation: 4849

Your Controller class needs to extend android.app.Application

Upvotes: 2

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132972

To make Controller as Global Application class you will need to extend Application as:

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

Upvotes: 2

Related Questions