Create Delete Dialog on selected piechart value? - java

I created this android app using the MPAndroidChart Library, which allows the user to create a quick PieChart using an ArrayList (I added some screenshots, for clarification).
My problem is that I want to allow the user to delete an entry from the piechart (and the array list), the pie chart should then be rendered without the removed entry.
Is there any way I can achieve this by allowing the user to long press an item, which opens some sort of yes/no dialog?
Screenshots gallery
Code:
package com.example.quickpie;
public class Main extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final List<PieEntry> entries = new ArrayList<>();
final EditText editText = (EditText) findViewById(R.id.editText);
final EditText editText2 = (EditText) findViewById(R.id.editText2);
final EditText editText3 = (EditText) findViewById(R.id.editText3);
final Button button = (Button) findViewById(R.id.button);
final Button button2 = (Button) findViewById(R.id.button2);
final TextView textView = (TextView) findViewById(R.id.textView);
final TextView textView2 = (TextView) findViewById(R.id.textView2);
final TextView textView3 = (TextView) findViewById(R.id.textView3);
editText.requestFocus();
button.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
//if(editText.getFreezesText())
if (editText.getText().toString().matches("")) {
Toast.makeText(getBaseContext(), "You did not enter a Valid Item ID", Toast.LENGTH_LONG).show();
return;
}
else if (editText2.getText().toString().matches("")) {
Toast.makeText(getBaseContext(), "You did not enter a Valid Quantitiy", Toast.LENGTH_LONG).show();
return;
}
else {
String nomen = (editText.getText().toString());
float number = Float.parseFloat(editText2.getText().toString());
final PieChart piechart = (PieChart) findViewById(R.id.piechart);
entries.add(new PieEntry(number, nomen));
editText.setText("");
editText2.setText("");
textView3.setSingleLine(false);
textView3.append("\n" + nomen + " " + number);
editText.requestFocus();
PieDataSet set = new PieDataSet(entries, "");
//colors
getResources().getColor(R.color.violp);
getResources().getColor(R.color.bluep);
getResources().getColor(R.color.redp);
getResources().getColor(R.color.greenp);
getResources().getColor(R.color.yellowp);
getResources().getColor(R.color.orangep);
getResources().getColor(R.color.lightbluep);
getResources().getColor(R.color.purplep);
getResources().getColor(R.color.darkredp);
set.setColors(new int[]{R.color.bluep, R.color.greenp, R.color.violp, R.color.redp, R.color.yellowp, R.color.orangep, R.color.lightbluep, R.color.purplep, R.color.darkredp}, getApplicationContext());
PieData data = new PieData(set);
piechart.setData(data);
Description description = new Description();
description.setText(getResources().getString(R.string.besch));
piechart.setDescription(description);
Toast.makeText(getBaseContext(), (R.string.loading),
Toast.LENGTH_SHORT).show();
String mitte = (editText3.getText().toString());
piechart.setCenterText(mitte);
piechart.setCenterTextSize(30);
piechart.setNoDataText(String.valueOf(R.string.nodata));
piechart.notifyDataSetChanged();
piechart.animateX(2000, Easing.EasingOption.EaseInExpo);
piechart.animateY(2000, Easing.EasingOption.EaseInExpo);
piechart.invalidate();
editText3.setVisibility(View.VISIBLE);
editText3.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
String mitte = (editText3.getText().toString());
piechart.setCenterText(mitte);
editText3.setText("");
editText.requestFocus(); //editText3.setVisibility(View.INVISIBLE);
InputMethodManager imm = (InputMethodManager) getSystemService(Main.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
//do something
}
return false;
}
});
editText3.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEvent.ACTION_UP == event.getAction()) {
piechart.setCenterText("");
textView3.setHint(R.string.hint1);
}
return false; // return is important...
}
});
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Toast.makeText(getBaseContext(), R.string.longpresshint, Toast.LENGTH_LONG).show();
return true;
}
});
final Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mitte = (editText3.getText().toString());
piechart.setCenterText(mitte);
//piechart.setVisibility(View.VISIBLE);
//editText.setVisibility(View.INVISIBLE);
//textView2.setVisibility(View.INVISIBLE);
//textView3.setVisibility(View.INVISIBLE);
//editText3.setVisibility(View.INVISIBLE);
// editText2.setVisibility(View.INVISIBLE);
//button.setVisibility(View.INVISIBLE);
//button2.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(), (R.string.loading),
Toast.LENGTH_SHORT).show();
piechart.animateX(2000, Easing.EasingOption.EaseInExpo);
piechart.animateY(2000, Easing.EasingOption.EaseInExpo);
InputMethodManager imm = (InputMethodManager) getSystemService(Main.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
});
}}
}
)
;
}
#Override
public void onBackPressed(){
super.onBackPressed();
Intent intent = getIntent();
finish();
startActivity(intent);
}
}

Please try this
button.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
//if(editText.getFreezesText())
if (editText.getText().toString().matches("")) {
Toast.makeText(getBaseContext(), "You did not enter a Valid Item ID", Toast.LENGTH_LONG).show();
return;
}
else if (editText2.getText().toString().matches("")) {
Toast.makeText(getBaseContext(), "You did not enter a Valid Quantitiy", Toast.LENGTH_LONG).show();
return;
}
else {
piechart.invalidate();
}

Related

Dialog dismiss not working inside adapter

I have a modal(dialog) with a edit text inside and a send button, what i'm trying to do is simply send the content inside the edit text when the button is clicked, the thing is, sending the content is working, but when i call mydialog.dismiss(); it doesn't work. It is using an instance of another class to call a method retrofit, and inside the "done" and "not done" buttons i have the "enviar"(send) button which is the one i'm trying to close the modal with.
Here is the adapter code:
public TasksAdapter(#NonNull Context context, #SuppressLint("SupportAnnotationUsage") #LayoutRes ArrayList<Tasks> list){
super(context, 0, list);
sContext = context;
taskData = list;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent){
View listItem = convertView;
if(listItem == null)
listItem = LayoutInflater.from(sContext).inflate(R.layout.item_tasks, parent,false);
final Tasks presenteTask = taskData.get(position);
TextView taskTitle = (TextView) listItem.findViewById(R.id.tasksTitle);
taskTitle.setText(presenteTask.getTitle());
EditText taskColor = (EditText) listItem.findViewById(R.id.taskColor);
if(presenteTask.getHexaColor().isEmpty()){
HexaColor = "#FFFFFF";
}
else{
HexaColor = presenteTask.getHexaColor();
taskColor.setBackgroundColor(Color.parseColor(HexaColor));
}
TextView taskTime = (TextView) listItem.findViewById(R.id.taskTime);
taskTime.setText(presenteTask.getTimeStart().toString().substring(0,5));
tasksModal = new Dialog(sContext);
tasksModal.setCancelable(false);
tasksModal.setContentView(R.layout.modal_tasksdone);
tasksModal.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
final EditText comentarios = (EditText) tasksModal.findViewById(R.id.edtComentario);
final Calendario calendario = new Calendario();
Button done = (Button) listItem.findViewById(R.id.tasksDone);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
yorn = true;
tarefaId = presenteTask.getTaskId();
data = presenteTask.getDataTask();
hora = String.valueOf(presenteTask.getTimeStart());
tasksModal.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentario = comentarios.getText().toString();
if(comentario.equals("")){
Toast.makeText(sContext,"Por favor digite um comentário.", Toast.LENGTH_SHORT).show();
tasksModal.dismiss();
}
else{
calendario.retrofitDoneTasks(tarefaId, comentario, data, hora, yorn, tarefaRealizadaId);
tasksModal.dismiss();
}
}
});
tasksModal.show();
}
});
Button notDone = (Button) listItem.findViewById(R.id.tasksNotDone);
notDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
yorn = false;
tarefaId = presenteTask.getTaskId();
data = presenteTask.getDataTask();
hora = String.valueOf(presenteTask.getTimeStart());
tasksModal.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentario = comentarios.getEditableText().toString();
if(comentario.equals("")){
Toast.makeText(sContext,"Por favor digite um comentário.", Toast.LENGTH_SHORT).show();
tasksModal.dismiss();
}
else{
calendario.retrofitDoneTasks(tarefaId, comentario, data, hora, yorn, tarefaRealizadaId);
tasksModal.dismiss();
}
}
});
tasksModal.show();
}
});
return listItem;
}
}
Thank you very much!
Firstly you have to make your dialog un-cancelable, so that outside click doesn't dismiss it using tasksModal.setCancelable(false);
Secondly no need to repeat code to create dialog inside done/undone button click. So, remove it and move it to TasksAdapter constructor.
Thirdly You are not dismissing your dialog inside done button click. So, add this tasksModal.dismiss();
Check and try with below code:
EditText comentarios;
Calendario calendario;
public TasksAdapter(#NonNull Context context, #SuppressLint("SupportAnnotationUsage") #LayoutRes ArrayList<Tasks> list){
super(context, 0, list);
sContext = context;
taskData = list;
tasksModal = new Dialog(sContext);
tasksModal.setCancelable(false); //make it un cancelable
tasksModal.setContentView(R.layout.modal_tasksdone);
tasksModal.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
comentarios = (EditText) tasksModal.findViewById(R.id.edtComentario);
calendario = new Calendario();
}
-------------------------------------------------------------
Button done = (Button) listItem.findViewById(R.id.tasksDone);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentarios.setText("");
yorn = true;
tarefaId = presenteTask.getTaskId();
data = presenteTask.getDataTask();
hora = String.valueOf(presenteTask.getTimeStart());
tasksModal.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentario = comentarios.getEditableText().toString();
if(!comentario.equals("")){
tasksModal.dismiss(); //dismiss here
calendario.retrofitDoneTasks(tarefaId, comentario, data, hora, yorn, tarefaRealizadaId);
}
else{
Toast.makeText(sContext,"Por favor digite um comentário.", Toast.LENGTH_SHORT).show();
}
}
});
tasksModal.show();
}
});
Button notDone = (Button) listItem.findViewById(R.id.tasksNotDone);
notDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentarios.setText("");
yorn = false;
tarefaId = presenteTask.getTaskId();
data = presenteTask.getDataTask();
hora = String.valueOf(presenteTask.getTimeStart());
tasksModal.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentario = comentarios.getEditableText().toString();
if(comentario.equals("")){
Toast.makeText(sContext,"Por favor digite um comentário.", Toast.LENGTH_SHORT).show();
}
else{
tasksModal.dismiss();
calendario.retrofitDoneTasks(tarefaId, comentario, data, hora, yorn, tarefaRealizadaId);
}
}
});
tasksModal.show();
}
});

App force closes after implementing media player

I programmed a quiz app there is one question, 3 choices, and ONE correct answer. Now I set up that on click on the right answer the MediaPlayer starts playing the sound. It worked fine but after I rebuilt the app forcecloses during splashscreen. Logcat says the error is the public void onClick(View view) under the FOR query.
Thanks for watching :D
public class QuizActivity extends AppCompatActivity {
private ActionBarDrawerToggle mToggle;
private QuestionLibrary mQuestionLibrary = new QuestionLibrary();
private TextView mScoreView;
private TextView mQuestionView;
private Button mButtonChoice1;
private Button mButtonChoice2;
private Button mButtonChoice3;
private String mAnswer;
private int mScore = 0;
private int mQuestionNumber = 0;
Dialog dialog;
TextView closeButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
final MediaPlayer mp = new MediaPlayer();
createDialog();
Button dialogButton = (Button) findViewById(R.id.dialogbtn);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView shareTextView = (TextView) findViewById(R.id.share);
shareTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Intent.ACTION_SEND);
myIntent.setType("text/plain");
myIntent.putExtra(Intent.EXTRA_SUBJECT, "Hello!");
myIntent.putExtra(Intent.EXTRA_TEXT, "My highscore in Quizzi is very high! I bet you can't beat me except you are cleverer than me. Download the app now! https://play.google.com/store/apps/details?id=amapps.impossiblequiz");
startActivity(Intent.createChooser(myIntent, "Share with:"));
}
});
mQuestionLibrary.shuffle();
setSupportActionBar((Toolbar) findViewById(R.id.nav_action));
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Able to see the Navigation Burger "Button"
((NavigationView) findViewById(R.id.nv1)).setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_stats:
startActivity(new Intent(QuizActivity.this, Menu2.class));
break;
case R.id.nav_about:
startActivity(new Intent(QuizActivity.this, Menu3.class));
break;
}
return true;
}
});
mScoreView = (TextView) findViewById(R.id.score_score);
mQuestionView = (TextView) findViewById(R.id.question);
mButtonChoice1 = (Button) findViewById(R.id.choice1);
mButtonChoice2 = (Button) findViewById(R.id.choice2);
mButtonChoice3 = (Button) findViewById(R.id.choice3);
final List<Button> choices = new ArrayList<>();
choices.add(mButtonChoice1);
choices.add(mButtonChoice2);
choices.add(mButtonChoice3);
updateQuestion();
for (final Button choice : choices) {
choice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (choice.getText().equals(mAnswer)) {
try {
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("sample.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
updateScore();
updateQuestion();
Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(QuizActivity.this, "Wrong... Try again!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score", mScore); // pass score to Menu2
startActivity(intent);
}
}
});
}
}
private void updateQuestion() {
if (mQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
mButtonChoice1.setText(mQuestionLibrary.getChoice1(mQuestionNumber));
mButtonChoice2.setText(mQuestionLibrary.getChoice2(mQuestionNumber));
mButtonChoice3.setText(mQuestionLibrary.getChoice3(mQuestionNumber));
mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber++);
} else {
Toast.makeText(QuizActivity.this, "Last Question! You are very intelligent!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score", mScore);
startActivity(intent);
}
}
private void updateScore() {
mScoreView.setText(String.valueOf(++mScore));
SharedPreferences mypref = getPreferences(MODE_PRIVATE);
int highScore = mypref.getInt("highScore", 0);
if (mScore > highScore) {
SharedPreferences.Editor editor = mypref.edit();
editor.putInt("highScore", mScore);
editor.apply();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return mToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
private void createDialog() {
dialog = new Dialog(this);
dialog.setTitle("Tutorial");
dialog.setContentView(R.layout.popup_menu1_1);
closeButton = (TextView) dialog.findViewById(R.id.closeTXT);
}
}
Try something like:
OnCreate{
mButtonChoice1 = (Button) findViewById(R.id.choice1);
mButtonChoice2 = (Button) findViewById(R.id.choice2);
mButtonChoice3 = (Button) findViewById(R.id.choice3);
mButtonChoice1.setOnClickListener(this);
mButtonChoice2.setOnClickListener(this);
mButtonChoice3.setOnClickListener(this);
}
public void onClick(View v) {
Button b = (Button)v;
String buttonText = b.getText().toString();
if(buttonText.equals(something)){
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = new MediaPlayer();
}
AssetFileDescriptor descriptor = getAssets().openFd("sample.mp3"");
mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mp.prepare();
mp.start();
}
}

android.widget.Button cannot be cast to android.widget.CheckBox

I'm getting the error from the title in my Android project. I have searched for similar issues, which had me checkboxes casting, which seems ok, and also to clean and rebuild the project, which it did not work.
The app is crashing when I click the "Register" Button after a register form that contains EditTexts (for username, email and password) and Checkboxes for the user to pick multiple items. What should I do next?
public class RegisterActivity extends Activity {
ArrayList<Sport> sports = new ArrayList<>();
ArrayList<Sport> selectedSports = new ArrayList<>();
private void initializeSports(){
String[] sportsArray = getResources().getStringArray(array.sportsName);
for (int i = 0; i < sportsArray.length; i++){
sports.add(new Sport(i + 1, sportsArray[i]));
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_register);
initializeSports();
final EditText etEmail = (EditText) findViewById(id.etEmail);
final EditText etUsername = (EditText) findViewById(id.etUsername);
final EditText etPassword = (EditText) findViewById(id.etPassword);
final Button bRegister = (Button) findViewById(id.bRegister);
final CheckBox cbSoccer = (CheckBox) findViewById(id.cbSoccer);
cbSoccer.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbFootball = (CheckBox) findViewById(id.cbFootball);
cbFootball.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbBasket = (CheckBox) findViewById(id.cbBasket);
cbBasket.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbTennis = (CheckBox) findViewById(id.cbTennis);
cbTennis.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbSwimming = (CheckBox) findViewById(id.cbSwimming);
cbSwimming.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbGym = (CheckBox) findViewById(id.cbGym);
cbGym.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbOther = (CheckBox) findViewById(id.cbOther);
cbOther.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String email = etEmail.getText().toString();
final String passcode = etPassword.getText().toString();
selectItem(v);
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(username, email, passcode, selectedSports, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
public void selectItem(View v){
boolean checked = ((CheckBox)v).isChecked();
switch(v.getId()){
case R.id.cbSoccer:
if(checked){
selectedSports.add(sports.get(0));
} else{
selectedSports.remove(sports.get(0));
} break;
case R.id.cbFootball:
if(checked){
selectedSports.add(sports.get(1));
} else{
selectedSports.remove(sports.get(1));
} break;
case R.id.cbTennis:
if(checked){
selectedSports.add(sports.get(2));
} else{
selectedSports.remove(sports.get(2));
} break;
case R.id.cbSwimming:
if(checked){
selectedSports.add(sports.get(3));
} else{
selectedSports.remove(sports.get(3));
} break;
case R.id.cbGym:
if(checked){
selectedSports.add(sports.get(4));
} else{
selectedSports.remove(sports.get(4));
} break;
case R.id.cbBasket:
if(checked){
selectedSports.add(sports.get(5));
} else{
selectedSports.remove(sports.get(5));
} break;
case R.id.cbOther:
if(checked){
selectedSports.add(sports.get(6));
} else{
selectedSports.remove(sports.get(6));
} break;
}
}
}
You are casting the view to CheckBox in your selectItem(v) method and in your listener
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectItem(v);
}
});
You are passing the View v, i.e, the clicked button, so the button can not be casted to CheckBox.
Remove this line from listener
selectItem(v);
and it will be alright.
In the selectItem(v) method the view passed to the method is an instance of Button since it is written in the onClickListener of button
If you want to do the same first make a check in selectItem(View v) method
if(v instanceof CheckBox) {
boolean checked = ((CheckBox)v).isChecked();
}
Then proceed with the rest of code

How do I check if my editText field is empty and make it go to a new activity with a Button?

I have made this code :
public class MainActivity extends AppCompatActivity {
private ImageButton ourButton;
private EditText operand1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find Views by IDs :
ourButton = (ImageButton) findViewById(R.id.gobutton);
operand1 = (EditText) findViewById(R.id.edit_Name);
String ed_text = operand1.getText().toString().trim();
if(ed_text.isEmpty() || ed_text.length() == 0 || ed_text.equals("") || ed_text == null)
{
ourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "You did not enter a username", Toast.LENGTH_LONG).show();
}
});
}
else
{
ourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this, ScreenName.class);
MainActivity.this.startActivity(myIntent);
}
});
}
}
The problem is that if I pressed the button with or without entering anything in the field, it will say :
You did not enter a username
And the next activity will not work neither.
How do I make the button to move the user into the next activity while making sure he inputed a name?
Use this, I have modified your code..
public class MainActivity extends AppCompatActivity {
private ImageButton ourButton;
private EditText operand1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find Views by IDs :
ourButton = (ImageButton) findViewById(R.id.gobutton);
operand1 = (EditText) findViewById(R.id.edit_Name);
ourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String ed_text = operand1.getText().toString().trim();
if(ed_text.equals(""))
{
Toast.makeText(MainActivity.this, "You did not enter a username", Toast.LENGTH_LONG).show();
}
else
{
Intent myIntent = new Intent(MainActivity.this, ScreenName.class);
MainActivity.this.startActivity(myIntent);
}
}
});
}
You need to do the check when the button is pressed, here is an example:
public class MainActivity extends AppCompatActivity {
private ImageButton ourButton;
private EditText operand1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find Views by IDs :
ourButton = (ImageButton) findViewById(R.id.gobutton);
operand1 = (EditText) findViewById(R.id.edit_Name);
ourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(operand1.getText().length() == 0){
Toast.makeText(MainActivity.this, "You did not enter a username", Toast.LENGTH_LONG).show();
}else{
Intent myIntent = new Intent(MainActivity.this, ScreenName.class);
MainActivity.this.startActivity(myIntent);
}
}
});
}
}
The problem is that you are not checking the value in the listener. Change it to this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find Views by IDs :
ourButton = (ImageButton) findViewById(R.id.gobutton);
operand1 = (EditText) findViewById(R.id.edit_Name);
ourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (operand1.getText().toString().trim().length() > 0) {
Intent myIntent = new Intent(MainActivity.this, ScreenName.class);
MainActivity.this.startActivity(myIntent);
} else {
Toast.makeText(MainActivity.this, "You did not enter a username", Toast.LENGTH_LONG).show();
}
}
});
}
Also onCreate gets called when the Activity is created so you can't check the name field's value in there. That's why you need to move that check in your button's click listener. Then it will always check if the name field is empty when you click your button.
You can try this code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private ImageButton ourButton;
private EditText operand1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find Views by IDs :
ourButton = (ImageButton) findViewById(R.id.gobutton);
operand1 = (EditText) findViewById(R.id.edit_Name);
ourButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.gobutton) {
if(operand1.getText().toString().trim().equals("")){
Toast.makeText(MainActivity.this, "You did not enter a username", Toast.LENGTH_LONG).show()
}else{
Intent myIntent = new Intent(this,ScreenName.class);
startActivity(myIntent);
}
}
}
Try this instead...
public class MainActivity extends AppCompatActivity {
private ImageButton ourButton;
private EditText operand1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find Views by IDs :
ourButton = (ImageButton) findViewById(R.id.gobutton);
operand1 = (EditText) findViewById(R.id.edit_Name);
String ed_text = operand1.getText().toString().trim();
ourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ed_text.isEmpty() || ed_text.length() == 0 || ed_text.equals("") || ed_text == null) {
Toast.makeText(MainActivity.this, "You did not enter a username", Toast.LENGTH_LONG).show();
} else {
Intent myIntent = new Intent(MainActivity.this, ScreenName.class);
MainActivity.this.startActivity(myIntent);
}
});
}
}
you can use this
public class MainActivity extends AppCompatActivity {
private ImageButton ourButton;
private EditText operand1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find Views by IDs :
ourButton = (ImageButton) findViewById(R.id.gobutton);
operand1 = (EditText) findViewById(R.id.edit_Name);
String ed_text = operand1.getText().toString();
ourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ed_text.equalsignorcase("")
{
Toast.makeText(MainActivity.this, "You did not enter a username", Toast.LENGTH_LONG).show();
}
else
{
Intent myIntent = new Intent(MainActivity.this, ScreenName.class);
MainActivity.this.startActivity(myIntent);
}
});
}
cahnge your code like that
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private ImageButton ourButton;
private EditText operand1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find Views by IDs :
ourButton = (ImageButton) findViewById(R.id.gobutton);
operand1 = (EditText) findViewById(R.id.edit_Name);
ourButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
String ed_text = operand1.getText().toString().trim();
if(ed_text.equals("")){
Toast.makeText(MainActivity.this, "You did not enter a username", Toast.LENGTH_LONG).show()
}else{
Intent myIntent = new Intent(MainActivity.this, ScreenName.class);
MainActivity.this.startActivity(myIntent);
}
}
}
Don't set two OnClickListeners for one button
Try following code -
String ed_text = operand1.getText().toString().trim();
ourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!TextUtils.isEmpty(ed_text)){
Toast.makeText(MainActivity.this, "Not Empty", Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(MainActivity.this, ScreenName.class);
startActivity(myIntent);
finish(); //If you want to kill current Activity.
}else{
Toast.makeText(MainActivity.this, "Empty", Toast.LENGTH_SHORT).show();
}
}
});
Hope it will help :)

Users not able to sign in using Parse

I'm using Parse.com and my app is supposed to let users sign up and login. They are able to sign up, at which point I see that they get stored on the Parse database, but when I try using the same username and password on my login activity, it says it does not exist. After the user signs up though, it goes into the MainActivity, up until you sign out, then you can't log back in. Any help?
Here is my SignUp Activity
public class SignupActivity extends ActionBarActivity {
EditText mName, mUsername, mEmail, mPassword, mPasswordConfirm;
Button mSignup, mCancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_signup);
getActionBar().setDisplayHomeAsUpEnabled(true);
mName = (EditText) findViewById(R.id.name);
mUsername = (EditText) findViewById(R.id.username);
mEmail = (EditText) findViewById(R.id.email);
mPassword = (EditText) findViewById(R.id.password);
mPasswordConfirm = (EditText) findViewById(R.id.confirm_password);
mSignup = (Button) findViewById(R.id.signup_button);
mSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = mUsername.getText().toString().trim();
final String email = mEmail.getText().toString().trim();
final String password = mPassword.getText().toString().trim();
final String confirmedPassword = mPasswordConfirm.getText().toString().trim();
final String name = mName.getText().toString().trim();
if(username.isEmpty() || email.isEmpty() || password.isEmpty()){
AlertDialog.Builder builder = new AlertDialog.Builder(SignupActivity.this);
builder.setMessage("Item missing in Signup Fields")
.setPositiveButton("Ok", null)
.setTitle("Error Message");
AlertDialog dialog = builder.create();
dialog.show();
}
else if(!confirmPass(password, confirmedPassword)){
AlertDialog.Builder builder = new AlertDialog.Builder(SignupActivity.this);
builder.setMessage("Passwords do not match")
.setPositiveButton("Ok", null)
.setTitle("Error Message");
AlertDialog dialog = builder.create();
dialog.show();
}
else{
ParseUser user = new ParseUser();
user.setUsername(username);
user.setPassword(password);
user.setEmail(email);
user.put("Name", name);
setProgressBarIndeterminateVisibility(true);
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
setProgressBarIndeterminate(false);
if(e == null){
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(SignupActivity.this);
builder.setMessage(e.getMessage())
.setTitle("Error Message")
.setPositiveButton("Ok", null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
}
public boolean confirmPass(String password, String passwordConfirm){
if(password.equals(passwordConfirm)){
return true;
}
else return false;
}
}
Here is my LoginActivity
public class LoginActivity extends ActionBarActivity {
EditText mUsername, mPassword;
Button mLogin;
TextView mSignup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Allows us to use progress circle
requestWindowFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_login);
//hides action bar
getActionBar().hide();
mUsername = (EditText) findViewById(R.id.username);
mPassword = (EditText) findViewById(R.id.password);
mLogin = (Button) findViewById(R.id.sign_in);
mSignup = (TextView) findViewById(R.id.sign_up);
//goes to signup page when clicked
mSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
startActivity(intent);
}
});
//logs user in when clicked
mLogin.setOnClickListener(new View.OnClickListener() {
String username = mUsername.getText().toString().trim();
String password = mPassword.getText().toString().trim();
//checks to make sure user exists or doesn't exist to sign them in
#Override
public void onClick(View v) {
ParseUser.logInInBackground(username, password, new LogInCallback() {
//if user exists, do this
#Override
public void done(ParseUser user, ParseException e) {
if(e == null){
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
Toast.makeText(LoginActivity.this, (CharSequence) user, Toast.LENGTH_LONG);
//makes sure you can't press "back" in the next activity and come back to Login page
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
//if user doesn't exist, show error message
else{
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage((CharSequence) username)
.setPositiveButton("Ok", null)
.setTitle("Error Message");
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
});
}
}
Here is my MainActivity
public class MainActivity extends ListActivity {
ParseQueryAdapter<ParseObject> mainAdapter;
CustomAdapter customAdapter;
ListView listView;
TextView ideaTitle;
ImageView icon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ideaTitle = (TextView) findViewById(R.id.title);
icon = (ImageView) findViewById(R.id.icon);
ParseUser currentUser = ParseUser.getCurrentUser();
if(currentUser == null){
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}else {
Log.i("USERNAME", currentUser.getUsername());
customAdapter = new CustomAdapter(this);
listView = (ListView) findViewById(android.R.id.list);
listView.setAdapter(customAdapter);
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
//get selected items
System.out.println(l);
System.out.println(v);
System.out.println(position);
System.out.println(id);
Toast.makeText(MainActivity.this, (int) position, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch(id){
case R.id.add_idea:
Intent add = new Intent(MainActivity.this, AddIdeaActivity.class);
startActivity(add);
break;
case R.id.logout:
ParseUser.logOut();
Intent logout = new Intent(MainActivity.this, LoginActivity.class);
logout.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
logout.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(logout);
break;
}
return super.onOptionsItemSelected(item);
}
}
Make sure your login use the same parse init session as main activity.
Create new user in your app.
Verify parse dashboard shows the new entry in User table.
Use curl to log on to your app from terminal session ( cmd) if on windows os.
If u can curl cli log on following log on instruction in parse rest Api docs, then u know u r log on activity has bug.

Categories