我在String中有两个日期,我将它们比作这样:
SimpleDateFormat formatter = new SimpleDateFormat("MMMM' 'dd', 'yyyy");
Date date1 = formatter.parse(final_date.toString());
Log.e("Taggal Selected:",date1.toString());
String str2 = "March 10, 2017";
Date date2 = formatter.parse(str2);
if (date1.compareTo(date2)<0)
{
btn_lunch.setBackgroundResource(R.drawable.lunch_inactive);
btn_dinner.setBackgroundResource(R.drawable.dinner_inactive);
} else if(date1.compareTo(date2)==0) {
date.setText("Tanggal 2 sama 1");
} else {
btn_lunch.setBackgroundResource(R.drawable.lunch_inactive);
btn_dinner.setBackgroundResource(R.drawable.dinner_inactive);
date.setText("Tanggal 1 lebih besar dari tanggal 2");
}
但在尝试使用 setBackgroundResource 更改按钮时出现错误,错误显示...
java.lang.NullPointerException:尝试调用虚方法&#39; void android.widget.Button.setBackgroundResource(INT)&#39;在null对象上 参考
尝试更改按钮或设置启用按钮时代码只是错误..代码通常可以在尝试使用textview时使用... 我的错在哪里?
这是我完整的课程..
public class ProductBuyActivity extends AppCompatActivity {
private int year;
private int month;
private int day;
private int user_id;
public String token = "",difday,diff,val;
static TextView date;
ImageView imgbg;
ProgressDialog pDialog;
public Button btn_lunch,btn_dinner;
Context context;
public final GlobalVar globalvar = (GlobalVar)GlobalVar.getAppContex();
public String final_date;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_buy_layout);
SharedPreferences shared = getSharedPreferences(getResources().getString(R.string.shared), MODE_PRIVATE);
final String userdata = shared.getString("user_data", "");
Bundle extras = getIntent().getExtras();
try {
JSONObject userobject = new JSONObject(userdata);
user_id = userobject.getInt("id");
} catch (JSONException e) {
e.printStackTrace();
}
AssetManager am = this.getApplicationContext().getAssets();
TextView login_title = (TextView)findViewById(R.id.title);
TextView product_name = (TextView)findViewById(R.id.product_name);
product_name.setText(globalvar.getProductName());
TextView product_portion = (TextView)findViewById(R.id.product_portion);
product_portion.setText(String.valueOf(globalvar.getQty())+" Portion");
imgbg = (ImageView) findViewById(R.id.imagebg);
String detailimg = extras.getString("ImageURL");
int total_price = 0;
total_price = Integer.valueOf(globalvar.getProductPrice()) * globalvar.getQty();
if(globalvar.getFrom().equals("main")){
total_price = Integer.valueOf(globalvar.getProductPrice()) * globalvar.getQty();
}else{
total_price = Integer.valueOf(globalvar.getProductPrice()) * globalvar.getQty();
}
TextView product_price = (TextView)findViewById(R.id.product_price);
product_price.setTypeface(font);
product_price.setText(HelperClass.price(String.valueOf(total_price)));
TextView txt = (TextView)findViewById(R.id.txt1);
txt.setTypeface(font4);
btn_lunch = (Button) findViewById(R.id.lunch);
btn_dinner = (Button) findViewById(R.id.dinner);
Button btn1 = (Button)findViewById(R.id.btn1);
btn1.setTypeface(font);
Button btn2 = (Button)findViewById(R.id.btn2);
btn2.setTypeface(font);
date = (TextView)findViewById(R.id.date);
date.setTypeface(font);
request_validation();
// Get current date by calender
// Button listener to show date picker dialog
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// Show current date
StringBuilder current_date = new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" ");
SimpleDateFormat dateFormat = new SimpleDateFormat("M-dd-yyyy", Locale.getDefault());
Date mydate = null;
try{
mydate = dateFormat.parse(current_date.toString());
}catch(ParseException e){
e.printStackTrace();
}
SimpleDateFormat custome_date = new SimpleDateFormat("MMMM' 'dd','yyyy", Locale.getDefault());
String final_date = custome_date.format(mydate);
globalvar.setDate(final_date);
date.setText(final_date);
// Button listener to show date picker dialog
date.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
show_date_picker();
}
});
ImageView back = (ImageView)findViewById(R.id.back_button);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
go_back();
}
});
globalvar.setOrderTime(0);
}
public void setdate(){
GlobalVar globalvar = (GlobalVar)GlobalVar.getAppContex();
difday = globalvar.get_diffday();
int adddate=0;
String logadd = String.valueOf(adddate);
Log.e("Logadd",logadd);
if(difday.equals("2")){
adddate = 2;
logadd = String.valueOf(adddate);
Log.e("Logadd2",logadd);
}else {
adddate = 1;
logadd = String.valueOf(adddate);
Log.e("Logadd1",logadd);
}
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// Show current date
StringBuilder current_date = new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day+adddate).append("-")
.append(year).append(" ");
SimpleDateFormat dateFormat = new SimpleDateFormat("M-dd-yyyy", Locale.getDefault());
Date mydate = null;
try{
mydate = dateFormat.parse(current_date.toString());
}catch(ParseException e){
e.printStackTrace();
}
SimpleDateFormat custome_date = new SimpleDateFormat("MMMM' 'dd','yyyy", Locale.getDefault());
String final_date = custome_date.format(mydate);
globalvar.setDate(final_date);
date.setText(final_date);
}
public void go_checkout(View v){
DatabaseHandler db = new DatabaseHandler(this);
ShoppingCartList cartlist = new ShoppingCartList();
cartlist.setProductId(globalvar.getProductId());
cartlist.setProductName(globalvar.getProductName());
cartlist.setProductPrice(globalvar.getProductPrice());
cartlist.setImage(globalvar.getImage());
cartlist.setQty(globalvar.getQty());
cartlist.setDate(globalvar.getDate());
cartlist.setOrderTime(globalvar.getOrderTime());
cartlist.setProductSellingPrice(globalvar.getProductSellingPrice());
cartlist.setuserID(user_id);
//db.addCart(cartlist);
if(globalvar.getFrom().equals("main")){
if(db.Cart_Exists(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate(), user_id)){
ShoppingCartList cart_detail = db.getCart(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate(), user_id);
}
// if(db.Cart_Exists(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate())){
//
// ShoppingCartList cart_detail = db.getCart(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate());
//
// cart_detail.setQty(cart_detail.getQty() + globalvar.getQty());
//
// db.updateChart(cart_detail);
}else{
db.addCart(cartlist);
}
if(globalvar.getFrom().equals("main")){
if(db.Cart_Exists(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate(),user_id)){
ShoppingCartList cart_detail = db.getCart(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate(),user_id);
cart_detail.setQty(cart_detail.getQty() + globalvar.getQty());
db.updateChart(cart_detail);
}else{
db.addCart(cartlist);
}
}
else{
if(db.Cart_ExistsPaket(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate(),user_id)){
ShoppingCartList cart_detail = db.getCartPaket(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate(),user_id);
cart_detail.setQty(cart_detail.getQty() + globalvar.getQty());
db.updateChartPaket(cart_detail);
}else{
db.addCartPaket(cartlist);
}
}
db.close();
Toast.makeText(ProductBuyActivity.this, "Added To Shopping Cart", Toast.LENGTH_LONG).show();
if(globalvar.getFrom().equals("main")){
this.finish();
Intent intent = new Intent(this, ShoppingCartActivity.class);
startActivity(intent);
}else{
// this.finish();
// Intent intent = new Intent(this, OrderPacketActivity.class);
// startActivity(intent);
}
}
public void go_addchart(View v){
DatabaseHandler db = new DatabaseHandler(this);
ShoppingCartList cartlist = new ShoppingCartList();
cartlist.setProductId(globalvar.getProductId());
cartlist.setProductName(globalvar.getProductName());
cartlist.setProductPrice(globalvar.getProductPrice());
cartlist.setImage(globalvar.getImage());
cartlist.setQty(globalvar.getQty());
cartlist.setDate(globalvar.getDate());
cartlist.setOrderTime(globalvar.getOrderTime());
cartlist.setProductSellingPrice(globalvar.getProductSellingPrice());
cartlist.setuserID(user_id);
if(globalvar.getFrom().equals("main")){
if(db.Cart_Exists(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate(),user_id)){
ShoppingCartList cart_detail = db.getCart(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate(),user_id);
cart_detail.setQty(cart_detail.getQty() + globalvar.getQty());
db.updateChart(cart_detail);
}else{
db.addCart(cartlist);
}
}else{
if(db.Cart_ExistsPaket(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate(),user_id)){
ShoppingCartList cart_detail = db.getCartPaket(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate(),user_id);
cart_detail.setQty(cart_detail.getQty() + globalvar.getQty());
db.updateChartPaket(cart_detail);
}else{
db.addCartPaket(cartlist);
}
}
db.close();
Toast.makeText(ProductBuyActivity.this, "Added To Shopping Cart", Toast.LENGTH_LONG).show();
if(globalvar.getFrom().equals("main")){
this.finish();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
public void selectlunch(View v){
btn_lunch.setBackgroundResource(R.drawable.lunch_active);
btn_dinner.setBackgroundResource(R.drawable.dinner_inactive);
globalvar.setOrderTime(0);
}
public void selectdinner(View v){
btn_lunch.setBackgroundResource(R.drawable.lunch_inactive);
btn_dinner.setBackgroundResource(R.drawable.dinner_active);
globalvar.setOrderTime(1);
}
private void show_date_picker(){
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener,DatePicker.OnDateChangedListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
GlobalVar globalvar = (GlobalVar)GlobalVar.getAppContex();
String difdays = globalvar.get_diffday();
int adddate=0;
String logadd = String.valueOf(adddate);
Log.e("Logadd",logadd);
if(difdays.equals("2")){
adddate = 2;
logadd = String.valueOf(adddate);
Log.e("Logadd2",logadd);
}else {
adddate = 1;
logadd = String.valueOf(adddate);
Log.e("Logadd1",logadd);
}
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH)+adddate;
DatePickerDialog dpd = new DatePickerDialog(getActivity(), android.R.style.Theme_Holo_Light_Dialog, this, year, month, day+adddate);
//dpd.setInverseBackgroundForced(false);
dpd.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dpd.getDatePicker().setMinDate(System.currentTimeMillis() - 1000 );
dpd.setTitle("Select Day"); // Uncomment this line to activate it
// Create a new instance of DatePickerDialog and return it
return dpd;
}
@Override
public void onDateChanged(DatePicker datePicker, int year, int month, int dayOfMonth) {
Log.d("Date", "Year=" + year + " Month=" + (month + 1) + " day=" + dayOfMonth);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
GlobalVar globalvar = (GlobalVar)GlobalVar.getAppContex();
StringBuilder current_date = new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" ");
SimpleDateFormat dateFormat = new SimpleDateFormat("M-dd-yyyy", Locale.getDefault());
Date mydate = null;
try{
mydate = dateFormat.parse(current_date.toString());
}catch(ParseException e){
e.printStackTrace();
}
SimpleDateFormat custome_date = new SimpleDateFormat("MMMM' 'dd', 'yyyy", Locale.getDefault());
String final_date = custome_date.format(mydate);
globalvar.setDate(final_date);
date.setText(final_date);
ProductBuyActivity product = new ProductBuyActivity();
product.compareDate(final_date);
// product.differenDate(final_date,"0");
}
}
public void enabled_button(){
btn_lunch.setBackgroundResource(R.drawable.lunch_active);
btn_lunch.setEnabled(true);
btn_dinner.setBackgroundResource(R.drawable.dinner_active);
btn_dinner.setEnabled(true);
// Toast.makeText(getBaseContext(), "date2 is Greater than my date1", Toast.LENGTH_LONG).show();
}
public void disabled_button(){
btn_lunch.setBackgroundResource(R.drawable.lunch_inactive);
btn_lunch.setEnabled(false);
btn_dinner.setBackgroundResource(R.drawable.dinner_inactive);
btn_dinner.setEnabled(false);
// Toast.makeText(getBaseContext(), "date2 is Greater than my date1", Toast.LENGTH_LONG).show();
}
public void compareDate(String final_date) {
try{
Context context;
SimpleDateFormat formatter = new SimpleDateFormat("MMMM' 'dd', 'yyyy");
Date date1 = formatter.parse(final_date.toString());
Log.e("Taggal Selected:",date1.toString());
String str2 = "March 10, 2017";
Date date2 = formatter.parse(str2);
if (date1.compareTo(date2)<0)
{
System.out.print("Date2 is Greater than mydate1");
date.setText("Tanggal 2 lebih besar dari tanggal 1");
//// btn_lunch.setBackgroundResource(R.drawable.lunch_inactive);
// btn_lunch.setEnabled(false);
//// btn_dinner.setBackgroundResource(R.drawable.dinner_inactive);
// btn_dinner.setEnabled(false);
enabled_button();
// Toast.makeText(getBaseContext(), "date2 is Greater than my date1", Toast.LENGTH_LONG).show();
}
else if(date1.compareTo(date2)==0){
// Toast.makeText(getBaseContext(), "Same Date", Toast.LENGTH_SHORT).show();
System.out.print("Same Date");
date.setText("Tanggal 2 sama 1");
}
else{
// disabled_button();
System.out.print("Date1 is Greater than mydate2");
date.setText("Tanggal 1 lebih besar dari tanggal 2");
}
}catch (ParseException e1){
e1.printStackTrace();
}
}
public void request_token() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, getResources().getString(R.string.API) + "oauth/token",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("respon token", response);
//Toast.makeText(getBaseContext(), response, Toast.LENGTH_LONG).show();Toast.makeText(getBaseContext(), response, Toast.LENGTH_LONG).show();
//String token = "";
try {
JSONObject return_val = new JSONObject(response);
token = return_val.getString("access_token");
} catch (JSONException e) {
e.printStackTrace();
//Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
SharedPreferences.Editor editor = getSharedPreferences(getResources().getString(R.string.shared), MODE_PRIVATE).edit();
editor.putString("token", token);
editor.commit();
request_validation();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProductBuyActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put("grant_type", getResources().getString(R.string.grant_type));
map.put("username", getResources().getString(R.string.username));
map.put("password", getResources().getString(R.string.password));
map.put("client_id", getResources().getString(R.string.client_id));
map.put("client_secret", getResources().getString(R.string.client_secret));
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(15000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(stringRequest);
}
private void go_back(){
this.finish();
}
private void showPDialog() {
pDialog = new ProgressDialog(ProductBuyActivity.this, R.style.MyTheme);
//pDialog.setTitle("Loading... Please Wait");
pDialog.setCancelable(false);
pDialog.setProgressStyle(android.R.style.Widget_Material_ProgressBar_Large);
pDialog.show();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
@Override
public void onBackPressed() {
go_back();
}
}
答案 0 :(得分:0)
使用以下内容来改变并实现目标..
public static void differenDate(String startDate, String endDate) {
Log.d("S D", "---> S D = " + startDate);
Log.d("E D", "---> E D = " + endDate);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss.sss");
Date sDate = null;
Date eDate = null;
try {
sDate = format.parse(startDate);
eDate = format.parse(endDate);
} catch (ParseException e) {
e.printStackTrace();
}
// final int MILLI_TO_HOUR = 1000 * 60 * 60;
// int diff = (int) ( (eDate.getTime() - sDate.getTime()) / MILLI_TO_HOUR );
System.out.println("DIFF = " + (eDate.getTime() - sDate.getTime()));
int calcDiff = (int) (eDate.getTime() - sDate.getTime());
}
答案 1 :(得分:0)
ProductBuyActivity product = new ProductBuyActivity();
您无需任何意图即可实例化您的活动。因此,onCreate
将不被调用。
这会让您的compareDate
方法因尝试使用product
btn_lunch
和btn_dinner
而未被初始化而感到困惑 - 因此,null
1}}
compareDate()
是一个公共方法,你可以简单地调用你可以尝试使用compareDate(final_date);
ProductBuyActivity.this.compareDate(final_date);
无需实例化新的活动项目。
修改强>
如果无法完全重构您的代码,那么您需要为DatePickerDialog
设置一个Listener回调。
保持DatePickerDialog
静态。
不要在您的片段上实现OnDateSetListener
接口。
相反,请在活动
public static class DatePickerFragment extends DialogFragment implements DatePicker.OnDateChangedListener
public class ProductBuyActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener
将您的onDataSet
移至活动,覆盖界面
public class ProductBuyActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener{
.....
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
GlobalVar globalvar = (GlobalVar)GlobalVar.getAppContex();
StringBuilder current_date = new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" ");
SimpleDateFormat dateFormat = new SimpleDateFormat("M-dd-yyyy", Locale.getDefault());
Date mydate = null;
try{
mydate = dateFormat.parse(current_date.toString());
}catch(ParseException e){
e.printStackTrace();
}
SimpleDateFormat custome_date = new SimpleDateFormat("MMMM' 'dd', 'yyyy", Locale.getDefault());
String final_date = custome_date.format(mydate);
globalvar.setDate(final_date);
date.setText(final_date);
//ProductBuyActivity product = new ProductBuyActivity();
//product.compareDate(final_date);
compareDate(final_date);
}
}
编辑2 :
更改DatePickerDialog
实例化:
DatePickerDialog dpd = new DatePickerDialog(getActivity(), android.R.style.Theme_Holo_Light_Dialog, (ProductBuyActivity)getActivity(), year, month, day+adddate);