我正在学习编写Android应用程序,并且正在开发电子商务应用程序。当我去购物车时,我在CartActivity中不断收到nullPointerException。我敢肯定,我只是错过了一些简单的事情或做了一些愚蠢的事情,但是任何输入将不胜感激!您无需一步一步告诉我,而只需指出正确的方向即可。请别客气,因为我是Android开发的新手。
谢谢!
我将相关文件和LINK包含在整个项目中(以防万一)。
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);
}
}
CartActivity.java
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;
}
}
}
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;
}
}
DetailActivity.java
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;
}
}
}
MainActivity.java
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();
}
}
}
}
Product.java
package edu.phoenix.mbl402.week2apppp1943;
public class Product
{
private String productId;
private String name;
private String description;
private double price;
private int count;
public Product()
{
}
public String getProductId() {
return productId;
}
public String getName() {
return name;
}
public String getDescription() {
return description + "\n";
}
public double getPrice() {
return price;
}
public int getCount() { return count; }
public Product(String productId, String name, String description, double price) {
this.productId = productId;
this.name = name;
this.description = description;
this.price = price;
this.count = count;
}
}
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;
}
}
}
这是与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>
我最终希望能够汇总购物车中的物品价格,但是我什至无法在购物车中显示任何东西。
答案 0 :(得分:1)
检查您从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);
product
因此您的case_when
为空,它崩溃了。