java - 带有自定义数组列表的空对象引用。在哪里实例化?
问题描述
试图完成我的估算项目真的碰壁了。想使用 gson 将自定义 ArrayList 保存到 sharedPreferences。我需要将估计值添加到估计值中(自定义 ArrayList)。我已经阅读了十几个其他类似的帖子,甚至以前也解决过类似的问题。我一直在发疯,试图弄清楚我没有正确实例化什么以及我应该在哪里做这个。我觉得我到处都试过了,但我显然错过了一些东西。
问题出在下面代码中的 .add() 上。
saveButton = findViewById(R.id.save);
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
estimates.add(newEstimate);
saveData();
}
});
这是完整的活动
public class EstimateActivity extends AppCompatActivity {
private RecyclerView eRecyclerview;
private CartAdapter eAdapter;
private RecyclerView.LayoutManager eLayoutManager;
private ArrayList<Inventory> eCartList;
private TextView clientName, clientEmail, workOrder;
private Button saveButton;
private ArrayList<Estimate> estimates;
private Estimate newEstimate;
private String name, code, email;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_estimate);
estimates = new ArrayList<>();
newEstimate = new Estimate();
//get intents
Intent intent = getIntent();
newEstimate = intent.getParcelableExtra("newEstimate");
estimates = intent.getParcelableArrayListExtra("estimates");
eCartList = intent.getParcelableArrayListExtra("cartList");
//set up textViews
workOrder= findViewById(R.id.cart_work_order);
clientName = findViewById(R.id.client_name_cart);
clientEmail = findViewById(R.id.cart_email);
name = newEstimate.getClientName();
code = newEstimate.getWorkOrder();
email = newEstimate.getClientEmail();
workOrder.setText(code);
clientName.setText(name);
clientEmail.setText(email);
//connect recyclerView
eRecyclerview = findViewById(R.id.recyclerview_cart);
eLayoutManager = new LinearLayoutManager(this);
eAdapter = new CartAdapter(eCartList);
eRecyclerview.setLayoutManager(eLayoutManager);
eRecyclerview.setAdapter(eAdapter);
newEstimate.setCart(eCartList);
//Set up save button
saveButton = findViewById(R.id.save);
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
estimates.add(newEstimate);
saveData();
}
});
}
private void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences("share preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(estimates);
editor.putString("task list", json);
editor.apply();
}
}
解决方案
估计,Inventory 类必须实现 Parcelable 接口。
根据Android API ReferencedescribeContents()
,您必须writeToParcel(Parcel dest, int flags)
正确。
并在intent.getParcelableArrayListExtra()
.
推荐阅读
- css - Shinydashboard::box 标题中的 shinyWidget::dropdownButton 样式
- ios - Fastlane crashlytics_path 通过迦太基
- angularjs - Zingchart-angularjs - 获取点击事件的数据
- powerbi - Power BI - 当我在切片器中选择某些内容时,我不希望我的卡值发生变化
- hbase - 何时使用 PrefixFilter?
- heroku - heroku:在发布阶段刷新 redis
- vba - Excel VBA:循环工作表/传输数据/为每个工作表创建新工作簿
- android - 无法在 Android 语音识别中使用长输入,初始化时出错?
- java - Android java客户端突然停止
- php - Mailchimp 等服务如何从电子邮件中签名?