Good day guys. I'm new to android and now using startActivityForResult in my program. In my app, I have two button and two textView. The two button used to open the dialog. How can I check which button was pressed onActivityResult so that the TextView can be setText accordingly to the button?
int a1 = 1;
int a2 = 2;
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialogRadio(a1);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialogRadio(a2);
}
});
public void AlertDialogRadio(final int k) { //parameter k is never used
final CharSequence[] ClaimsModel = {"Project", "Petrol", "Car Maintenance"
, "Medical", "Other"};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select a Claims");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), Project1.class);
startActivityForResult(intent, 0);
} else if (item == 1) {
Intent intent = new Intent(getActivity().getApplicationContext(), Petrol.class);
startActivityForResult(intent, 1);
} else if (item == 2) {
Intent intent = new Intent(getActivity().getApplicationContext(), CarMainten.class);
startActivityForResult(intent, 2);
} else if (item == 3) {
Intent intent = new Intent(getActivity().getApplicationContext(), Medical.class);
startActivityForResult(intent, 3);
} else if (item == 4) {
Intent intent = new Intent(getActivity().getApplicationContext(), Other.class);
startActivityForResult(intent, 4);
}
dialog.dismiss();
}
});
AlertDialog alert = alt_bld.create();
alert.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 1) { // if button1 was clicked
switch (requestCode) {
case 0:
String result = data.getStringExtra("text");
String b = data.getStringExtra("a");
c.setText(" " + b + "------" + "RM " + result);
Toast.makeText(getActivity(), "Not completed ", Toast.LENGTH_LONG).show();
break;
case 1:
String result1 = data.getStringExtra("text");
String b1 = data.getStringExtra("a");
c.setText(" " + b1 + "------" + "RM " + result1);
break;
case 2:
String result2 = data.getStringExtra("text");
String b2 = data.getStringExtra("a");
c.setText(" " + b2 + "------" + "RM " + result2);
break;
case 3:
String result3 = data.getStringExtra("text");
String b3 = data.getStringExtra("a");
c.setText(" " + b3 + "------" + "RM " + result3);
break;
case 4:
String result4 = data.getStringExtra("text");
String b4 = data.getStringExtra("a");
c.setText(" " + b4 + "------" + "RM " + result4);
break;
}
}
else if (resultCode == 2) { // if button2 was clicked
switch (requestCode) {
case 0:
String result = data.getStringExtra("text");
String b = data.getStringExtra("a");
d.setText(" " + b + "------" + "RM " + result);
break;
case 1:
String result1 = data.getStringExtra("text");
String b1 = data.getStringExtra("a");
d.setText(" " + b1 + "------" + "RM " + result1);
break;
case 2:
String result2 = data.getStringExtra("text");
String b2 = data.getStringExtra("a");
d.setText(" " + b2 + "------" + "RM " + result2);
break;
case 3:
String result3 = data.getStringExtra("text");
String b3 = data.getStringExtra("a");
d.setText(" " + b3 + "------" + "RM " + result3);
break;
case 4:
String result4 = data.getStringExtra("text");
String b4 = data.getStringExtra("a");
d.setText(" " + b4 + "------" + "RM " + result4);
break;
}
}
}
So my program should work like this:
If button1 was clicked....c.setText();
If button2 was clicked....d.setText();
But the program now is nothing display on the TextView. Did the error came from if (resultCode == 1) and else if (resultCode == 2) ?? Thanks a lot
Assume the use select Project1.class
Project1.class
public class Project1 extends AppCompatActivity {
private static String text;
private static String a;
private static EditText txt;
private int g;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
txt= (EditText)findViewById(R.id.editText36);
Button b=(Button)findViewById(R.id.button17);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a="Project";
text = txt.getText().toString();
returnIntent.putExtra("text", text);
returnIntent.putExtra("a",a);
// returnIntent.putExtra("k",getIntent().getExtras().getString("k"));
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
}
request_code is the calling function identity, from where it is requested, result_code is the called function identifier, also it specifies status of the called message as Intent.ACTIVITY_OK and so on.
You should avoid using the literal code here.
if (resultCode == 1)
much better to use the named constant --
if (resultCode == RESULT_OK) {
RESULT_OK is -1, so that might be your issue.
Once I set all my request codes the same. Didn't work.
Seems your request codes are different, I'm used to seeing them like this:
private static final int REQUEST_CODE_THIS = 0;
private static final int REQUEST_CODE_THAT = 1;
private static final int REQUEST_CODE_THE_OTHER = 1003;
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), Project1.class);
startActivityForResult(intent, REQUEST_CODE_THIS);
Check if changing the onActivityResult() like this might help.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_THIS) { // if button1 was clicked
switch (resultCode == RESULT_OK) {
case 0:
...
}
Related
I do not know why I can't add boolean insertData = dbHelper.addData(emailString, nameString,ageString, preferencesString,passwordString) where the addData keep showing error in the lines of code provided below. I wanted to add the if-else statement there is because I wanted it to make sure during the insert data process, a user has to fill in all the details in order to create an account, but not leaving blanks on any of the fields given for them to fill in. or I need to do it in another way? I'm still a newbie for android studio. Please help me.
private void getData() {
name = "" + Pname.getText().toString().trim();
age = "" + PAge.getText().toString().trim();
phone = "" + Pphone.getText().toString().trim();
preferenceselected = "" + Ppreferenceselected.getText().toString().trim();
String timeStamp = "" + System.currentTimeMillis();
long id = dbHelper.insertInfo(
"" + imageUri,
"" + name,
"" + age,
"" + phone,
"" + preferenceselected,
"" + timeStamp,
"" + timeStamp
);
String emailString = Pemail.getText().toString();
String nameString = Pname.getText().toString();
String ageString = PAge.getText().toString();
String preferencesString = Ppreferenceselected.getText().toString();
String passwordString = Ppassword.getText().toString();
boolean insertData = dbHelper.addData(emailString, nameString,ageString, preferencesString,passwordString);
if (insertData == true) {
Toast.makeText(MainActivity.this, "Account Created", Toast.LENGTH_LONG).show();
Intent goappsetting = new Intent(MainActivity.this,setting.class);
startActivity(goappsetting);
}else {
Toast.makeText(MainActivity.this, "Please do not leave any blanks or user exist", Toast.LENGTH_LONG).show();
}
Toast.makeText(this, "Account Created", Toast.LENGTH_SHORT).show();
}
this is my MainActivity.Java
public class MainActivity extends AppCompatActivity {
private DatabaseHelper dbHelper;
private ImageView pImageView;
private EditText Pemail, Pname, PAge, Pphone, Ppassword;
private TextView loginacclink, Ppreferenceselected;
Button createacc, preferencebtn;
ActionBar actionBar;
String[] categories;
boolean[] checkeditems;
ArrayList<Integer> mUserItems = new ArrayList<>();
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 101;
private static final int IMAGE_PICK_CAMERA_CODE = 102;
private static final int IMAGE_PICK_GALLERY_CODE = 103;
private String[] cameraPermissions;
private String[] storagePermissions;
private Uri imageUri;
private String name, age, phone;
private String preferenceselected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// this is the status bar
actionBar = getSupportActionBar();
actionBar.setTitle("Create Account");
// this is for the check list
categories = getResources().getStringArray(R.array.user_categories);
checkeditems = new boolean[categories.length];
// this is for the items in the xml file
pImageView = findViewById(R.id.personImage);
Pemail = findViewById(R.id.email);
Pname = findViewById(R.id.name);
PAge = findViewById(R.id.age);
Pphone = findViewById(R.id.phone);
Ppassword = findViewById(R.id.password);
createacc = findViewById(R.id.createacc);
preferencebtn = findViewById(R.id.preferencebtn);
loginacclink = findViewById(R.id.loginacclink);
Ppreferenceselected = (TextView) findViewById(R.id.preferenceselected);
dbHelper = new DatabaseHelper(this);
cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
pImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imagePickDialog();
}
});
preferencebtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view){
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
mBuilder.setTitle(R.string.dialog_title);
mBuilder.setMultiChoiceItems(categories, checkeditems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int position, boolean isChecked) {
if (isChecked) {
if (!mUserItems.contains(position)) {
mUserItems.add(position);
}
} else if (mUserItems.contains(position)) {
mUserItems.remove(position);
}
}
});
mBuilder.setCancelable(false);
mBuilder.setPositiveButton(R.string.ok_label, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
String item = "";
for (int i = 0; i < mUserItems.size(); i++) {
item = item + categories[mUserItems.get(i)];
if (i != mUserItems.size() - 1) {
item = item + ",";
}
}
Ppreferenceselected.setText(item);
}
});
mBuilder.setNegativeButton(R.string.dismiss_label, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
mBuilder.setNeutralButton(R.string.clear_all_label, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
for (int i = 0; i < checkeditems.length; i++) {
checkeditems[i] = false;
mUserItems.clear();
Ppreferenceselected.setText("");
}
}
});
AlertDialog mDialog = mBuilder.create();
mDialog.show();
}
});
loginacclink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, login.class);
startActivity(intent); }
});
createacc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// insert data into db
getData();
}
});
}
private void getData() {
name = "" + Pname.getText().toString().trim();
age = "" + PAge.getText().toString().trim();
phone = "" + Pphone.getText().toString().trim();
preferenceselected = "" + Ppreferenceselected.getText().toString().trim();
String timeStamp = "" + System.currentTimeMillis();
long id = dbHelper.insertInfo(
"" + imageUri,
"" + name,
"" + age,
"" + phone,
"" + preferenceselected,
"" + timeStamp,
"" + timeStamp
);
String emailString = Pemail.getText().toString();
String nameString = Pname.getText().toString();
String ageString = PAge.getText().toString();
String preferencesString = Ppreferenceselected.getText().toString();
String passwordString = Ppassword.getText().toString();
boolean insertData = dbHelper.addData(emailString, nameString,ageString, preferencesString,passwordString);
if (insertData == true) {
Toast.makeText(MainActivity.this, "Account Created", Toast.LENGTH_LONG).show();
Intent goappsetting = new Intent(MainActivity.this,setting.class);
startActivity(goappsetting);
}else {
Toast.makeText(MainActivity.this, "Please do not leave any blanks or user exist", Toast.LENGTH_LONG).show();
}
Toast.makeText(this, "Account Created", Toast.LENGTH_SHORT).show();
}
private void imagePickDialog() {
String[] options = {"Camera", "Gallery"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick Image From");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
if (!checkCameraPermission()) {
requestCameraPermission();
}
else {
pickFromCamera();
}
}
else if (which == 1) {
if (!checkStoragePermission()) {
requestStoragePermission();
}
else {
pickFromGallery();
}
}
}
});
builder.create().show();
}
private boolean checkCameraPermission() {
boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
private void requestCameraPermission() {
ActivityCompat.requestPermissions(this, cameraPermissions, CAMERA_REQUEST_CODE);
}
private void pickFromGallery() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_CODE);
}
private void pickFromCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Image title");
values.put(MediaStore.Images.Media.DESCRIPTION, "Image description");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
private boolean checkStoragePermission() {
boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result;
}
private void requestStoragePermission() {
ActivityCompat.requestPermissions(this, storagePermissions, STORAGE_REQUEST_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case CAMERA_REQUEST_CODE: {
if (grantResults.length>0) {
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean storageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && storageAccepted) {
pickFromCamera();
}
else {
Toast.makeText(this, "Camera permission required!", Toast.LENGTH_SHORT).show();
}
}
}
break;
case STORAGE_REQUEST_CODE:{
if (grantResults.length>0) {
boolean storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (storageAccepted) {
pickFromGallery();
}
else {
Toast.makeText(this, "Storage permission required!", Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PICK_GALLERY_CODE) {
CropImage.activity(data.getData())
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
else if (requestCode == IMAGE_PICK_CAMERA_CODE) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
imageUri = resultUri;
pImageView.setImageURI(resultUri);
}
else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
Toast.makeText(this, ""+error, Toast.LENGTH_SHORT).show();
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
This is my DatabaseHelper.Java
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(#Nullable Context context) {
super(context, constants.DB_NAME, null, constants.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(constants.CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + constants.TABLE_NAME);
onCreate(db);
}
public long insertInfo(String image, String name, String age, String phone, String preference, String addTimeStamp, String updateTimeStamp) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(constants.C_NAME, name);
values.put(constants.C_AGE, age);
values.put(constants.C_PHONE, phone);
values.put(constants.C_PREFERENCES, preference);
values.put(constants.C_IMAGE, image);
values.put(constants.C_Add_TIMESTAMP, addTimeStamp);
values.put(constants.C_UPDATED_TIMESTAMP, updateTimeStamp);
long id = db.insert(constants.TABLE_NAME, null, values);
db.close();
return id;
}
}
This is constance.Java
public class constants {
public static final String DB_NAME = "MMTA_DB";
public static final int DB_VERSION = 1;
public static final String TABLE_NAME = "USER_TABLE";
public static final String C_EMAIL = "EMAIL";
public static final String C_NAME = "NAME";
public static final String C_AGE = "AGE";
public static final String C_PHONE = "PHONE";
public static final String C_PASSWORD = "PASSWORD";
public static final String C_PREFERENCES = "PREFERENCES";
public static final String C_IMAGE = "IMAGE";
public static final String C_Add_TIMESTAMP = "TIMESTAMP";
public static final String C_UPDATED_TIMESTAMP = "UPDATED_TIMESTAMP";
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " ("
+ C_EMAIL + " TEXT PRIMARY KEY ,"
+ C_NAME + " TEXT,"
+ C_AGE + " TEXT,"
+ C_PHONE + " TEXT,"
+ C_PASSWORD + " TEXT,"
+ C_PREFERENCES + " TEXT,"
+ C_IMAGE + " TEXT,"
+ C_Add_TIMESTAMP + " TEXT,"
+ C_UPDATED_TIMESTAMP + " TEXT"
+ ");";
}
The method addData(String,String,String,String,String) is missing from DatabaseHelper class. Please add this method in that class.
Update the DatabaseHelper class.
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(#Nullable Context context) {
super(context, constants.DB_NAME, null, constants.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(constants.CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + constants.TABLE_NAME);
onCreate(db);
}
public long insertInfo(String image, String name, String age, String phone, String preference, String addTimeStamp, String updateTimeStamp) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(constants.C_NAME, name);
values.put(constants.C_AGE, age);
values.put(constants.C_PHONE, phone);
values.put(constants.C_PREFERENCES, preference);
values.put(constants.C_IMAGE, image);
values.put(constants.C_Add_TIMESTAMP, addTimeStamp);
values.put(constants.C_UPDATED_TIMESTAMP, updateTimeStamp);
long id = db.insert(constants.TABLE_NAME, null, values);
db.close();
return id;
}
//add the method
public boolean addData(String parameter1,String parameter2,String parameter3,String parameter4,String parameter5) {
// put here your logic
return false;
}
}
I am trying to build a quiz app, where admin will create questions in admin activity and these questions will be shown as quiz exam in another activity. While I try to fill up the form by clicking CREATE QUESTION button from admin activity my app is going back to previous activity(adminlogin activity)
Here is the code of AdminActivity:
public class AdminActivity extends AppCompatActivity {
Button btnCreateQuestion, btnReadQuestion, btnDeleteQuestion;
EditText editTextQuestion, editTextOption1, editTextOption2, editTextOption3, editTextOption4,
editTextAnswerNo,editTextChapterNo;
QuizDbHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
btnCreateQuestion = findViewById(R.id.btnCreateQuestion);
btnReadQuestion = findViewById(R.id.btnReadQuestions);
btnDeleteQuestion = findViewById(R.id.btnDeleteQuestions);
editTextQuestion = findViewById(R.id.editTextQuestion);
editTextOption1 = findViewById(R.id.editTextOption1);
editTextOption2 = findViewById(R.id.editTextOption2);
editTextOption3 = findViewById(R.id.editTextOption3);
editTextOption4 = findViewById(R.id.editTextOption4);
editTextAnswerNo = findViewById(R.id.editTextAnswerNo);
editTextChapterNo = findViewById(R.id.editTextChapterNo);
db = new QuizDbHelper(this);
btnCreateQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String question = editTextQuestion.getText().toString();
String option1 = editTextOption1.getText().toString();
String option2 = editTextOption2.getText().toString();
String option3 = editTextOption3.getText().toString();
String option4 = editTextOption4.getText().toString();
Integer answerNo = Integer.parseInt(editTextAnswerNo.getText().toString());
String chapterName = editTextAnswerNo.getText().toString();
if( question != "" && option1 != "" && option2 != "" && option3 != "" && option4 != "" && answerNo!= null && chapterName != ""){
Question q = new Question(question,option1,option2,option3,option4,answerNo,chapterName);
db.addQuestion(q);
Toast.makeText(AdminActivity.this,"Question Added", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(AdminActivity.this,"Please fill up", Toast.LENGTH_SHORT).show();
}
}
});
btnReadQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Question> allQuestions = db.getAllQuestions();
if(allQuestions.size()< 1){
Toast.makeText(AdminActivity.this,"No questions in the Database", Toast.LENGTH_SHORT).show();
}else {
StringBuffer buffer = new StringBuffer();
for (Question q: allQuestions) {
buffer.append("Question : " + q.getQuestion() + "\n" );
buffer.append("Option1: " + q.getOption1() + "\n");
buffer.append("Option2: " + q.getOption2() + "\n");
buffer.append("Option3: " + q.getOption3() + "\n");
buffer.append("Option4: " + q.getOption4() + "\n");
buffer.append("Answer No: " + q.getAnswerNo() + "\n");
buffer.append("Option4: " + q.getChapterName() + "\n\n");
}
AlertDialog.Builder builder = new AlertDialog.Builder(AdminActivity.this);
builder.setCancelable(true);
builder.setTitle("Questions");
builder.setMessage(buffer.toString());
builder.show();
}
}
});
btnDeleteQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}}
Any clue? Thank You in Advance.
Check in onCreate function of your Activity class, did you have initialize your EditText and Button.
Also, You have to make change in your condition as below:
if(!question.equalsIgnoreCase("") && !option1.equalsIgnoreCase("") && !option2.equalsIgnoreCase("") && !option3.equalsIgnoreCase("") && !option4.equalsIgnoreCase("") && answerNo != 0 && !chapterName.equalsIgnoreCase("")
Because, == tests for reference equality (whether they are the same object).
Whereas, equalsIgnoreCase() ignores the case while comparing two strings.
I am new to android studio and have created an app with a page that enables 2 spinners to be selected, a user enters a time and then an 'end time' is calculated. I am trying to add some validation to this page as when I click the 'VerifyButton' the app crashes as no fields have been selected. My intention is that when the user selects the 'VerifyButton' that an error message displays to ensure the spinner values have been filled in, meaning the app doesn't crash. I have tried a few methods within the onNothingSelected but it doesn't seem to work.. I wasn't sure if it needs to be in there or the VerifyButton? Thanks in advance!
Spinner Java
final ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(CreateLine.this,
R.layout.spinner_layout, getResources().getStringArray(R.array.LineTypes));
myAdapter.setDropDownViewResource(R.layout.spinner_layout);
spinner.setAdapter(myAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position2, long l) {
switch (position2) {
case 0:
quantity.setText("");
break;
case 1:
quantity.setVisibility(View.INVISIBLE);
timeadded = 10;
duration.setText(timeadded + " Hours");
spinner2.setVisibility(View.INVISIBLE);
break;
case 2:
quantity.setVisibility(View.INVISIBLE);
timeadded = 10;
duration.setText(timeadded + " Hours");
spinner2.setVisibility(View.INVISIBLE);
break;
case 3:
quantity.setVisibility(View.INVISIBLE);
timeadded = 10;
duration.setText(timeadded + " Hours");
spinner2.setVisibility(View.INVISIBLE);
break;
case 4:
quantity.setVisibility(View.VISIBLE);
duration.setText(timeadded + " Hours");
spinner2.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Select Package Type", Toast.LENGTH_SHORT).show();
break;
case 5:
quantity.setVisibility(View.VISIBLE);
duration.setText(timeadded + " Hours");
spinner2.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Select Package Type", Toast.LENGTH_SHORT).show();
break;
case 6:
quantity.setVisibility(View.VISIBLE);
duration.setText(timeadded + " Hours");
spinner2.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Select Package Type", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
ArrayAdapter<String> myAdapter2 = new ArrayAdapter<String>(CreateLine.this,
R.layout.spinner_layout, getResources().getStringArray(R.array.PackageTypes));
myAdapter2.setDropDownViewResource(R.layout.spinner_layout);
spinner2.setAdapter(myAdapter2);
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
switch (position) {
case 0:
quantity.setText("");
break;
case 1:
quantity.setText(PackageType20);
timeadded = 28;
duration.setText(timeadded + " Hours");
break;
case 2:
quantity.setText(PackageType30);
timeadded = 27;
duration.setText(timeadded + " Hours");
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
VerifyButton Java
VerifyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
spinnerSelection = String.valueOf(spinner.getSelectedItem());
spinnerSelection2 = String.valueOf(spinner2.getSelectedItem());
String q = quantity.getText().toString();
String d = duration.getText().toString();
DateTime datetime = new DateTime(yearNow, monthNow, dayNow, hourNow, minuteNow);
DateTimeFormatter fmt = DateTimeFormat.forPattern("EE dd MM yyyy" + "\n" + " h:mm a ");
String formattedtime = fmt.print(datetime);
CalculateButton.setText(formattedtime);
// Plus some hours, minutes, and seconds to the original DateTime.
DateTimeFormatter fmt2 = DateTimeFormat.forPattern("EE dd MM yyyy" + "\n" + " h:mm a ");
DateTime dateTime1 = datetime.plusHours(timeadded);
String endtimecalc = fmt2.print(dateTime1);
TextView endtime = findViewById(endtimetextView);
endtime.setVisibility(View.VISIBLE);
endtime.setText(endtimecalc);
if (spinnerSelection !=null) {
Toast.makeText(getApplicationContext(),"enter value",
Toast.LENGTH_LONG).show();
}
//INSERT DATA TO DATABASE
boolean isInserted = myDb.insertData(
spinnerSelection,
spinnerSelection2,
q,
d,
formattedtime,
endtimecalc);
if (isInserted == true)
Toast.makeText(CreateLine.this, "Data Inserted Successfully", Toast.LENGTH_LONG).show();
else
Toast.makeText(CreateLine.this, "This line is already Active!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), Dashboard.class);
startActivity(intent);
}
});
Replace all of your :
getApplicationContext()
with:
getContext()
and in following line instead of getApplicationContext():
Intent intent = new Intent(getApplicationContext(), Dashboard.class);
Use your class name as follows:
Intent intent = new Intent(YourClassName.this, Dashboard.class);
Class in which you are defining your verify button.
And in both of onNothingSelected methods set default value for spinner as:
ArrayList<String> list = getResources().getStringArray(R.array.LineTypes);
yourSpinner.setSelection(list[0]);
Also apply check instead of this:
if (spinnerSelection !=null) {
Toast.makeText(getApplicationContext(),"enter value",
Toast.LENGTH_LONG).show();
}
As:
if (spinnerSelection.getSelectedItem().toString().isEmpty() || spinnerSelection.getSelectedItem().toString() == "" )
{
Toast.makeText(getApplicationContext(),"enter value",
Toast.LENGTH_LONG).show();
}
After spinner.setAdapter(myAdapter) add;
spinner.setAdapter(myAdapter)
spinner.setSelection(-1);
then on verify button click:
if (spinner.getSelectedItemPosition() == -1 || spinner2.getSelectedItemPosition() == -1 ){
// showErrorMessage
}
else{
//do your work
}
Do the same for spinner2
The app has an order button when it's clicked the gmail app should be opened with subject and body filed desirably but the intent for it in my code is not working and the app shows a message that it is unfortunately stopping. I've tried many ways to implement this but i'm unable to do so.
package com.example.android.justjava;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import java.text.NumberFormat;
import static android.R.attr.value;
import static android.R.id.checkbox;
import static android.R.id.message;
/**
* This app displays an order form to order coffee.
*/
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
int topping_price = 0;
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
String variable1,variable2,variable3;
CheckBox cream = (CheckBox) findViewById(R.id.checkbox);
CheckBox choco = (CheckBox) findViewById(R.id.checkbox_choco);
boolean value1 = cream.isChecked();
boolean value2 = choco.isChecked();
if(value1 == true) {
variable1 = "Yes";
topping_price += 1;
}
else
variable1 = "No" ;
if(value2 == true) {
variable2 = "Yes";
topping_price += 2;
}
else
variable2 = "No" ;
EditText input_name = (EditText) findViewById(R.id.name);
variable3 = input_name.getText().toString();
if((quantity + count) == 0){
topping_price = 0;
variable1 = "No";
variable2 = "No";
}
String price_message = "Whipped cream topping: " + variable1 + "\nChocolate topping: " + variable2 +"\nName: " + variable3 +"\nQuantity: " + (quantity + count) +"\nTotal $" + (( quantity + count ) * 10 + topping_price ) + "\nThank You";
displayMessage(price_message);
topping_price = 0 ;
Intent sendIntent = new Intent(Intent.ACTION_SENDTO);
sendIntent.setType("*/*");
sendIntent.setData(Uri.parse("masquerade0097#gmail.com"));
sendIntent.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail");
sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "masquerade0097#gmail.com" });
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Just Java order for " + variable3);
sendIntent.putExtra(Intent.EXTRA_TEXT,"Whipped cream topping: " + variable1 + "\nChocolate topping: " + variable2 +"\nName: " + variable3 +"\nQuantity: " + (quantity + count) +"\nTotal $" + (( quantity + count ) * 10 + topping_price ) + "\nThank You");
// startActivity(sendIntent);
if (sendIntent.resolveActivity(getPackageManager()) != null) {
startActivity(sendIntent);
}
}
/**
* This method displays the given text on the screen.
*/
private void displayMessage(String message) {
TextView priceTextView = (TextView) findViewById(R.id.price_text_view);
priceTextView.setText(message);
}
int quantity = 1;
int count = 0;
public void increment(View view){
if((quantity + count) < 101)
count = count + 1;
display(quantity + count );
displayPrice( (quantity + count) * 10);
}
public void decrement(View view){
if((quantity + count) != 0)
count = count - 1;
display(quantity + count);
displayPrice((quantity + count) * 10);
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int number) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + number);
}
private void displayPrice(int number){
TextView priceTextView = (TextView) findViewById(R.id.price_text_view);
priceTextView.setText(NumberFormat.getCurrencyInstance().format(number));
}
}
You can try with this code. This will open chooser from where you can select gmail app.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_TEXT, "Text you want to share");
startActivity(Intent.createChooser(intent, "Send mail..."));
If you specifically want to open gmail app then use this
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("test#gmail.com"));
sendIntent.setClassName("com.google.android.gm","com.google.android.gm.ComposeActivityGmail");
sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "test#gmail.com" });
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Test");
sendIntent.putExtra(Intent.EXTRA_TEXT, "Test");
startActivity(sendIntent);
but this code may fail if the package name changes or if the package name does not exist.So better use this(along with intent chooser)
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", emailId, null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "");
emailIntent.putExtra(Intent.EXTRA_TEXT, "");
startActivity(Intent.createChooser(emailIntent, "Send email..."));
use intent.setType("message/rfc822") in the Intent
To open the Gmail App, use the following code:
Intent mailClient = new Intent(Intent.ACTION_VIEW);
mailClient.setClassName("com.google.android.gm", "com.google.android.gm.ConversationListActivity");
startActivity(mailClient);
To have the fields to, subject and body pre-filled, you can put extras in the intent like this:
mailClient.putExtra(Intent.EXTRA_EMAIL, new String[] { "hello#gmail.com" });
mailClient.putExtra(Intent.EXTRA_SUBJECT, "hello subject");
mailClient.putExtra(Intent.EXTRA_TEXT, "hello message");
I have a listView in Activity A as shown below. All the values and name were actually returned from Activity C to B then only A.
When the first list is clicked, it should display text Project and value 3 on editText B. But it displays Medical which was actually getting from the last list.
After I change the value from 3 to 43 and return to A, the name changed. What should I do so that the name will remain the same ?
Activity A
ArrayAdapter<String> adapter;
ArrayList<String> m_listItems = new ArrayList<String>();
int mClickedPosition;
adapter=new ArrayAdapter<String (getActivity(),R.layout.claims,R.id.textView1,m_listItems);
listV = (ListView) claims.findViewById(R.id.listView1);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() { // if list clicked
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
mClickedPosition = position;
if (name.equals("Project")) {
String temp[] = m_listItems.get(position).split("\\s\\s+");
result = temp[temp.length - 1].trim();
result = result.replace("RM","");
Intent intent = new Intent(Claims1.this.getActivity(), Project1.class);
intent.putExtra("bitmap", true); // image
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 0);
Log.e("RESULT", "Result= " + result);
}
else if(name.equals("Medical"))
{
String temp[] = m_listItems.get(position).split("\\s\\s+");
result = temp[temp.length - 1].trim();
result = result.replace("RM","");
Intent intent = new Intent(Claims1.this.getActivity(), Medical.class);
intent.putExtra("bitmap", true);
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 1);
}
}
});
return claims;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0: // for Project
result = data.getStringExtra("text"); //get from B
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:" + result);
Text = " " + name + " " + "RM" + result + "";
if (mClickedPosition == -1) { // if is icon button clicked
m_listItems.add(Text);
} else {
m_listItems.set(mClickedPosition, Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
case 1: // for Medical
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:" + result);
Text = " " + name + " " + "RM" + result + "";
// m_listItems.clear();
if (mClickedPosition==-1)
{
m_listItems.add(Text);
}
else
{
m_listItems.set(mClickedPosition, Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
Activity B (Project1)
if(getIntent().getExtras()!=null) { //if has value pass from A
final String Amount = getIntent().getExtras().getString("result");
final String description1 = getIntent().getExtras().getString("description");
txt1.setText(description1);
txt.setText(Amount);
}
b.setOnClickListener(new View.OnClickListener() { // return to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
returnIntent.putExtra("c", c); // receive from Activity C
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
viewImage.setImageBitmap(Global.img); // receive from C
}
Noted that the result in Activity A represents value 3,5 while name represents project and Medical. How can I fix this ? Please help.
From what I understood, your variable name in Activity A contains previously resulted value (from Activity B) and not from row you have clicked on listview i.e. "Medical" value you previously got from Activity B which held by variable name and on your listview click event you have checks the if name is "Medical" or "Project" (and in this case it is "Medical" and hence Medical activity is started).
One solution is to get the value("Project/Medical") from listview.
Try this code.
Activity A
mClickedPosition = position;
String temp[] = m_listItems.get(position).split("\\s\\s+");
result = temp[temp.length - 1].trim();
result = result.replace("RM","");
name = temp[1].trim();
if (name.equals("Project")) {
Intent intent = new Intent(Claims1.this.getActivity(), Project1.class);
intent.putExtra("bitmap", true);
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 0);
Log.e("RESULT", "Result= " + result);
}
else if(name.equals("Medical"))
{
Intent intent = new Intent(Claims1.this.getActivity(), Medical.class);
intent.putExtra("bitmap", true);
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 1);
}