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
Related
Can someone look at my code its really simple created just to practice my skills. But the language spinner works but the gender spinner is buggy. It will work once i change the language then change the gender and then go back to the gender i originally wanted. Code is shown. Thanks. Have tried putting onItemSelected() for spinnerGen, it does not solve the issue. Researching about this since last night cant find any solution
public class MainActivity extends AppCompatActivity {
private Button btnGo, btnAbout;
private Spinner spinner, spinnerGen;
private EditText addName;
private ArrayList<String> options;
private ArrayList<String> optionsGen;
private String allOption = "";
private String genOption = "";
private String genOptionSec = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initPage();
options = new ArrayList<>();
options.add("English");
options.add("Bengali");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, options);
spinner.setAdapter(adapter);
adapter.setNotifyOnChange(true);
adapter.notifyDataSetChanged();
optionsGen = new ArrayList<>();
optionsGen.add("Male");
optionsGen.add("Female");
ArrayAdapter<String> adapterGen = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, optionsGen);
spinnerGen.setAdapter(adapterGen);
adapterGen.setNotifyOnChange(true);
adapterGen.notifyDataSetChanged();
spinnerMethod();
}
private void initPage() {
btnGo = findViewById(R.id.btnGo);
btnAbout = findViewById(R.id.btnAbout);
spinner = findViewById(R.id.spinner);
spinnerGen = findViewById(R.id.spinnerGen);
addName = findViewById(R.id.addName);
}
public void spinnerMethod() {
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
allOption = spinner.getSelectedItem().toString();
switch (allOption) {
case "English" :
newMethodEnglish();
break;
case "Bengali" :
newMethodBengali();
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void newMethodEnglish() {
genOption = spinnerGen.getSelectedItem().toString();
switch (genOption) {
case "Male":
onClickEngMale(); //In these method Im just navigating to another activity
break;
case "Female":
OnClickEngFemale();
break;
default:
break;
}
}
public void OnClickEngFemale() {
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String femaleData = addName.getText().toString();
Intent intent = new Intent(MainActivity.this, EngFemale.class);
intent.putExtra("DataFemale", femaleData);
startActivity(intent);
}
});
}
public void onClickEngMale() {
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String maleData = addName.getText().toString();
Intent intent = new Intent(MainActivity.this, EngMale.class);
intent.putExtra("Data", maleData);
startActivity(intent);
}
});
}
public void newMethodBengali() {
genOptionSec = spinnerGen.getSelectedItem().toString();
switch (genOptionSec){
case "Male":
onClickBanMale();
break;
case "Female":
onClickBanFemale();
default:
break;
}
}
public void onClickBanMale() {
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String maleData = addName.getText().toString();
Intent intent = new Intent(MainActivity.this, BanMale.class);
intent.putExtra("DataBan", maleData);
startActivity(intent);
}
});
}
public void onClickBanFemale() {
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String femaleData = addName.getText().toString();
Intent intent = new Intent(MainActivity.this, BanFemale.class);
intent.putExtra("BanFemale", femaleData);
startActivity(intent);
}
});
}
}
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();
}
});
I try to google play subscription billing. Code is working doing payment. But I want to try when a payment successfull ı want to catch payment cost,time(montly,yearly) and I send my php API for example with an ID or Token. How can i do this.
I tried overriding onPurchasesUpdated
public void onPurchasesUpdated(BillingResult billingResult, #Nullable List<Purchase> purchases) {
}
but it didn't work . I tried show a toast. But method didn't work.
Can I do this with this method If I can how can I run this method ?
public void openPayment(final Context mContext){
final List<String> skuList = new ArrayList<>();
//valueof1MonthMoney,valueof3MonthsMoney,valueof6MonthsMoney,valueof1YearMoney;
skuList.add("com.yeniasya.enewspaper.subscription.onemonth");
skuList.add("com.yeniasya.enewspaper.subscription.threemonth");
skuList.add("com.yeniasya.enewspaper.subscription.sixmonth");
skuList.add("com.yeniasya.enewspaper.subscription.oneyear");
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(mContext,android.R.style.Theme_DeviceDefault_Light_NoActionBar_Fullscreen);
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View mView = li.inflate(R.layout.popup_payment, null);
ImageView imvClose=(ImageView)mView.findViewById(R.id.imvClose);
final TextView tv1MonthMoney = (TextView) mView.findViewById(R.id.tv1MonthMoney);
final TextView tv3MonthsMoney = (TextView) mView.findViewById(R.id.tv3MonthsMoney);
final TextView tv6MonthsMoney = (TextView) mView.findViewById(R.id.tv6MonthsMoney);
final TextView tv1YearMoney = (TextView) mView.findViewById(R.id.tv1YearMoney);
final TextView tvOpenPrivacy = (TextView) mView.findViewById(R.id.tvOpenPrivacy);
final LinearLayout linLay1Year = (LinearLayout) mView.findViewById(R.id.linLay1Year);
final LinearLayout linLay6Months = (LinearLayout) mView.findViewById(R.id.linLay6Months);
final LinearLayout linLay3Months = (LinearLayout) mView.findViewById(R.id.linLay3Months);
final LinearLayout linLay1Month = (LinearLayout) mView.findViewById(R.id.linLay1Month);
mBuilder.setView(mView);
dialog = mBuilder.create();
dialog.setCanceledOnTouchOutside(false);
final SkuDetails[] s = new SkuDetails[4];
params.setSkusList(skuList).setType(BillingClient.SkuType.SUBS);
billingClient.querySkuDetailsAsync(params.build(),
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(BillingResult billingResult,
List<SkuDetails> skuDetailsList) {
// Process the result.
s[0] =skuDetailsList.get(0);
s[1] =skuDetailsList.get(1);
s[2] =skuDetailsList.get(2);
s[3] =skuDetailsList.get(3);
// Toast.makeText(mContext, "listeye girdi", Toast.LENGTH_SHORT).show();
try {
tv1MonthMoney.setText(skuDetailsList.get(0).getPrice());
tv1YearMoney.setText(skuDetailsList.get(1).getPrice());
tv6MonthsMoney.setText(skuDetailsList.get(2).getPrice());
tv3MonthsMoney.setText(skuDetailsList.get(3).getPrice());
/* if(skuDetailsList.get(i).getSku().equals("com.yeniasya.enewspaper.subscription.onemonth"));
tv1MonthMoney.setText(skuDetailsList.get(i).getPrice()+"");
if(skuDetailsList.get(i).getSku().equals("com.yeniasya.enewspaper.subscription.threemonth"));
tv3MonthsMoney.setText(skuDetailsList.get(i).getPrice()+"");
if(skuDetailsList.get(i).getSku().equals("com.yeniasya.enewspaper.subscription.sixmonth"));
tv6MonthsMoney.setText(skuDetailsList.get(i).getPrice()+"");
if(skuDetailsList.get(i).getSku().equals("com.yeniasya.enewspaper.subscription.oneyear"));
tv1YearMoney.setText(skuDetailsList.get(i).getPrice()+""); */
// Toast.makeText(mContext, skuDetailsList.get(i).getSku()+"", Toast.LENGTH_SHORT).show();
}catch (Exception e){
}
}
});
dialog.show();
imvClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
linLay1Year.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takeMoney(s[1]);
}
});
linLay1Month.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takeMoney(s[0]);
}
});
linLay3Months.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takeMoney(s[3]);
}
});
linLay6Months.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takeMoney(s[2]);
}
});
tvOpenPrivacy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
Intent i = new Intent(Intent.ACTION_VIEW);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setData(Uri.parse(mcontext.getString(R.string.PrivacyPolicyUrl)));
mcontext.startActivity(i);}catch (Exception e){}
}
});
}
private void takeMoney(SkuDetails skuDetails){
BillingFlowParams flowParams = BillingFlowParams.newBuilder()
.setSkuDetails(skuDetails)
.build();
billingClient.launchBillingFlow(MainActivity.mActivity,flowParams);
// Toast.makeText(mContext, "bastın3", Toast.LENGTH_SHORT).show();
}
#Override
public void onPurchasesUpdated(BillingResult billingResult, #Nullable List<Purchase> purchases) {
}
This question already has answers here:
how to pass value data between classes/activity in Android?
(6 answers)
Closed 5 years ago.
I want to pass the value of textview1 of Income.java onClick of btn_save to the MainActivity. And also want to sum the value of MainActivity.java when again new value passed Please help me...
Income.java
public class Income extends AppCompatActivity implements AdapterView.OnItemSelectedListener,Calculator.OnDialogReturnListener,View.OnClickListener{
Spinner spinner1;
String[] name,name1;
Button btn_cancel, btn_save,acc_btn,button,updatebtn;
TextView textView1,textView2,accountTV,wantupdate,income;
//EditText textView1;
int yy,mm,dd;
private Income_class i_class;
DatabaseHandler mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.income);
textView1 = (TextView) findViewById(R.id.income_tv);
textView2 = (TextView) findViewById(R.id.date_tv);
accountTV = (TextView) findViewById(R.id.acc_tv);
income = (TextView) findViewById(R.id.incometv);
wantupdate = (TextView) findViewById(R.id.notupdate);
btn_cancel = (Button) findViewById(R.id.cancel_btn);
updatebtn = (Button) findViewById(R.id.up_btn);
acc_btn = (Button) findViewById(R.id.account_btn);
btn_save = (Button) findViewById(R.id.save_btn);
button = (Button) findViewById(R.id.btn);
final AlertDialog.Builder dialog = new AlertDialog.Builder(Income.this);
final AlertDialog.Builder dialog1 = new AlertDialog.Builder(Income.this);
final AlertDialog.Builder dialog2 = new AlertDialog.Builder(Income.this);
final AlertDialog.Builder dialog3 = new AlertDialog.Builder(Income.this);
final EditText editText = new EditText(Income.this);
dialog.setView(editText);
final DatabaseHandler db = new DatabaseHandler(Income.this);
mydb = new DatabaseHandler(this);
button.setOnClickListener(this);
// for calculator
final Calculator cdd = new Calculator(Income.this);
cdd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//cdd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
cdd.setOnDialogReturnListener(this);
cdd.show();
// for displaying date
final Calendar c = Calendar.getInstance();
yy = c.get(Calendar.YEAR);
mm = c.get(Calendar.MONTH);
dd = c.get(Calendar.DAY_OF_MONTH);
//set current date into text..
textView2.setText(new StringBuilder()
//month os 0 based. Just add 1
.append(dd).append("-").append(mm + 1).append("-").append(yy));
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Income.this,MainActivity.class);
startActivity(intent);
finish();
}
});
acc_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Income.this,Account_detail.class);
startActivity(intent);
finish();
}
});
updatebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String cat = button.getText().toString();
String acc = accountTV.getText().toString();
String text = textView1.getText().toString();
if(text.equals("0")){
dialog3.setTitle("You must enter amount.");
dialog3.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface ialog, int which) {
}
});
dialog3.show();
}
else if(cat.equals("Select Category")){
dialog1.setTitle("Please Select category");
dialog1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/*Intent intent = new Intent(Income.this, Income.class);
startActivity(intent);
finish();*/
button.requestFocus();
}
});
dialog1.show();
}
else if(acc.equals("")){
dialog2.setTitle("Please Select Account");
dialog2.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
acc_btn.requestFocus();
}
});
dialog2.show();
}
else {
String value = accountTV.getText().toString();
String value2 = textView1.getText().toString();
String value3 = button.getText().toString();
db.update_income(value, value2, value3);
Toast.makeText(getBaseContext(), "Updated Successfully...", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Income.this, Acc_income.class);
startActivity(intent);
finish();
}
}
});
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String cat = button.getText().toString();
String acc = accountTV.getText().toString();
String text = textView1.getText().toString();
if(text.equals("0")){
dialog3.setTitle("You must enter amount.");
dialog3.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface ialog, int which) {
}
});
dialog3.show();
}
else if(cat.equals("Select Category")){
dialog1.setTitle("Please Select category");
dialog1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/*Intent intent = new Intent(Income.this, Income.class);
startActivity(intent);
finish();*/
button.requestFocus();
}
});
dialog1.show();
}
else if(acc.equals("")){
dialog2.setTitle("Please Select Account");
dialog2.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
acc_btn.requestFocus();
}
});
dialog2.show();
}
else {
String balance2 = textView1.getText().toString();
String name = accountTV.getText().toString();
String category = button.getText().toString();
db.income_insert(name, category, balance2);
Toast.makeText(getBaseContext(), "Account Added...",
Toast.LENGTH_SHORT).show();
}
}
});
wantupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder dialog = new AlertDialog.Builder(Income.this);
dialog.setTitle("Enter Income");
final EditText editText = new EditText(Income.this);
dialog.setView(editText);
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String value1 = textView1.getText().toString();
String value2 = editText.getText().toString();
if(textView1.equals("0")){
String a = editText.getText().toString();
textView1.setText(a);
}
else if(value2.equals("")){
Toast.makeText(Income.this,"Please Enter Amount.",Toast.LENGTH_LONG).show();
}
else {
int a = Integer.parseInt(value1);
int b = Integer.parseInt(value2);
int sum = a + b;
textView1.setText(Integer.toString(sum));
}
}
});
dialog.show();
}
});
Intent intent = getIntent();
accountTV.setText(intent.getStringExtra("ppp"));
}
public void addnumber(){
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String name2 = name[position];
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onReturn(String data) {
textView1.setText(data);
}
#Override
public void onClick(View v) {
/*String cat = button.getText().toString();
if(cat.equals("Select Category")){
button.setError("Please Select category");
button.requestFocus();
}
else */
final CharSequence[] items = {"Automobile", "Entertainment", "Family", "Food And Drinks", "Gasoline", "Gifts And Donations",
"Groceries", "Health And Fitness", "Housing", "Medical", "Other", "Parking", "Shopping", "Utilities"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Make your selection");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
button.setText(items[item]);
}
});
AlertDialog alert = builder.create();
alert.show();
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(Income.this,MainActivity.class);
startActivity(intent);
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button expance,income,account,budget,calander,report,more,transfer;
TextView incomeTv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
incomeTv = (TextView)findViewById(R.id.incometv);
expance = (Button)findViewById(R.id.button_expanse);
income = (Button)findViewById(R.id.button_income);
account = (Button)findViewById(R.id.button_account);
budget = (Button)findViewById(R.id.button_budget);
transfer = (Button)findViewById(R.id.button_moneytransfer);
calander = (Button)findViewById(R.id.button_calander);
report = (Button)findViewById(R.id.button_report);
more = (Button)findViewById(R.id.button_more);
expance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Expense.class);
startActivity(intent);
finish();
}
});
income.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Income.class);
startActivity(intent);
finish();
}
});
account.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Account_detail.class);
startActivity(intent);
finish();
}
});
transfer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Account_Transfer.class);
startActivity(intent);
finish();
}
});
budget.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Acc_income.class);
startActivity(intent);
finish();
}
});
calander.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Account_detail_2.class);
startActivity(intent);
finish();
}
});
more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Update.class);
startActivity(intent);
finish();
}
});
}
You can use
intent.putExtra("key", value);
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();
}