Android application, Got error "java.lang.NullPointerException: println needs a message" - java

i have trouble with my app please i can't fix it. I know the problem at the price = getIntent().getIntExtra("price", -1); line but I don't know how to fix it. i have asked my friend but he sent me here. Please help me this is for my coursework.
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_detail);
init();
sqLiteHelper = new SQLiteHelper(this, "DrinDB.sqlite", null, 1);
sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS CART(ID INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, " +
"quantity INTEGER, price INTEGER)");
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (item < 1) {
Toast.makeText(DrinkDetailActivity.this, "Maaf Pesanan Minimal 1 cup", Toast.LENGTH_SHORT).show();
return;
}
try {
Log.i("TXT PRICE", txtName.getText().toString());
sqLiteHelper.insertData(txtName.getText().toString().trim(),
txtQuantity.getText().toString().trim(),
txtPrice.getText().toString().trim());
Toast.makeText(getApplicationContext(), "Masuk Keranjang!", Toast.LENGTH_SHORT).show();
txtQuantity.setText("0");
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(DrinkDetailActivity.this, CartListActivity.class);
startActivity(intent);
}
});
String name = getIntent().getStringExtra("name");
String type = getIntent().getStringExtra("type");
int image;
image = getIntent().getIntExtra("image", -1);
price = getIntent().getIntExtra("price", -1);
Log.e("SECOND ACTIVITY", name);
TextView nameTV = (TextView) findViewById(R.id.drink_name_text_view);
nameTV.setText(name);
TextView typeTV = (TextView) findViewById(R.id.type);
typeTV.setText(type);
ImageView imageV = (ImageView) findViewById(R.id.drink_image);
imageV.setImageResource(image);
imageV.setVisibility(View.VISIBLE);
TextView priceTV = (TextView) findViewById(R.id.harga_detail_text_view);
priceTV.setText(Integer.toString(price));
sumTextView = (TextView) findViewById(R.id.sum_text_view);
priceTotalTextView =(TextView) findViewById(R.id.harga_total_text_view);
Button incrementBtn = (Button) findViewById(R.id.increment_btn);
incrementBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
increment();
}
});
Button decrementBtn = (Button) findViewById(R.id.decrement_btn);
decrementBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
decrement();
}
});
}
private void init(){
txtName = findViewById(R.id.drink_name_text_view);
txtQuantity = findViewById(R.id.sum_text_view);
txtPrice = findViewById(R.id.harga_total_text_view);
btnAdd = findViewById(R.id.pesan_btn);
btnCart = findViewById(R.id.cart_btn);
}
private void increment(){
item++;
sumTextView.setText(Integer.toString(item));
priceTotalTextView.setText(Integer.toString(sumOfProduct(price)));
}
private void decrement(){
if(item<1){
Toast.makeText(this, "maaf Anda tidak dapat memesan kurang dari 1", Toast.LENGTH_SHORT).show();
return;
}
item =item-1;
sumTextView.setText(Integer.toString(item));
priceTotalTextView.setText(Integer.toString(sumOfProduct(price)));
}
private int sumOfProduct(int price){
return item * price;
}
}
`
and the error message is here [ at com.dicoding.picodiploma.kedaikopi.Models.DrinkDetailActivity.onCreate(DrinkDetailActivity.java:69)]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2760)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2821)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1541)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:181)
at android.app.ActivityThread.main(ActivityThread.java:6295)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:793)
Caused by: java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.e(Log.java:236)
at com.dicoding.picodiploma.kedaikopi.Models.DrinkDetailActivity.onCreate(DrinkDetailActivity.java:69)
at android.app.Activity.performCreate(Activity.java:6834)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1125)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2713)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2821) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1541) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:181) 
at android.app.ActivityThread.main(ActivityThread.java:6295) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:793) 

When using Intent.putExtra, you need to specify a name (first argument) and a value (second argument). The name is always a String and MUST have the package name as prefix.
From the documentation:
The name must include a package prefix, for example the app com.android.contacts would use names like "com.android.contacts.ShowAll".
In your example, when you create the Intent to start an Activity, use intent.putExtra(getPackageName() + ".name", "my name"). And when you want to extract the extra, use String name = getIntent().getStringExtra(getPackageName() + ".name").

Related

Radio button returns wrong value in Android

I have a form where a person can enter details about a friend (name, age, gender, address). This friend is displayed in a list view and when a friend from the list is clicked on they have the choice to edit that record.
I can successfully update every detail about a friend except for the gender.
For example:
List view:
1) James Bond, 20, Male, Sydney NSW
Then I click edit and change it to
James smith, 21, Female, Canberra NSW
and then back in my list view it will show:
1) James smith, 21, Male, Canberra NSW
Notice how the gender doesn't change?
I can figure out why this is happening as I use the same logic to change the name and age as i did to change the gender
Here is the relevant code:
ViewFriend.java ( this class displays the list view and has the edit option)
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
String text = listView.getItemAtPosition(position).toString();
final int ID = Integer.parseInt(String.valueOf(text.charAt(0)));
AlertDialog.Builder builder = new AlertDialog.Builder(viewFriends.this);
builder.setTitle("Notice");
builder.setMessage("Please select to to edit, delete a friend or cancel");
// add the buttons
builder.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), editOrDelete.class);
ArrayList<String> result1 = mydb.retrieveRow(ID);
name = result1.get(1);
age = result1.get(2);
gender = result1.get(3);
address = result1.get(4);
code = result1.get(0);
intent.putExtra("code", code);
intent.putExtra("name", name);
intent.putExtra("age", age);
intent.putExtra("gender", gender);
intent.putExtra("address", address);
startActivity(intent);
}
});
builder.setNeutralButton(" Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mydb.deleteTitle(ID);
finish();
Intent intent = new Intent(getApplicationContext(),viewFriends.class);
startActivity(intent);
}
});
builder.setNegativeButton("Cancel", null);
AlertDialog dialog = builder.create();
dialog.show();
}
});
The code above retrieves the details from the database and passes it to the intent. I have printed the contents of each variable (name, age, gender, address) and they print out correctly.
editFriend.java ( this class pre fills the form with the data passed through the intent that displays correctly)
public class editFriend extends AppCompatActivity {
private Intent intent;
private RadioGroup rg;
private Button update;
private RadioButton rb;
private String newName,newAddress,newGender;
private int newAge;
EditText ed, ed1;
public String name,address,gender,age,code;
private int selectedID,ages,codes;
NumberPicker numberPicker;
private databaseManager4 myDataBase;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_editordeletefriend);
intent= getIntent();
myDataBase = new databaseManager4(this);
rg = (RadioGroup)findViewById(R.id.radioGroup_update);
selectedID = rg.getCheckedRadioButtonId();
rb = (RadioButton) findViewById(selectedID);
ed = (EditText)findViewById(R.id.fullName_update);
numberPicker = (NumberPicker)findViewById(R.id.resultAge_update);
numberPicker.setMinValue(6);
numberPicker.setMaxValue(110);
numberPicker.setWrapSelectorWheel(false);
update = (Button)findViewById(R.id.update_button);
ed1 = (EditText)findViewById(R.id.address_update);
name = intent.getStringExtra("name");
age = intent.getStringExtra("age");
gender = intent.getStringExtra("gender");
address = intent.getStringExtra("address");
code = intent.getStringExtra("code");
codes = Integer.parseInt(code);
displayForm();
newName = ed.getText().toString();
newAge = numberPicker.getValue();
newGender = rb.getText().toString();
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = rg.getCheckedRadioButtonId();
rb = (RadioButton) findViewById(id);
if (myDataBase.updateRow(codes,newName,newAge,newGender,ed1.getText().toString())){
Toast.makeText(getApplicationContext(),"successfully updated the friend "
+ed.getText().toString(),Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(),"Could not update the friend "
+ed.getText().toString(),Toast.LENGTH_SHORT).show();
}
intent = new Intent(getApplicationContext(),viewFriends.class);
startActivity(intent);
}
});
}
public void displayForm(){
ed.setText(name);
ed1.setText(address);
if (gender.equals("Male")){
rb = (RadioButton)findViewById(R.id.resultGenderMale_update);
}
else if (gender.equals("Female"))
{
rb = (RadioButton)findViewById(R.id.resultGenderFemale_update);
}
rb.setChecked(true);
ages= Integer.parseInt(age);
numberPicker.setValue(ages);
}
public void clear(){
ed.setText("");
ed1.setText("");
}
}
This is where the issue lies, even if the user clicks on Male it registers as female and i am unsure why.
Any ideas how i can fix this?
Your problem is that you set value of rb variable to a single radio button, predefined with previous gender value here
if (gender.equals("Male")){
rb = (RadioButton)findViewById(R.id.resultGenderMale_update);
}
else if (gender.equals("Female"))
{
rb = (RadioButton)findViewById(R.id.resultGenderFemale_update);
}
And you read value of the same button then. To fix that in you click listener for update button you need to read checked radio button id using getCheckedRadioButtonId on radio group (your rg variable).
upd:
this is how your Edit Friend activity code might look like
public class EditFriendActivity extends AppCompatActivity {
private RadioGroup mGenderRadioGroup;
private Button mUpdateButton;
private EditText mNameField;
private EditText mAddressField;
private NumberPicker mAgePicker;
private databaseManager4 mDatabaseManager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_editordeletefriend);
initUI();
mDatabaseManager = new databaseManager4(this);
}
private void initUI() {
Intent intent = getIntent();
mNameField = (EditText) findViewById(R.id.fullName_update);
mNameField.setText(intent.getStringExtra("name"));
mAddressField = (EditText) findViewById(R.id.address_update);
mAddressField.setText(intent.getStringExtra("address"));
mAgePicker = (NumberPicker) findViewById(R.id.resultAge_update);
mAgePicker.setMinValue(6);
mAgePicker.setMaxValue(110);
mAgePicker.setWrapSelectorWheel(false);
mAgePicker.setValue(Integer.parseInt(intent.getStringExtra("age")));
mUpdateButton = (Button) findViewById(R.id.update_button);
mUpdateButton.setOnClickListener(updateClickListener);
mGenderRadioGroup = (RadioGroup) findViewById(R.id.radioGroup_update);
RadioButton targetRadioButton = null;
switch (Gender.fromString(intent.getStringExtra("gender"))) {
case MALE:
targetRadioButton = (RadioButton) findViewById(R.id.resultGenderMale_update);
break;
case FEMALE:
targetRadioButton = (RadioButton) findViewById(R.id.resultGenderFemale_update);
break;
}
if (targetRadioButton != null) {
targetRadioButton.setChecked(true);
}
}
public void clear() {
mNameField.setText("");
mAddressField.setText("");
}
private Gender getSelectedGender() {
int checkedButtonId = mGenderRadioGroup.getCheckedRadioButtonId();
switch (checkedButtonId) {
case R.id.resultGenderMale_update:
return Gender.MALE;
case R.id.resultGenderFemale_update:
return Gender.FEMALE;
}
return Gender.UNDEFINED;
}
private View.OnClickListener updateClickListener =
new View.OnClickListener() {
#Override
public void onClick(View v) {
Gender newGender = getSelectedGender();
int code = Integer.parseInt(getIntent().getStringExtra("code"));
System.out.println("gender is" + newGender.stringValue);
if (mDatabaseManager.updateRow(
code,
mNameField.getText().toString(),
mAgePicker.getValue(),
newGender.stringValue,
mAddressField.getText().toString())) {
Toast.makeText(
getApplicationContext(),
"successfully updated the friend " + ed.getText().toString(),
Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(
getApplicationContext(),
"Could not update the friend " + ed.getText().toString(),
Toast.LENGTH_SHORT)
.show();
}
Intent viewFriendsIntent = new Intent(getApplicationContext(), viewFriends.class);
startActivity(viewFriendsIntent);
finish();
}
};
private enum Gender {
UNDEFINED("undefined"),
MALE("Male"),
FEMALE("Female");
private #Nullable String stringValue;
Gender(#Nullable String stringValue) {
this.stringValue = stringValue;
}
public static Gender fromString(#Nullable String value) {
if (value != null) {
for (Gender gender : Gender.values()) {
if (value.equals(gender.stringValue)) {
return gender;
}
}
}
return UNDEFINED;
}
}
}

Save Button State (Enable and Disable)

I am making the application in android studio, in my application i add the feature, if the user click on button second time, then the button is disable and save the state of button in sharedprefernce and if the user closed the app and again open the app then the save button state are shown(if the button is disabled then the disable button is show, else shows enable state ). I put many codes of sharedprefences in my code, but every time the null object reference occurs. My code is given below and I put the shared preferences code on this button but how?
java:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counrClick = counrClick + 1;
if (counrClick == 1) {
downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse("Url");
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle("" + "" + "");
request.setDescription("Downloading " + "" + "");
request.setVisibleInDownloadsUi(true);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/" + "filename");
refid = downloadManager.enqueue(request);
Log.e("OUT", "" + refid);
if (counrClick == 2) {
button.setEnabled(false);
}
}
}
});
Please refer the code below. and please remember you can use preference name ("MY_PREF") and key name ("DOWNLOAD_BUTTON_STATUS") to alter preference anywhere else in your application. You can even create a separate class for control all preferences in your application.
private SharedPreferences sharedPreferences;
private Button btn_download_one, btn_download_two, btn_download_three, btn_download_four;
private final String DOWNLOAD_BUTTON_STATUS_KEY_ONE = "DOWNLOAD_BUTTON_STATUS_ONE";
private final String DOWNLOAD_BUTTON_STATUS_KEY_TWO = "DOWNLOAD_BUTTON_STATUS_TWO";
private final String DOWNLOAD_BUTTON_STATUS_KEY_THREE = "DOWNLOAD_BUTTON_STATUS_THREE";
private final String DOWNLOAD_BUTTON_STATUS_KEY_FOUR = "DOWNLOAD_BUTTON_STATUS_FOUR";
private int clickCountOne = 0, clickCountTwo = 0, clickCountThree = 0, clickCountFour = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_download_one = findViewById(R.id.button1);
btn_download_two = findViewById(R.id.button2);
btn_download_three = findViewById(R.id.button3);
btn_download_four = findViewById(R.id.button4);
sharedPreferences = getSharedPreferences("MY_PREF", 0);
btn_download_one.setEnabled(getDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_ONE));
btn_download_two.setEnabled(getDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_TWO));
btn_download_three.setEnabled(getDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_THREE));
btn_download_four.setEnabled(getDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_FOUR));
btn_download_one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//... some code
clickCountOne++;
if (clickCountOne == 2)
changeDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_ONE, false);
}
});
btn_download_two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//... some code
clickCountTwo++;
if (clickCountTwo == 2)
changeDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_TWO, false);
}
});
btn_download_three.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//... some code
clickCountThree++;
if (clickCountThree == 2)
changeDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_THREE, false);
}
});
btn_download_four.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//... some code
clickCountFour++;
if (clickCountFour == 2)
changeDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_FOUR, false);
}
});
}
private void changeDownloadButtonStatusPref(String key, boolean status) {
sharedPreferences.edit().putBoolean(key, status).apply();
switch (key) {
case DOWNLOAD_BUTTON_STATUS_KEY_ONE:
btn_download_one.setEnabled(status);
clickCountOne = 0;
break;
case DOWNLOAD_BUTTON_STATUS_KEY_TWO:
btn_download_two.setEnabled(status);
clickCountTwo = 0;
break;
case DOWNLOAD_BUTTON_STATUS_KEY_THREE:
btn_download_three.setEnabled(status);
clickCountThree = 0;
break;
case DOWNLOAD_BUTTON_STATUS_KEY_FOUR:
btn_download_four.setEnabled(status);
clickCountFour = 0;
break;
}
}
private boolean getDownloadButtonStatusPref(String key) {
return sharedPreferences.getBoolean(key, true);
}
//Add this code on button click
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putString("enabled", "").apply();
//Add this code in OnCreate/OncreateView Method
String statusLocked1 = prefs.getString("enabled","");
if(statusLocked1.equals("enabled")){
//enable the button
}else{
//disbale the button
}
Try this it will disable button next time you run your activity if it was previously clicked twice;
Button button;
SharedPreferences preferences;
boolean firstclick = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
// SharePrefs
preferences = getSharedPreferences("yourprefsname", 0);
firstclick = preferences.getBoolean("countclick", false);
button = findViewById(R.id.yourbutton);
//disables if it is clicked twice
if (!firstclick){
button.setEnabled(false);
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (firstclick) {
downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse("Url");
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle("" + "" + "");
request.setDescription("Downloading " + "" + "");
request.setVisibleInDownloadsUi(true);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/" + "filename");
refid = downloadManager.enqueue(request);
Log.e("OUT", "" + refid);
else{
//edit prefs
preferences.edit().putBoolean("countclick",firstclick).apply();
button.setEnabled(false);
}
}
}
});
}

Why the id is changing every time on the same phone ? Firebase database

enter image description hereFirst of all i want to say that my english isn't very good but i hope this is not a problem (i hope). So I wrote a code that "should" get user id from the user of my app but every time
firebase get other id on the same phone can someone help me with this problem ?
If you need more info, please write it in comments . Thank you in advance. Here my code .
EditText editTextName;
Button buttonAdd;
Spinner spinnerGenres;
DatabaseReference databaseArtists;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_cent);
databaseArtists = FirebaseDatabase.getInstance().getReference("prousers");
editTextName = (EditText) findViewById(R.id.editTextName);
buttonAdd = (Button) findViewById(R.id.buttonAddArtist);
spinnerGenres = (Spinner) findViewById(R.id.spinnerGenres);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addArtist();
}
});
}
private void addArtist(){
String name = editTextName.getText().toString().trim();
String genre = spinnerGenres.getSelectedItem().toString();
if (!TextUtils.isEmpty(name)){
String id = databaseArtists.push().getKey();
Artist artist = new Artist(id, name, genre);
databaseArtists.child(id).setValue(artist);
Toast.makeText(this, "You are a pro user :D", Toast.LENGTH_LONG).show();
finish();
System.exit(0);
}else{
Toast.makeText(this, "Something's wrong", Toast.LENGTH_LONG).show();
}
}
}
and this one too
public Artist(){
}
public Artist(String artistId, String artistName, String artistGenre) {
this.artistId = artistId;
this.artistName = artistName;
this.artistGenre = artistGenre;
}
public String getArtistId() {
return artistId;
}
public String getArtistName() {
return artistName;
}
public String getArtistGenre() {
return artistGenre;
}
}

Activity crashes when closed via an AlertDialog and re-opened later

Everything works just as expected until I exit the activity using the button of the AlertDialog and re-enter the same dialog through the main menu.
Here's how I coded the AlertDialog:
AlertDialog.Builder builder = new AlertDialog.Builder(NewCustomerInfoActivity.this);
if (result.equals("{\"success\":true}")){
builder.setMessage("Yeni müşteri başarıyla kaydedildi.").setTitle("Kayıt Başarılı");
builder.setPositiveButton("Ana ekrana dön", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent backToMainActivityIntent = new Intent(NewCustomerInfoActivity.this, MainActivity.class);
dialog.dismiss();
startActivity(backToMainActivityIntent);
}
});
} else {
builder.setMessage("Yeni müşteri kaydedilemedi.").setTitle("Kayıt Başarısız");
builder.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
}
AlertDialog dialog = builder.create();
dialog.show();
Everything works fine if I remove the code above.
The whole activity if it helps:
public class NewCustomerInfoActivity extends AppCompatActivity {
String jCities;
ArrayList<City> cities;
ArrayList<String> cityStrings;
ArrayList<String> townStrings;
RadioButton personalRadioButton;
RadioButton corporateRadioButton;
Spinner citySpinner;
Spinner townSpinner;
String url;
int isPersComp = 1;
String cityString = "Adana";
int cityNo = 1;
String townString = "Aladağ";
int townNo = 1;
JSONObject json;
String deviceId;
User user;
String result;
Toast toast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_customer_info);
deviceId = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
user = (User) getIntent().getSerializableExtra("user");
url = getResources().getString(R.string.service_call_url) + "newCustomer/" + deviceId + "/" + user.getSecureSessionId() + "/";
// Kayıtlı şehir ve ilçeler okunur.
SharedPreferences prefs = getSharedPreferences("cities", MODE_PRIVATE);
jCities = prefs.getString("jCities", null);
if (!(jCities.isEmpty() || jCities == null)){
WebRequest webRequest = new WebRequest();
cities = webRequest.parseCities(jCities);
cityStrings = new ArrayList<String>();
for (City city : cities){
if (!cityStrings.contains(city.getCityName())){
cityStrings.add(city.getCityName());
}
}
}
// Tüzel - Şahıs radio butonlarının kendilerine dokunulması durumunda tepkileri belirlenir.
personalRadioButton = (RadioButton) findViewById(R.id.personalRadioButton);
corporateRadioButton = (RadioButton) findViewById(R.id.corporateRadioButton);
isPersComp = 1;
View.OnClickListener optionOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView taxOrIdNoTitleTextView = (TextView) findViewById(R.id.taxOrIdNoTitleTextView);
if (personalRadioButton.isChecked()){
taxOrIdNoTitleTextView.setText("TC Kimlik No:");
isPersComp = 1;
}
if (corporateRadioButton.isChecked()){
taxOrIdNoTitleTextView.setText("Vergi No:");
isPersComp = 0;
}
}
};
personalRadioButton.setOnClickListener(optionOnClickListener);
corporateRadioButton.setOnClickListener(optionOnClickListener);
// İl seçimi için spinner doldurulur.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, cityStrings);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
final Spinner citySpinner = (Spinner) findViewById(R.id.citySpinner);
citySpinner.setAdapter(adapter);
citySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
cityString = citySpinner.getSelectedItem().toString();
cityNo = 1 + citySpinner.getSelectedItemPosition();
resetTownSpinner(cityNo);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
// Şehir seçimi yapılınca çağırılan ve ilçe spinner'ını seçilen şehre göre dolduran fonksiyon.
public void resetTownSpinner(int cityCode){
townStrings = new ArrayList<String>();
for (City city : cities){
if (city.getCityCode() == cityCode){
townStrings.add(city.getTownName());
}
}
townSpinner = (Spinner) findViewById(R.id.townSpinner);
ArrayAdapter<String> townAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, townStrings);
townSpinner.setAdapter(townAdapter);
townSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
townString = townSpinner.getSelectedItem().toString();
townNo = 1 + townSpinner.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
// Kayıt butonuna basıldığında çağırılan fonksiyon.
public void saveNewCustomer (View view){
// JSON objesi oluşturulur.
json = new JSONObject();
try {
// JSON objesi kullanıcının girdiği değerlere göre doldurulur.
JSONObject jCustomer = new JSONObject();
jCustomer.put("LOGICALREF", 0);
jCustomer.put("CODE", "");
EditText definitionText = (EditText) findViewById(R.id.definitionText);
jCustomer.put("DEFINITION_", definitionText.getText().toString());
jCustomer.put("ISPERSCOMP", isPersComp);
EditText taxOrIdNoText = (EditText) findViewById(R.id.taxOrIdNoText);
if (isPersComp == 1){
jCustomer.put("TAXNR", "");
jCustomer.put("TCKNO", taxOrIdNoText.getText().toString());
} else {
jCustomer.put("TAXNR", taxOrIdNoText.getText().toString());
jCustomer.put("TCKNO", "");
}
EditText taxOfficeText = (EditText) findViewById(R.id.taxOfficeText);
String taxOfficeString = taxOfficeText.getText().toString();
if (taxOfficeString.isEmpty() || taxOfficeString == null){
jCustomer.put("TAXOFFICE", "TCKIMLIK");
} else {
jCustomer.put("TAXOFFICE", taxOfficeString);
}
EditText emailText = (EditText) findViewById(R.id.emailText);
jCustomer.put("EMAILADDR", emailText.getText().toString());
EditText address1Text = (EditText) findViewById(R.id.address1Text);
jCustomer.put("ADDR1", address1Text.getText().toString());
EditText address2Text = (EditText) findViewById(R.id.address2Text);
jCustomer.put("ADDR2", address2Text.getText().toString());
jCustomer.put("CITY", cityString);
jCustomer.put("CITYCODE", cityNo);
jCustomer.put("TOWN", townString);
jCustomer.put("TOWNCODE", townNo);
EditText inChargeText = (EditText) findViewById(R.id.inChargeText);
jCustomer.put("INCHARGE", inChargeText.getText().toString());
EditText nameText = (EditText) findViewById(R.id.nameText);
jCustomer.put("NAME", nameText.getText().toString());
EditText surnameText = (EditText) findViewById(R.id.surnameText);
jCustomer.put("SURNAME", surnameText.getText().toString());
EditText phoneNo1Text = (EditText) findViewById(R.id.phoneNo1Text);
jCustomer.put("TELNRS1", phoneNo1Text.getText().toString());
EditText phoneNo2Text = (EditText) findViewById(R.id.phoneNo2Text);
jCustomer.put("TELNRS2", phoneNo2Text.getText().toString());
json.put("data", jCustomer);
// JSON objesini server'a gönderen Thread başlatılır.
new postJSON().execute();
} catch (Exception e){
e.printStackTrace();
}
}
// JSON objesini server'a gönderen Thread.
private class postJSON extends AsyncTask<Void, Void, Void>{
ProgressDialog progressDialog;
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(NewCustomerInfoActivity.this);
progressDialog.setMessage("Yeni müşteri kaydediliyor. Lütfen bekleyiniz.");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
WebRequest webRequest = new WebRequest();
// JSON objesi string'e dönüştürülür ve linkin sonuna eklenir.
url = url + json.toString();
result = webRequest.getJson(url, true);
return null;
}
protected void onPostExecute(Void requestResult) {
super.onPostExecute(requestResult);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
AlertDialog.Builder builder = new AlertDialog.Builder(NewCustomerInfoActivity.this);
// Server'dan dönen değer kontrol edilir.
if (result.equals("{\"success\":true}")){
builder.setMessage("Yeni müşteri başarıyla kaydedildi.").setTitle("Kayıt Başarılı");
builder.setPositiveButton("Ana ekrana dön", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent backToMainActivityIntent = new Intent(NewCustomerInfoActivity.this, MainActivity.class);
dialog.dismiss();
startActivity(backToMainActivityIntent);
}
});
} else {
builder.setMessage("Yeni müşteri kaydedilemedi.").setTitle("Kayıt Başarısız");
builder.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
}
AlertDialog dialog = builder.create();
dialog.show();
}
}
}
Again, no problems as long as the AlertDialog isn't used. No problem at all unless you use the AlertDialog and then try to get into the Activity once again, then the app stops working.
Logcat:
07-27 13:14:16.113 28618-28618/eof.concrete E/AndroidRuntime: FATAL EXCEPTION: main
Process: eof.concrete, PID: 28618
java.lang.RuntimeException: Unable to start activity ComponentInfo{eof.concrete/eof.concrete.newCustomer.NewCustomerInfoActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String eof.concrete.classes.User.getSecureSessionId()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String eof.concrete.classes.User.getSecureSessionId()' on a null object reference
at eof.concrete.newCustomer.NewCustomerInfoActivity.onCreate(NewCustomerInfoActivity.java:64)
at android.app.Activity.performCreate(Activity.java:6980)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6540) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
The problem is in this line and not in the AlertDialog
user = (User) getIntent().getSerializableExtra("user");
Prior to calling getIntent() you need to be sure that your Activity has been created by an intent.
When your activity is destroyed and re-created by the Android framework, the intent will be null.
If the user object in the intent is fundamental to the Activity functionalities, you could finish it.
Intent intent = getIntent();
if (intent != null){
user = (User) intent.getSerializableExtra("user");
if (user == null){
//handle null user
}
} else {
//here you can call finish() if the user is fundamental to your Activity
//or you must handle a possible nullable `User` object in the following code
finish();
return;
}
And in your AlertDialog, if you want to simply go back to the previous Activity you can replace this code
Intent backToMainActivityIntent = new Intent(NewCustomerInfoActivity.this,
MainActivity.class);
dialog.dismiss();
startActivity(backToMainActivityIntent);
with this
dialog.dismiss();
finish();

How to set default value to 0 in edittext when nothing is inputted?

I have an app here which adds the number. I have 4 edittexts here. What I want to happen is that when i entered none in one of the edittexts, it will assume that I entered 0. How can it be done? Here is my code:
public class Order extends Activity {
Button GoBackHome;
private Button button1;
private EditText txtbox1,txtbox2,txtbox3,txtbox4;
private TextView tv;
Button PayNow;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order);
GoBackHome = (Button) findViewById(R.id.gohomebutton);
PayNow = (Button) findViewById(R.id.button2);
txtbox1= (EditText) findViewById(R.id.editText1);
button1 = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.editText5);
txtbox2= (EditText) findViewById(R.id.editText2);
txtbox3= (EditText) findViewById(R.id.editText3);
txtbox4= (EditText) findViewById(R.id.editText4);
button1.setOnClickListener(new clicker());
GoBackHome.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent i = new Intent(Order.this, MainActivity.class);
startActivity(i);
}
});
PayNow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent i = new Intent(Order.this, Payment.class);
startActivity(i);
}
});
}
class clicker implements Button.OnClickListener
{
public void onClick(View v)
{
String a,b,c,d;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
c = txtbox3.getText().toString();
d = txtbox4.getText().toString();
vis = Integer.parseInt(a)*2+Integer.parseInt(b)*3+Integer.parseInt(c)*4+Integer.parseInt(d)*5;
tv.setText(vis.toString());
}
}
}
You can do as Tushar said or you can initialize the value in the XML. Something like
<EditText
android:name="#+id/editText1"
android:text="0"/>
FYI you might also find it cleaner to handle your button clicks on xml like:
<Button
android:name="#+id/btn1"
android:onClick="handleClicks"/>
and then in java you'd have a public void method:
public void handleClicks(View clickedView){
if(clickedView.getId() == btn1.getId(){
...
} else if (...){}
}
initialize as :
txtbox1.setText("0");
Check the EditText length when you get it
String value = null;
if(ed.getText().length()){
value = textBox.getText().toString();
} else
value = 0+"";
You can set android:hint="0" in your XML file, then, in your code, you can check if it's empty (maybe using TextUtils.isEmpty()) and setting some variable to 0.
android:hint="0" will make a "0" appear in your EditTexts, but the "0" will disappear when anything is inputted.
Then you can change the onClick() to this:
class clicker implements Button.OnClickListener {
public void onClick(View v) {
String a,b,c,d;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
c = txtbox3.getText().toString();
d = txtbox4.getText().toString();
try {
vis = Integer.parseInt(a)*2+Integer.parseInt(b)*3+Integer.parseInt(c)*4+Integer.parseInt(d)*5;
tv.setText(vis.toString());
} catch (NumberFormatException e) {
vis = "0";
}
// Do something with "vis"
}
}
Or you can create a method to check a value, try to parse to an int or return a default value.
public int getInt(String edtValue, int defaultValue) {
int value = defaultValue;
if (edtValue != null) {
try {
value = Integer.parseInt(edtValue);
} catch (NumberFormatException e) {
value = defaultValue;
}
}
return value;
}
Then you change your call to
vis = this.getInt(a, 0) * 2 + this.getInt(b, 0) * 3 + this.getInt(c, 0) * 4 + this.getInt(d, 0) * 5;

Categories