Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/186.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 让商品出现在购物车中?_Java_Android_Android Activity - Fatal编程技术网

Java 让商品出现在购物车中?

Java 让商品出现在购物车中?,java,android,android-activity,Java,Android,Android Activity,我正在学习编写Android应用程序,我正在开发一款电子商务应用程序。当我去购物车时,我在CartActivity中不断得到一个nullPointerException。我确信我错过了一些简单的事情,或者做了一些愚蠢的事情,但是任何意见都将不胜感激!你不必一步一步地告诉我,只要给我指出正确的方向就行了。因为我是Android开发新手,所以请耐心点 谢谢大家! 我包括相关文件和整个项目(以防万一) AboutActivity.java package edu.phoenix.mbl402.week

我正在学习编写Android应用程序,我正在开发一款电子商务应用程序。当我去购物车时,我在CartActivity中不断得到一个nullPointerException。我确信我错过了一些简单的事情,或者做了一些愚蠢的事情,但是任何意见都将不胜感激!你不必一步一步地告诉我,只要给我指出正确的方向就行了。因为我是Android开发新手,所以请耐心点

谢谢大家!

我包括相关文件和整个项目(以防万一)

AboutActivity.java

package edu.phoenix.mbl402.week2apppp1943;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;

public class AboutActivity extends AppCompatActivity
{

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_about);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

}
package edu.phoenix.mbl402.week2apppp1943;

import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.Objects;
import static java.security.AccessController.getContext;

// TODO: WORK ON CART ACTIVITY
public class CartActivity extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState)
{
    CartActivity ca = new CartActivity();
    Product product = new Product();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cart);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

   String productId = getIntent().getStringExtra(MainActivity.PRODUCT_ID);
   product = DataProvider.productMap.get(productId);

    TextView tv = (TextView) findViewById(R.id.nameText);
    tv.setText(product.getName());

    NumberFormat formatter = NumberFormat.getCurrencyInstance();
    String price = formatter.format(product.getPrice());
    TextView priceText = (TextView) findViewById(R.id.priceText);
    priceText.setText(price);

    ImageView iv = (ImageView) findViewById(R.id.imageView);
    Bitmap bitmap = ca.getBitmapFromAsset(product.getProductId());
    iv.setImageBitmap(bitmap);

    String nCount = Integer.toString(product.getCount());
    ((TextView) findViewById(R.id.qty_in_cart)).setText(nCount);
}

/*    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState)
{
   super.onCreate(savedInstanceState);
   setContentView(R.layout.content_cart);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

            Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
}*/
public Bitmap getBitmapFromAsset(String productId)
{
    AssetManager assetManager = getAssets();
    InputStream stream = null;

    try {
        stream = assetManager.open(productId + ".png");
        return BitmapFactory.decodeStream(stream);
    } catch (IOException e)
    {
        e.printStackTrace();
        return null;
    }
}
}
package edu.phoenix.mbl402.week2apppp1943;

import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.security.CryptoPrimitive;
import java.text.NumberFormat;

public class DetailActivity extends AppCompatActivity
{
int count = 0;

//@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState)
{

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    String productId = getIntent().getStringExtra(MainActivity.PRODUCT_ID);
    final Product product = DataProvider.productMap.get(productId);

    TextView tv = (TextView) findViewById(R.id.nameText);
    tv.setText(product.getName());

    TextView descView = (TextView) findViewById(R.id.descriptionText);
    descView.setText(product.getDescription());

    NumberFormat formatter = NumberFormat.getCurrencyInstance();
    String price = formatter.format(product.getPrice());
    TextView priceText = (TextView) findViewById(R.id.priceText);
    priceText.setText(price);

    ImageView iv = (ImageView) findViewById(R.id.imageView);
    Bitmap bitmap = getBitmapFromAsset(product.getProductId());
    iv.setImageBitmap(bitmap);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

    fab.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            count++;
            String nCount = Integer.toString(count);
            ((TextView) findViewById(R.id.qty_in_cart)).setText(nCount);
//                Intent data = new Intent();
//                data.putExtra(MainActivity.RETURN_MESSAGE,
//                        product.getName() + " added to shopping cart");
//                setResult(RESULT_OK, data);
//                finish();
        }
    });
        //Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    FloatingActionButton fab_remove = (FloatingActionButton) findViewById(R.id.fab_remove);
    fab_remove.setOnClickListener(new View.OnClickListener()
    {

        public void onClick(View view)
        {
            count--;
            String nCount = Integer.toString(count);
            ((TextView) findViewById(R.id.qty_in_cart)).setText(nCount);

            Intent intent = new Intent(getApplicationContext(), CartActivity.class);
            intent.putExtra("Count", nCount);

            startActivity(intent);


        }
    });
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

private Bitmap getBitmapFromAsset(String productId)
{
    AssetManager assetManager = getAssets();
    InputStream stream = null;

    try {
        stream = assetManager.open(productId + ".png");
        return BitmapFactory.decodeStream(stream);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

}
package edu.phoenix.mbl402.week2apppp1943;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;

public class MainActivity extends AppCompatActivity
{

private static final int MENU_ITEM_LOGOUT = 1001;
public static final String PRODUCT_ID = "PRODUCT_ID";

private static final int DETAIL_REQUEST = 1111;
public static final String RETURN_MESSAGE = "RETURN_MESSAGE";

private CoordinatorLayout coordinatorLayout;

private static String webUrl = "http://www.google.com";
private static String email = "ppotter0003@gmail.com";

private List<Product> products = DataProvider.productList;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            // Send an email
            String[] addresses = {email};
            Intent intent = new Intent(Intent.ACTION_SENDTO);
            intent.setData(Uri.parse("mailto:"));
            intent.putExtra(Intent.EXTRA_EMAIL, addresses);
            intent.putExtra(Intent.EXTRA_SUBJECT, "Information request");
            intent.putExtra(Intent.EXTRA_TEXT, "Please send some information!");
            if (intent.resolveActivity(getPackageManager()) != null)
            {
                startActivity(intent);
            }
        }
    });

    String[] items = getResources().getStringArray(R.array.clothing);
//        ArrayAdapter<String> adapter =
//                new ArrayAdapter<>(this,
//                        android.R.layout.simple_list_item_1,
//                        android.R.id.text1, items);
    ProductListAdapter adapter = new ProductListAdapter(
            this, R.layout.list_item, products);
    ListView lv = (ListView) findViewById(R.id.listView);
    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            Intent intent = new Intent(MainActivity.this, DetailActivity.class);

            Product product = products.get(position);
            intent.putExtra(PRODUCT_ID, product.getProductId());

            startActivityForResult(intent, DETAIL_REQUEST);
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);

    menu.add(0, MENU_ITEM_LOGOUT, 1001, R.string.logout);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{

    int id = item.getItemId();

    switch (id)
    {
        case R.id.action_settings:
            Snackbar.make(coordinatorLayout,
                    "You Selected settings", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
            return true;
        case R.id.action_about:
            Snackbar.make(coordinatorLayout,
                    "You Selected About", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
            Intent intent = new Intent(this, AboutActivity.class);
            startActivity(intent);
            return true;
        case R.id.action_web:
            //Go to the website
            Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(webUrl));
            if (webIntent.resolveActivity(getPackageManager()) != null)
            {
                startActivity(webIntent);
            }
            return true;
        case R.id.action_cart:
           Snackbar.make(coordinatorLayout,
                   "Going To Shopping Cart", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
            intent = new Intent(this, CartActivity.class);
            startActivity(intent);
           return true;

        case MENU_ITEM_LOGOUT:
            Snackbar.make(coordinatorLayout,
                    "You selected Logout", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
            return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == DETAIL_REQUEST)
    {
        if (resultCode == RESULT_OK)
        {
            String message = data.getStringExtra(RETURN_MESSAGE);
            Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG)
                    .setAction("Go to cart", new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            Toast.makeText(MainActivity.this,
                                    "Going to cart", Toast.LENGTH_SHORT).show();

                        }
                    }).show();
        }
    }
}
}
CartActivity.java

package edu.phoenix.mbl402.week2apppp1943;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;

public class AboutActivity extends AppCompatActivity
{

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_about);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

}
package edu.phoenix.mbl402.week2apppp1943;

import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.Objects;
import static java.security.AccessController.getContext;

// TODO: WORK ON CART ACTIVITY
public class CartActivity extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState)
{
    CartActivity ca = new CartActivity();
    Product product = new Product();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cart);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

   String productId = getIntent().getStringExtra(MainActivity.PRODUCT_ID);
   product = DataProvider.productMap.get(productId);

    TextView tv = (TextView) findViewById(R.id.nameText);
    tv.setText(product.getName());

    NumberFormat formatter = NumberFormat.getCurrencyInstance();
    String price = formatter.format(product.getPrice());
    TextView priceText = (TextView) findViewById(R.id.priceText);
    priceText.setText(price);

    ImageView iv = (ImageView) findViewById(R.id.imageView);
    Bitmap bitmap = ca.getBitmapFromAsset(product.getProductId());
    iv.setImageBitmap(bitmap);

    String nCount = Integer.toString(product.getCount());
    ((TextView) findViewById(R.id.qty_in_cart)).setText(nCount);
}

/*    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState)
{
   super.onCreate(savedInstanceState);
   setContentView(R.layout.content_cart);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

            Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
}*/
public Bitmap getBitmapFromAsset(String productId)
{
    AssetManager assetManager = getAssets();
    InputStream stream = null;

    try {
        stream = assetManager.open(productId + ".png");
        return BitmapFactory.decodeStream(stream);
    } catch (IOException e)
    {
        e.printStackTrace();
        return null;
    }
}
}
package edu.phoenix.mbl402.week2apppp1943;

import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.security.CryptoPrimitive;
import java.text.NumberFormat;

public class DetailActivity extends AppCompatActivity
{
int count = 0;

//@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState)
{

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    String productId = getIntent().getStringExtra(MainActivity.PRODUCT_ID);
    final Product product = DataProvider.productMap.get(productId);

    TextView tv = (TextView) findViewById(R.id.nameText);
    tv.setText(product.getName());

    TextView descView = (TextView) findViewById(R.id.descriptionText);
    descView.setText(product.getDescription());

    NumberFormat formatter = NumberFormat.getCurrencyInstance();
    String price = formatter.format(product.getPrice());
    TextView priceText = (TextView) findViewById(R.id.priceText);
    priceText.setText(price);

    ImageView iv = (ImageView) findViewById(R.id.imageView);
    Bitmap bitmap = getBitmapFromAsset(product.getProductId());
    iv.setImageBitmap(bitmap);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

    fab.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            count++;
            String nCount = Integer.toString(count);
            ((TextView) findViewById(R.id.qty_in_cart)).setText(nCount);
//                Intent data = new Intent();
//                data.putExtra(MainActivity.RETURN_MESSAGE,
//                        product.getName() + " added to shopping cart");
//                setResult(RESULT_OK, data);
//                finish();
        }
    });
        //Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    FloatingActionButton fab_remove = (FloatingActionButton) findViewById(R.id.fab_remove);
    fab_remove.setOnClickListener(new View.OnClickListener()
    {

        public void onClick(View view)
        {
            count--;
            String nCount = Integer.toString(count);
            ((TextView) findViewById(R.id.qty_in_cart)).setText(nCount);

            Intent intent = new Intent(getApplicationContext(), CartActivity.class);
            intent.putExtra("Count", nCount);

            startActivity(intent);


        }
    });
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

private Bitmap getBitmapFromAsset(String productId)
{
    AssetManager assetManager = getAssets();
    InputStream stream = null;

    try {
        stream = assetManager.open(productId + ".png");
        return BitmapFactory.decodeStream(stream);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

}
package edu.phoenix.mbl402.week2apppp1943;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;

public class MainActivity extends AppCompatActivity
{

private static final int MENU_ITEM_LOGOUT = 1001;
public static final String PRODUCT_ID = "PRODUCT_ID";

private static final int DETAIL_REQUEST = 1111;
public static final String RETURN_MESSAGE = "RETURN_MESSAGE";

private CoordinatorLayout coordinatorLayout;

private static String webUrl = "http://www.google.com";
private static String email = "ppotter0003@gmail.com";

private List<Product> products = DataProvider.productList;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            // Send an email
            String[] addresses = {email};
            Intent intent = new Intent(Intent.ACTION_SENDTO);
            intent.setData(Uri.parse("mailto:"));
            intent.putExtra(Intent.EXTRA_EMAIL, addresses);
            intent.putExtra(Intent.EXTRA_SUBJECT, "Information request");
            intent.putExtra(Intent.EXTRA_TEXT, "Please send some information!");
            if (intent.resolveActivity(getPackageManager()) != null)
            {
                startActivity(intent);
            }
        }
    });

    String[] items = getResources().getStringArray(R.array.clothing);
//        ArrayAdapter<String> adapter =
//                new ArrayAdapter<>(this,
//                        android.R.layout.simple_list_item_1,
//                        android.R.id.text1, items);
    ProductListAdapter adapter = new ProductListAdapter(
            this, R.layout.list_item, products);
    ListView lv = (ListView) findViewById(R.id.listView);
    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            Intent intent = new Intent(MainActivity.this, DetailActivity.class);

            Product product = products.get(position);
            intent.putExtra(PRODUCT_ID, product.getProductId());

            startActivityForResult(intent, DETAIL_REQUEST);
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);

    menu.add(0, MENU_ITEM_LOGOUT, 1001, R.string.logout);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{

    int id = item.getItemId();

    switch (id)
    {
        case R.id.action_settings:
            Snackbar.make(coordinatorLayout,
                    "You Selected settings", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
            return true;
        case R.id.action_about:
            Snackbar.make(coordinatorLayout,
                    "You Selected About", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
            Intent intent = new Intent(this, AboutActivity.class);
            startActivity(intent);
            return true;
        case R.id.action_web:
            //Go to the website
            Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(webUrl));
            if (webIntent.resolveActivity(getPackageManager()) != null)
            {
                startActivity(webIntent);
            }
            return true;
        case R.id.action_cart:
           Snackbar.make(coordinatorLayout,
                   "Going To Shopping Cart", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
            intent = new Intent(this, CartActivity.class);
            startActivity(intent);
           return true;

        case MENU_ITEM_LOGOUT:
            Snackbar.make(coordinatorLayout,
                    "You selected Logout", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
            return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == DETAIL_REQUEST)
    {
        if (resultCode == RESULT_OK)
        {
            String message = data.getStringExtra(RETURN_MESSAGE);
            Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG)
                    .setAction("Go to cart", new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            Toast.makeText(MainActivity.this,
                                    "Going to cart", Toast.LENGTH_SHORT).show();

                        }
                    }).show();
        }
    }
}
}
DataProvider.java

package edu.phoenix.mbl402.week2apppp1943;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public final class DataProvider
{

public static List<Product> productList = new ArrayList<>();
public static Map<String, Product> productMap = new HashMap<>();

static {

    addProduct("shirt101",
            "Umbrella T-Shirt",
            "Cute, red t-shirt, featuring a person chasing a flying away umbrella. Made with 100% cotton.",
            35);

    addProduct("jacket101",
            "Girls Pink Coat",
            "Super stylish, girls pink goose down coat. Stuffed with all natural goose down that contains a waterproof outer layer.",
            88);

    addProduct("outfit101",
            "Ladybug Girls Outfit",
            "Stylish girls ladybug outfit will have you looking fabulous. Made with 100% cotton and woven spandex fibers to move with you anywhere you go.",
            55);

    addProduct("shirt102",
            "Red Sushi T-Shirt",
            "Red t-shirt featuring chopsticks and a piece of sushi will have your child looking hip. Made with 100% cotton.",
            35);

    addProduct("shirt103",
            "Peppa Pig Onesie",
            "Peppa pig themed baby onesie, is perfect for easy clothing needs of a baby. Featuring sizes zero months to eighteen.",
            26);

    addProduct("shirt107",
            "Daddy Pig T-Shirt",
            "Daddy Pig themed t-shirt is perfect for Peppa Pig fans. Made with 100% cotton.",
            35);

    addProduct("shirt104",
            "Polo Shirt",
            "Our pre-shrunk organic cotton polo shirt is perfect for weekend activities, lounging around the house, and casual days at the park or school.",
            38);

    addProduct("shirt105",
            "Blue Hammerhead Shark T-Shirt",
            "Baby blue shark t-shirt is perfect for fans of sharks or just comfy t-shirts. Made with 100% cotton.",
            45);

    addProduct("jacket102",
            "Thermal Fleece Jacket",
            "Our thermal organic fleece jacket, is brushed on both sides for ultra softness and warmth. This medium-weight jacket is versatile all year around, and can be worn with layers for the winter season.",
            85);

    addProduct("shirt109",
            "Yellow Shark Graphic T-Shirt",
            "Bright yellow graphic t-shirt is an attention getter and great for school or out to play. Made with 100% cotton.",
            35);

    addProduct("shirt111",
            "Rainbow Unicorn T-Shirt",
            "Rainbow girls or boys unicorn t-shirt features a silly unicorn throwing up a rainbow.",
            28);

    addProduct("shirt108",
            "Yellow Mr. Strong T-Shirt",
            "Bright yellow t-shirt feature Mr. Strong from Mr. Happy and friends will bring back nostalgia. Made with 100% cotton.",
            75);

    addProduct("vest101",
            "Green Down Vest",
            "Green goose down vest is perfect for chilly mornings but not too hot that your little one suffers.",
            35);
}

private static void addProduct(String itemId, String name,
                               String description, double price) {
    Product item = new Product(itemId, name, description, price);
    productList.add(item);
    productMap.put(itemId, item);
}

public static List<String> getProductNames() {
    List<String> list = new ArrayList<>();
    for (Product product : productList) {
        list.add(product.getName());
    }
    return list;
}

public static List<Product> getFilteredList(String searchString) {

    List<Product> filteredList = new ArrayList<>();
    for (Product product : productList) {
        if (product.getProductId().contains(searchString)) {
            filteredList.add(product);
        }
    }

    return filteredList;

}

}
MainActivity.java

package edu.phoenix.mbl402.week2apppp1943;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;

public class AboutActivity extends AppCompatActivity
{

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_about);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

}
package edu.phoenix.mbl402.week2apppp1943;

import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.Objects;
import static java.security.AccessController.getContext;

// TODO: WORK ON CART ACTIVITY
public class CartActivity extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState)
{
    CartActivity ca = new CartActivity();
    Product product = new Product();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cart);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

   String productId = getIntent().getStringExtra(MainActivity.PRODUCT_ID);
   product = DataProvider.productMap.get(productId);

    TextView tv = (TextView) findViewById(R.id.nameText);
    tv.setText(product.getName());

    NumberFormat formatter = NumberFormat.getCurrencyInstance();
    String price = formatter.format(product.getPrice());
    TextView priceText = (TextView) findViewById(R.id.priceText);
    priceText.setText(price);

    ImageView iv = (ImageView) findViewById(R.id.imageView);
    Bitmap bitmap = ca.getBitmapFromAsset(product.getProductId());
    iv.setImageBitmap(bitmap);

    String nCount = Integer.toString(product.getCount());
    ((TextView) findViewById(R.id.qty_in_cart)).setText(nCount);
}

/*    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState)
{
   super.onCreate(savedInstanceState);
   setContentView(R.layout.content_cart);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

            Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
}*/
public Bitmap getBitmapFromAsset(String productId)
{
    AssetManager assetManager = getAssets();
    InputStream stream = null;

    try {
        stream = assetManager.open(productId + ".png");
        return BitmapFactory.decodeStream(stream);
    } catch (IOException e)
    {
        e.printStackTrace();
        return null;
    }
}
}
package edu.phoenix.mbl402.week2apppp1943;

import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.security.CryptoPrimitive;
import java.text.NumberFormat;

public class DetailActivity extends AppCompatActivity
{
int count = 0;

//@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState)
{

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    String productId = getIntent().getStringExtra(MainActivity.PRODUCT_ID);
    final Product product = DataProvider.productMap.get(productId);

    TextView tv = (TextView) findViewById(R.id.nameText);
    tv.setText(product.getName());

    TextView descView = (TextView) findViewById(R.id.descriptionText);
    descView.setText(product.getDescription());

    NumberFormat formatter = NumberFormat.getCurrencyInstance();
    String price = formatter.format(product.getPrice());
    TextView priceText = (TextView) findViewById(R.id.priceText);
    priceText.setText(price);

    ImageView iv = (ImageView) findViewById(R.id.imageView);
    Bitmap bitmap = getBitmapFromAsset(product.getProductId());
    iv.setImageBitmap(bitmap);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

    fab.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            count++;
            String nCount = Integer.toString(count);
            ((TextView) findViewById(R.id.qty_in_cart)).setText(nCount);
//                Intent data = new Intent();
//                data.putExtra(MainActivity.RETURN_MESSAGE,
//                        product.getName() + " added to shopping cart");
//                setResult(RESULT_OK, data);
//                finish();
        }
    });
        //Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    FloatingActionButton fab_remove = (FloatingActionButton) findViewById(R.id.fab_remove);
    fab_remove.setOnClickListener(new View.OnClickListener()
    {

        public void onClick(View view)
        {
            count--;
            String nCount = Integer.toString(count);
            ((TextView) findViewById(R.id.qty_in_cart)).setText(nCount);

            Intent intent = new Intent(getApplicationContext(), CartActivity.class);
            intent.putExtra("Count", nCount);

            startActivity(intent);


        }
    });
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

private Bitmap getBitmapFromAsset(String productId)
{
    AssetManager assetManager = getAssets();
    InputStream stream = null;

    try {
        stream = assetManager.open(productId + ".png");
        return BitmapFactory.decodeStream(stream);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

}
package edu.phoenix.mbl402.week2apppp1943;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;

public class MainActivity extends AppCompatActivity
{

private static final int MENU_ITEM_LOGOUT = 1001;
public static final String PRODUCT_ID = "PRODUCT_ID";

private static final int DETAIL_REQUEST = 1111;
public static final String RETURN_MESSAGE = "RETURN_MESSAGE";

private CoordinatorLayout coordinatorLayout;

private static String webUrl = "http://www.google.com";
private static String email = "ppotter0003@gmail.com";

private List<Product> products = DataProvider.productList;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            // Send an email
            String[] addresses = {email};
            Intent intent = new Intent(Intent.ACTION_SENDTO);
            intent.setData(Uri.parse("mailto:"));
            intent.putExtra(Intent.EXTRA_EMAIL, addresses);
            intent.putExtra(Intent.EXTRA_SUBJECT, "Information request");
            intent.putExtra(Intent.EXTRA_TEXT, "Please send some information!");
            if (intent.resolveActivity(getPackageManager()) != null)
            {
                startActivity(intent);
            }
        }
    });

    String[] items = getResources().getStringArray(R.array.clothing);
//        ArrayAdapter<String> adapter =
//                new ArrayAdapter<>(this,
//                        android.R.layout.simple_list_item_1,
//                        android.R.id.text1, items);
    ProductListAdapter adapter = new ProductListAdapter(
            this, R.layout.list_item, products);
    ListView lv = (ListView) findViewById(R.id.listView);
    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            Intent intent = new Intent(MainActivity.this, DetailActivity.class);

            Product product = products.get(position);
            intent.putExtra(PRODUCT_ID, product.getProductId());

            startActivityForResult(intent, DETAIL_REQUEST);
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);

    menu.add(0, MENU_ITEM_LOGOUT, 1001, R.string.logout);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{

    int id = item.getItemId();

    switch (id)
    {
        case R.id.action_settings:
            Snackbar.make(coordinatorLayout,
                    "You Selected settings", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
            return true;
        case R.id.action_about:
            Snackbar.make(coordinatorLayout,
                    "You Selected About", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
            Intent intent = new Intent(this, AboutActivity.class);
            startActivity(intent);
            return true;
        case R.id.action_web:
            //Go to the website
            Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(webUrl));
            if (webIntent.resolveActivity(getPackageManager()) != null)
            {
                startActivity(webIntent);
            }
            return true;
        case R.id.action_cart:
           Snackbar.make(coordinatorLayout,
                   "Going To Shopping Cart", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
            intent = new Intent(this, CartActivity.class);
            startActivity(intent);
           return true;

        case MENU_ITEM_LOGOUT:
            Snackbar.make(coordinatorLayout,
                    "You selected Logout", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
            return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == DETAIL_REQUEST)
    {
        if (resultCode == RESULT_OK)
        {
            String message = data.getStringExtra(RETURN_MESSAGE);
            Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG)
                    .setAction("Go to cart", new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            Toast.makeText(MainActivity.this,
                                    "Going to cart", Toast.LENGTH_SHORT).show();

                        }
                    }).show();
        }
    }
}
}
ProductListAdapter.java

package edu.phoenix.mbl402.week2apppp1943;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.List;

public class ProductListAdapter extends ArrayAdapter<Product>
{

private List<Product> products;

public ProductListAdapter(Context context, int resource, List<Product> objects)
{
    super(context, resource, objects);
    products = objects;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{

    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).
                inflate(R.layout.list_item, parent, false);
    }

    Product product = products.get(position);

    TextView nameText = (TextView) convertView.findViewById(R.id.nameText);
    nameText.setText(product.getName());

    NumberFormat formatter = NumberFormat.getCurrencyInstance();
    String price = formatter.format(product.getPrice());
    TextView priceText = (TextView) convertView.findViewById(R.id.priceText);
    priceText.setText(price);

    ImageView iv = (ImageView) convertView.findViewById(R.id.imageView);
    Bitmap bitmap = getBitmapFromAsset(product.getProductId());
    iv.setImageBitmap(bitmap);

    return convertView;
}

public Bitmap getBitmapFromAsset(String productId)
{
    AssetManager assetManager = getContext().getAssets();
    InputStream stream = null;

    try {
        stream = assetManager.open(productId + ".png");
        return BitmapFactory.decodeStream(stream);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

}
包edu.phoenix.mbl402.week2apppp1943;
导入android.content.Context;
导入android.content.res.AssetManager;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.ArrayAdapter;
导入android.widget.ImageView;
导入android.widget.TextView;
导入java.io.IOException;
导入java.io.InputStream;
导入java.text.NumberFormat;
导入java.util.List;
公共类ProductListAdapter扩展了ArrayAdapter
{
私人上市产品;
public ProductListAdapter(上下文、int资源、列表对象)
{
超级(上下文、资源、对象);
产品=对象;
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图)
{
if(convertView==null){
convertView=LayoutInflater.from(getContext())。
充气(R.layout.list\u项,父项,假);
}
产品=产品。获取(位置);
TextView nameText=(TextView)convertView.findViewById(R.id.nameText);
nameText.setText(product.getName());
NumberFormat formatter=NumberFormat.getCurrencyInstance();
字符串price=formatter.format(product.getPrice());
TextView priceText=(TextView)convertView.findViewById(R.id.priceText);
priceText.setText(price);
ImageView iv=(ImageView)convertView.findViewById(R.id.ImageView);
位图位图=getBitmapFromAsset(product.getProductId());
iv.设置图像位图(位图);
返回视图;
}
公共位图getBitmapFromAsset(字符串productId)
{
AssetManager AssetManager=getContext().getAssets();
InputStream=null;
试一试{
stream=assetManager.open(productId+“.png”);
返回BitmapFactory.decodeStream(流);
}捕获(IOE异常){
e、 printStackTrace();
返回null;
}
}
}
下面是与CartActivity.java关联的两个xml文件。 activity_cart.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="edu.phoenix.mbl402.week2apppp1943.CartActivity">



<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
    android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_cart" />

</android.support.constraint.ConstraintLayout>

content_cart.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".CartActivity"
tools:showIn="@layout/activity_cart">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_alignParentStart="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="64dp"
    android:src="@drawable/jacket101"
    android:contentDescription="@string/description" />

<TextView
    android:id="@+id/nameText"
    android:layout_width="256dp"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_alignTop="@+id/imageView"
    android:paddingLeft="10dp"
    android:text="@string/nameTextView"
    android:textSize="14sp"
    android:paddingStart="10dp" />

<TextView
    android:id="@+id/priceText"
    android:layout_width="145dp"
    android:layout_height="wrap_content"
    android:layout_below="@+id/nameText"
    android:layout_centerHorizontal="true"
    android:text="@string/priceTextView"
    android:textSize="14sp" />

<TextView
    android:id="@+id/qtyText"
    android:layout_width="56dp"
    android:layout_height="wrap_content"
    android:layout_alignStart="@+id/priceText"
    android:layout_alignLeft="@+id/priceText"
    android:layout_below="@+id/priceText"
    android:text="@string/qtyTextView"
    android:textSize="14sp" />

<TextView
    android:id="@+id/qty_in_cart"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/priceText"
    android:layout_centerHorizontal="true"
    android:text="@string/qty_in_cart"
    android:textStyle="bold"
    android:visibility="visible"
    tools:text="0" />

<TextView
    android:id="@+id/totalText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignStart="@+id/priceText"
    android:layout_alignLeft="@+id/priceText"
    android:layout_marginTop="120dp"
    android:text="@string/totalTextView" />

<TextView
    android:id="@+id/total_in_cart"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/qty_in_cart"
    android:layout_centerHorizontal="true"
    android:text="@string/total"
    android:textStyle="bold"
    android:visibility="visible"
    tools:text="0" />


</RelativeLayout>


我最终希望能够合计购物车中的物品价格,但我甚至无法在购物车中显示任何东西。

检查您开始的代码
CartActivity

case R.id.action_cart:
       Snackbar.make(coordinatorLayout,
               "Going To Shopping Cart", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show();
        intent = new Intent(this, CartActivity.class);
        startActivity(intent);
       return true;
您没有将
productId
传递到
CartActivity
,而在
CartActivity
中,您正在使用
productId

  String productId = getIntent().getStringExtra(MainActivity.PRODUCT_ID);
  product = DataProvider.productMap.get(productId);

因此,您的
产品
为空,正在崩溃。

天哪,这是太多的代码附加您的错误日志为所有代码感到抱歉。问题在于CartActivity.java。这是我的错误日志,只有相关的错误日志导致它太长:java.lang.NullPointerException:尝试在edu.phoenix.mbl402.week2apppp1943.Product.getName()的空对象引用上调用虚拟方法“java.lang.String edu.phoenix.mbl402.week2apppp1943.CartActivity.onCreate(CartActivity.java:42)