I am trying to save and store data in an android app using java. At the moment the data will not save and it causes my app to crash. Can anyone make any suggestions to my code? Part of my page includes a total budget and I am difficulty storing and saving the total budget.
public class Summary extends Activity implements TextWatcher, View.OnClickListener
{
DecimalFormat df = new DecimalFormat("£0.00");
int noOfGifts, giftsPurchased;
double cost;
EditText budgetEntered;
double savedBudget = 0;
String budgetString;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.summary);
budgetEntered = (EditText) findViewById(R.id.s2TotalBudget);
budgetEntered.addTextChangedListener(this);
Button saveBudget = (Button) findViewById(R.id.s2ViewList);
saveBudget.setOnClickListener(saveButtonListener);
if(savedBudget != 0)
{
saveBudget.setText(budgetString);
}
Bundle passedInfo = getIntent().getExtras();
if (passedInfo != null)
{
cost = passedInfo.getDouble("cost");
noOfGifts = passedInfo.getInt("noOfGifts");
giftsPurchased = passedInfo.getInt("giftsPurchased");
}
Button logoutButton = (Button) findViewById(R.id.s2LogoutButton);
logoutButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(Summary.this, MainActivity.class);
startActivity(myIntent);
}
});
Button viewList = (Button) findViewById(R.id.s2ViewList);
viewList.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(Summary.this, GiftList.class);
startActivity(myIntent);
}
});
String [][] summary = {{"Number of Presents to buy: ", (noOfGifts + "")},
{"Number of Presents bought:", (giftsPurchased + "")},
{"Cost: £", (cost + "")},
{"Budget: £", "50"}};
String passedBudget=null;
//convert totalPresents to double from String
String tempPresents = summary[0][1];
int presents = Integer.parseInt(tempPresents);
//convert presentsBought to double from String
String tempBought = summary[1][1];
int presentsToBuy = Integer.parseInt(tempBought);
//Number of presents
TextView s2PresentResult = (TextView) findViewById(R.id.s2PresentsResult);
s2PresentResult.setText(summary[0][1]);
//Number of presents to buy
TextView s2PresentsBuyResult = (TextView) findViewById(R.id.s2PresntsBuyResult);
s2PresentsBuyResult.setText((noOfGifts - giftsPurchased) + "");
Bundle passedId = getIntent().getExtras();
if (passedId != null)
{
passedBudget = passedId.getString("Enter Budget");
}
//EditText s2TotalBudget = (EditText) findViewById(R.id.s2TotalBudget);
//s2TotalBudget .addTextChangedListener((android.text.TextWatcher) this);
//s2TotalBudget .setText(passedBudget, TextView.BufferType.EDITABLE);
//Number of people
//TextView s2TotalBudget = (TextView) findViewById(R.id.s2TotalBudget);
//s2TotalBudget.setText("Enter budget");
//Number of people
TextView s2TotalCost = (TextView) findViewById(R.id.s2TotalCost);
s2TotalCost.setText(df.format(Double.parseDouble(summary[2][1])));
//Output if over or under budget
TextView s2CalculateOverBudget = (TextView) findViewById(R.id.s2CalculateOverBudget);
//convert totalCost to double from String
String temp = summary[2][1];
double totalCost = Double.parseDouble(temp);
//convert totalBudget to double from String
String tempTwo = "14";
double totalBudget = Double.parseDouble(tempTwo);
if((totalCost>totalBudget)&&(totalBudget!=0))
{
s2CalculateOverBudget.setTextColor(Color.rgb(209,0,0));
s2CalculateOverBudget.setText("You are over budget");
}
else if(totalBudget==0){
s2CalculateOverBudget.setText("");
}
else {
s2CalculateOverBudget.setText("You are within budget");
}
}
public View.OnClickListener saveButtonListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(budgetEntered.getText().length()>0)
{
budgetString = budgetEntered.getText().toString();
}
}
};
public void onClick(View v)
{
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void afterTextChanged(Editable s)
{
this it the best way to store and load value in Android:
save values: (put this where you want to save the values, for example in the onStop or onPause method. Or, in your case, in the onClick method)
SharedPreferences settings = getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("testValue", value);
editor.commit();
load values:
SharedPreferences settings = getSharedPreferences("MyPref", 0);
value = settings.getInt("testValue", defValue);
Related
I'm making a truth or dare app and i need a code that show the user input one by one every time i hit a button
I try somethink i watch in youtube.
So here's the activity that the user input names for the players playing.
public class NameInput1Activity extends AppCompatActivity {
Button SBtn;
Button RTMBtn;
EditText PN1;
EditText PN2;
EditText PN3;
EditText PN4;
EditText PN5;
EditText PN6;
EditText PN7;
EditText PN8;
EditText PN9;
EditText PN10;
String PI1;
String PI2;
String PI3;
String PI4;
String PI5;
String PI6;
String PI7;
String PI8;
String PI9;
String PI10;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name_input1);
SBtn = findViewById(R.id.SBtn);
RTMBtn = findViewById(R.id.RTMBtn);
PN1 = findViewById(R.id.player1NameInput);
PN2 = findViewById(R.id.player2NameInput);
PN3 = findViewById(R.id.player3NameInput);
PN4 = findViewById(R.id.player4NameInput);
PN5 = findViewById(R.id.player5NameInput);
PN6 = findViewById(R.id.player6NameInput);
PN7 = findViewById(R.id.player7NameInput);
PN8 = findViewById(R.id.player8NameInput);
PN9 = findViewById(R.id.player9NameInput);
PN10 = findViewById(R.id.player10NameInput);
SBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent PlayConf = new Intent(NameInput1Activity.this,PlayConf.class);
PI1 = PN1.getText().toString();
PI2 = PN2.getText().toString();
PI3 = PN3.getText().toString();
PI4 = PN4.getText().toString();
PI5 = PN5.getText().toString();
PI6 = PN6.getText().toString();
PI7 = PN7.getText().toString();
PI8 = PN8.getText().toString();
PI9 = PN9.getText().toString();
PI10 = PN10.getText().toString();
PlayConf.putExtra("Player1",PI1);
PlayConf.putExtra("Player2",PI2);
PlayConf.putExtra("Player3",PI3);
PlayConf.putExtra("Player4",PI4);
PlayConf.putExtra("Player5",PI5);
PlayConf.putExtra("Player6",PI6);
PlayConf.putExtra("Player7",PI7);
PlayConf.putExtra("Player8",PI8);
PlayConf.putExtra("Player9",PI9);
PlayConf.putExtra("Player10",PI10);
startActivity(PlayConf);
}
});
RTMBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent RTMBtn = new Intent(NameInput1Activity.this, MainActivity.class);
PN1.setText("");
PN1.setHint("Enter a name");
PN2.setText("");
PN2.setHint("Enter a name");
PN3.setText("");
PN3.setHint("Enter a name");
PN4.setText("");
PN4.setHint("Enter a name");
PN5.setText("");
PN5.setHint("Enter a hint");
PN6.setText("");
PN6.setHint("Enter a hint");
PN7.setText("");
PN7.setHint("Enter a hint");
PN8.setText("");
PN8.setHint("Enter a hint");
PN9.setText("");
PN9.setHint("Enter a hint");
PN10.setText("");
PN10.setHint("Enter a hint");
startActivity(RTMBtn);
}
});
}
}
So i have some 'edittext' that the player input the names and a 'OnClickListener' that passe's the input to 'PlayConf' Activity.
That's the 'PlayConf' Activity:
public class PlayConf extends AppCompatActivity {
Button AddMoreBtn;
Button MoveToToD;
Button RTMBtn;
String PI1;
String PI2;
String PI3;
String PI4;
String PI5;
String PI6;
String PI7;
String PI8;
String PI9;
String PI10;
TextView PTV1;
TextView PTV2;
TextView PTV3;
TextView PTV4;
TextView PTV5;
TextView PTV6;
TextView PTV7;
TextView PTV8;
TextView PTV9;
TextView PTV10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.example.myapplication.R.layout.activity_play_conf);
AddMoreBtn = findViewById(R.id.AddMoreBtn);
MoveToToD = findViewById(R.id.MoveToToD);
RTMBtn =findViewById(R.id.RTMBtn);
PTV1 = findViewById(R.id.Player1NameConf);
PTV2 = findViewById(R.id.Player2NameConf);
PTV3 = findViewById(R.id.Player3NameConf);
PTV4 = findViewById(R.id.Player4NameConf);
PTV5 = findViewById(R.id.Player5NameConf);
PTV6 = findViewById(R.id.Player6NameConf);
PTV7 = findViewById(R.id.Player7NameConf);
PTV8 = findViewById(R.id.Player8NameConf);
PTV9 = findViewById(R.id.Player9NameConf);
PTV10 = findViewById(R.id.Player10NameConf);
PI1 = getIntent().getExtras().getString("Player1");
PI2 = getIntent().getExtras().getString("Player2");
PI3 = getIntent().getExtras().getString("Player3");
PI4 = getIntent().getExtras().getString("Player4");
PI5 = getIntent().getExtras().getString("Player5");
PI6 = getIntent().getExtras().getString("Player6");
PI7 = getIntent().getExtras().getString("Player7");
PI8 = getIntent().getExtras().getString("Player8");
PI9 = getIntent().getExtras().getString("Player9");
PI10 = getIntent().getExtras().getString("Player10");
PTV1.setText(PI1);
PTV2.setText(PI2);
PTV3.setText(PI3);
PTV4.setText(PI4);
PTV5.setText(PI5);
PTV6.setText(PI6);
PTV7.setText(PI7);
PTV8.setText(PI8);
PTV9.setText(PI9);
PTV10.setText(PI10);
AddMoreBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent AddMore = new Intent(PlayConf.this,
NameInput1Activity.class);
startActivity(AddMore);
}
});
RTMBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent RTMBtn = new Intent(PlayConf.this, MainActivity.class);
PTV1.setText("");
PTV2.setText("");
PTV3.setText("");
PTV4.setText("");
PTV5.setText("");
PTV6.setText("");
PTV7.setText("");
PTV8.setText("");
PTV9.setText("");
PTV10.setText("");
startActivity(RTMBtn);
}
});
MoveToToD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent MoveToToD = new Intent(PlayConf.this, TruthOrDare.class);
MoveToToD.putExtra("Player1",PI1);
MoveToToD.putExtra("Player1",PI2);
MoveToToD.putExtra("Player1",PI3);
MoveToToD.putExtra("Player1",PI4);
MoveToToD.putExtra("Player1",PI5);
MoveToToD.putExtra("Player1",PI6);
MoveToToD.putExtra("Player1",PI7);
MoveToToD.putExtra("Player1",PI8);
MoveToToD.putExtra("Player1",PI9);
MoveToToD.putExtra("Player1",PI10);
startActivity(MoveToToD);
}
});
}
}
That's the 'PlayConf' Activity, it shows the input so the user see all the input's he enter.So i get the input from the previous Activity 'NameInput1Activity' and make another String from the input 'PI1'.Then i pass the input to the 'TruthOrDare' Activity with the Button 'MoveToToD'.
So that's where i have the problem the 'Truth or Dare' Activity:
public class TruthOrDare extends AppCompatActivity {
String PI1;
String PI2;
String PI3;
String PI4;
String PI5;
String PI6;
String PI7;
String PI8;
String PI9;
String PI10;
TextView PlayerView;
Integer TurnCount = 1;
Button RTMBtn;
Button Darebtn;
Button Truthbtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_truth_or_dare);
PI1 = getIntent().getExtras().getString("Player1");
PI2 = getIntent().getExtras().getString("Player2");
PI3 = getIntent().getExtras().getString("Player3");
PI4 = getIntent().getExtras().getString("Player4");
PI5 = getIntent().getExtras().getString("Player5");
PI6 = getIntent().getExtras().getString("Player6");
PI7 = getIntent().getExtras().getString("Player7");
PI8 = getIntent().getExtras().getString("Player8");
PI9 = getIntent().getExtras().getString("Player9");
PI10 = getIntent().getExtras().getString("Player10");
PlayerView = findViewById(R.id.PlayerNameTextView);
RTMBtn = findViewById(R.id.RTMBtn);
RTMBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent RTMBtn = new Intent(TruthOrDare.this, MainActivity.class);
startActivity(RTMBtn);
}
});
Truthbtn = findViewById(R.id.TruthBtn);
Darebtn = findViewById(R.id.Darebtn);
Truthbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent Truth = new Intent(TruthOrDare.this, TruthActivity.class);
TurnCount++;
startActivity(Truth);
}
});
Darebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TurnCount++;
}
});
}
public void ResetCount(View view) {
TurnCount = 1;
}
public void TurnCountIfElse(View view) {
if (TurnCount == 1) {
PlayerView.setText(PI1);
} else if (TurnCount == 2) {
PlayerView.setText(PI2);
} else if (TurnCount == 3) {
PlayerView.setText(PI3);
} else if (TurnCount == 4) {
PlayerView.setText(PI4);
} else if (TurnCount == 5) {
PlayerView.setText(PI5);
} else if (TurnCount == 6) {
PlayerView.setText(PI6);
} else if (TurnCount == 7) {
PlayerView.setText(PI7);
} else if (TurnCount == 8) {
PlayerView.setText(PI8);
} else if (TurnCount == 9) {
PlayerView.setText(PI9);
} else if (TurnCount == 10) {
PlayerView.setText(PI10);
}
else {
TurnCount = 1;
}
}
}
So what i do here is i make an 'onclicklistener' for the 'Truthbtn'
that add 1 to 'TurnCount' so the when i click the 'TurnCount' Value equals 2
so is set the textview to 'PI2' but instead of that it goes to the last 'else if' and set textview text to 'PI10'
IF YOU NEED ANY OTHER INFO LIKE XML'S JUST SAY IT PLS.
Dear Friend You made minor mistake during implementation. You send Same key value During intent on MoveToToD Button Click.
You use Same key Value Player1 for all player list value.That's the actual problem.So kindly Change Your MoveToToD click method and Write Below Code.
MoveToToD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent MoveToToD = new Intent(PlayConf.this, TruthOrDare.class);
MoveToToD.putExtra("Player1",PI1);
MoveToToD.putExtra("Player2",PI2);
MoveToToD.putExtra("Player3",PI3);
MoveToToD.putExtra("Player4",PI4);
MoveToToD.putExtra("Player5",PI5);
MoveToToD.putExtra("Player6",PI6);
MoveToToD.putExtra("Player7",PI7);
MoveToToD.putExtra("Player8",PI8);
MoveToToD.putExtra("Player9",PI9);
MoveToToD.putExtra("Player10",PI10);
startActivity(MoveToToD);
}
});
Check updates below.
I am making an app for a stair climbing challenge that tracks the date and number of steps taken (user input, not automatic). I have an ArrayList that stored objects containing the following three variables:
String date
Int steps
Instant timeStamp
The app has two input buttons, one for integer step input, and one for date selection. There is a simple method created to filter the visible list by the selected date and a couple of visual indicators of your daily progress vs. the daily goal for flights of stairs for the day.
App screenshot
I am using the Instant variable as a timestamp to try to get around the issue of the OnClickListener selecting the position of the item from the filtered list instead of the corresponding item in the unfiltered list. I do this by using the position reported from the OnClickListener to fetch the timeStamp variable from the associated item in the filtered ArrayList, then compare that timeStamp to the items in the unfiltered ArrayList and fetch the indexOf the matching item.
All filtered ArrayLists show properly in the RecyclerView when you select a date.
The problem comes in removing items. If I add items only to one date, then you can remove and add items as you'd expect.
App function without date change (gif)
If I add to one date, then another, while they display properly, the items will be removed from the correct position but in the date you first added items, regardless of whether that is the currently selected date or not.
App function with changing date (gif)
I feel like I'm missing something relatively simple here and my brain is just too saturated with this project to see it.
Main Activity:
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ExampleAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
Date temp_curr_date = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String sel_date = df.format(temp_curr_date);
String curr_date = df.format(temp_curr_date);
double daily_total;
int progress = 0;
double daily_goal = 7.5;
TextView textView1;
TextView textView2;
TextView textViewFlights;
ProgressBar pb;
List<ExampleItem> mExampleList;
List<ExampleItem> filteredList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ----- LOAD SAVED ARRAY LIST -----
loadData();
// ----- SET VARIABLES -----
daily_total = totalOutput(mExampleList, sel_date);
textView1 = findViewById(R.id.total);
textView1.setText(String.valueOf(daily_total));
textViewFlights = findViewById(R.id.flights);
pb = findViewById(R.id.progress_bar);
pb.setProgress(getProgress(mExampleList, sel_date), true);
// ----- BUILD RECYCLERVIEW -----
buildRecyclerView();
filter(sel_date);
// ----- ADD STEPS DIALOGUE -----
setAddStepButton();
// ----- CALENDAR DIALOGUE -----
setDateChangeButton();
}
public double totalOutput(List<ExampleItem> steps, String date) {
try{
int temp_total = 0;
double flight_total;
for (int a = 0; a < steps.size(); a++) {
if (date.equals(steps.get(a).getText1()))
temp_total += steps.get(a).getText2();
}
flight_total = round(temp_total / 16.0, 2);
return flight_total;
} catch (Exception e){
return 0.0;
}
}
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
public static int toInt(double value) {
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(0, RoundingMode.HALF_UP);
return bd.intValue();
}
public static Date getDate(int year, int month, int day) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, day);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
private void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(mExampleList);
editor.putString("task list", json);
editor.apply();
}
private void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list", null);
Type type = new TypeToken<ArrayList<ExampleItem>>() {}.getType();
mExampleList = gson.fromJson(json, type);
if (mExampleList == null){
mExampleList = new ArrayList<>();
}
}
private int getProgress(List<ExampleItem> steps, String date){
int daily_progress_int;
try{
int temp_progress = 0;
double flight_total;
for (int a = 0; a < steps.size(); a++) {
if (date.compareTo(steps.get(a).getText1()) == 0)
temp_progress += steps.get(a).getText2();
}
flight_total = round(temp_progress / 16.0, 2);
daily_progress_int = toInt((flight_total/daily_goal)*100);
return daily_progress_int;
} catch (Exception e){
return 0;
}
}
private void addProgress(double x, int prog){
int daily_progress_int = toInt((x/daily_goal)*100);
if (progress <= 100-daily_progress_int){
progress = progress + prog;
pb = findViewById(R.id.progress_bar);
pb.setProgress(daily_progress_int, true);
} else if (progress + daily_progress_int > 100){
pb = findViewById(R.id.progress_bar);
pb.setProgress(100, true);
}
}
private void removeProgress(double x, int prog){
int daily_progress_int = toInt((x/daily_goal)*100);
progress = progress - prog;
if (progress <= 100) {
pb = findViewById(R.id.progress_bar);
pb.setProgress(daily_progress_int, true);
} else {
pb = findViewById(R.id.progress_bar);
pb.setProgress(0, true);
}
}
public void addItem(String date, int steps, Instant ts){
mExampleList.add(new ExampleItem(date, steps, ts));
filter(sel_date);
}
public void removeItem(final int position){
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
View viewInflated = LayoutInflater.from(MainActivity.this).inflate(R.layout.confirm, (ViewGroup) findViewById(android.R.id.content), false);
builder.setCancelable(true);
builder.setView(viewInflated);
builder.setPositiveButton("Yup",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mExampleList.remove(position);
mAdapter.notifyDataSetChanged(position);
filter(sel_date);
daily_total = totalOutput(mExampleList, sel_date);
textView1 = findViewById(R.id.total);
textView1.setText(String.valueOf(daily_total));
removeProgress(daily_total,progress);
if (daily_total == 1.0){
textViewFlights.setText("flight");
} else {
textViewFlights.setText("flights");
}
saveData();
}
});
builder.setNegativeButton("Nope", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
public void buildRecyclerView(){
mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new ExampleAdapter(mExampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new ExampleAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
Instant test = filteredList.get(position).getTimeStamp();
for (ExampleItem item : mExampleList){
if (test.compareTo(item.getTimeStamp()) == 0){
removeItem(mExampleList.indexOf(item));
}
});
}
public void filter(String text){
filteredList = new ArrayList<>();
for (ExampleItem item : mExampleList){
if (item.getText1().toLowerCase().contains(text.toLowerCase())){
filteredList.add(item);
}
}
mAdapter.filterList(filteredList);
}
public void setAddStepButton(){
FloatingActionButton fab = findViewById(R.id.addSteps);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
View viewInflated = LayoutInflater.from(MainActivity.this).inflate(R.layout.add_steps, (ViewGroup) findViewById(android.R.id.content), false);
// Step input
final EditText input = viewInflated.findViewById(R.id.input);
builder.setView(viewInflated);
// OK Button
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (input.getText().length() != 0) {
try {
int in = Integer.parseInt(String.valueOf(input.getText()));
if (in > 0) {
Instant timeStamp = Instant.now();
addItem(sel_date, in, timeStamp);
dialog.dismiss();
} else {
dialog.cancel();
}
} catch (Exception e) {
dialog.cancel();
}
daily_total = totalOutput(mExampleList, sel_date);
textView1 = findViewById(R.id.total);
textView1.setText(String.valueOf(daily_total));
addProgress(daily_total, progress);
mAdapter.notifyDataSetChanged();
filter(sel_date);
if (daily_total == 1.0){
textViewFlights.setText("flight");
} else {
textViewFlights.setText("flights");
}
saveData();
} else{
dialog.cancel();
}
}
});
// Cancel Button
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
});
}
public void setDateChangeButton(){
FloatingActionButton fabcal = findViewById(R.id.calendarButton);
fabcal.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout ll= (LinearLayout)inflater.inflate(R.layout.calendar, null, false);
CalendarView cv = (CalendarView) ll.getChildAt(0);
long milliseconds = 0;
try {
Date d = df.parse(sel_date);
milliseconds = d.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
cv.setDate(milliseconds);
cv.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(
#NonNull CalendarView view,
int year,
int month,
int dayOfMonth)
{
Date temp_sel_date = getDate(year, month, dayOfMonth);
sel_date = df.format(temp_sel_date);
textView2 = findViewById(R.id.daily_total);
if (sel_date.equals(curr_date)){
textView2.setText("Today");
} else {
String dt_day = (String) DateFormat.format("dd", temp_sel_date);
String dt_month = (String) DateFormat.format("MMM", temp_sel_date);
textView2.setText(dt_month + " " + dt_day);
}
daily_total = totalOutput(mExampleList, sel_date);
textView1 = findViewById(R.id.total);
textView1.setText(String.valueOf(daily_total));
pb = findViewById(R.id.progress_bar);
pb.setProgress(getProgress(mExampleList, sel_date), true);
mAdapter.notifyDataSetChanged();
filter(sel_date);
}
});
new AlertDialog.Builder(MainActivity.this)
.setView(ll)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
).show();
}
});
}
}
Adapter Class:
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private static List<ExampleItem> mExampleList;
private static List<ExampleItem> exampleListFull;
private OnItemClickListener mListener;
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView1;
public ImageView mDeleteImage;
public ExampleViewHolder(View itemView, final OnItemClickListener listener) {
super(itemView);
mTextView1 = itemView.findViewById(R.id.textView);
mDeleteImage = itemView.findViewById(R.id.image_delete);
mDeleteImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
Instant test = mExampleList.get(position).getTimeStamp();
for (ExampleItem item : exampleListFull){
int compare = test.compareTo(item.getTimeStamp());
if (compare == 0){
int delIndex = exampleListFull.indexOf(item);
position = delIndex;
}
}
listener.onItemClick(position);
}
}
}
});
}
}
public ExampleAdapter(List<ExampleItem> exampleList){
this.mExampleList = exampleList;
exampleListFull = new ArrayList<>(exampleList);
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v, mListener);
return evh;
}
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
if (currentItem.getText2() == 1.0){
holder.mTextView1.setText(currentItem.getText2() + " step");
} else {
holder.mTextView1.setText(currentItem.getText2() + " steps");
}
}
#Override
public int getItemCount() {
return mExampleList.size();
}
public void filterList(List<ExampleItem> filteredList){
mExampleList = filteredList;
notifyDataSetChanged();
}
}
If anyone out there has any ideas, I'd love to hear from you!
UPDATE: The included code now reflects the changes suggested by users and is fully functional.
You should use
mAdapter.notifyDataSetChanged();
Instead of
mAdapter.notifyItemRemoved(position);
For more details Visit
this.
I figured it out, for those interested. Comparing the timestamps was working fine, but I put it in the wrong part of the OnClickListener cycle. It needed to be placed in the MainActivity buildRecyclerView method in the setOnClickListener override. I've updated original code to reflect this change.
Thank you anyone that took the time to look at my post.
maybe it could be better to place the onClickListner in Your adpater-class..so You can control every single card if it should be clickable or not...or if You want to place any Ads between the cards
GGK
I am new to Android Studio. I have gone through the official developer.android.com training and I decided to create a new and simple app called Grocery+ in which user will enter the price and quantity of particular item and app will display total sum.
I have done all UI based work then today I switched to programming. I am an experienced programmer of Java. I have also done all the work in it but:
1- my app crashes when I try to enter the first .
Then I have to enter any other value first then first value.
2- even after above hack my app doesn't display anything on 'grand total
Plese help :(((
package com.amostrone.akash.grocery;
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
static int Quantity[] = new int[4];
static float Price[] = new float[4];
public static double total=0;
static TextView txtValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtValue = (TextView) findViewById(R.id.txtExample);
}
/////////// QUANTITY
public void input_Quantity(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity);
calc();
}
public void input_Quantity2(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity2);
Quantity[1] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity3(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity3);
Quantity[2] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity4(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity4);
Quantity[3] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity5(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity5);
Quantity[4] = Integer.parseInt(x.toString());
calc();
}
/////////////// Quantity
////////////// Price
public void input_Price(View view) {
EditText x = (EditText) findViewById(R.id.editPrice);
Price[0] = Float.parseFloat(x.toString());
calc();
}
public void input_Price2(View view) {
EditText x = (EditText) findViewById(R.id.editPrice2);
Price[1] = Float.parseFloat(x.toString());
calc();
}
public void input_Price3(View view) {
EditText x = (EditText) findViewById(R.id.editPrice3);
Price[2] = Float.parseFloat(x.toString());
calc();
}
public void input_Price4(View view) {
EditText x = (EditText) findViewById(R.id.editPrice4);
Price[3] = Float.parseFloat(x.toString());
calc();
}
public void input_Price5(View view) {
EditText x = (EditText) findViewById(R.id.editPrice5);
calc();
}
///////////// Price
/////////////// Calculate
public static void calc()
{
for(int i=0;i<=4;i++)
total += (Quantity[i] * Price[i]);
String str = Double.toString(total);
txtValue.setText(str);
}
////////////// Calculate }
Looking at your code it appears your are triggering EditText value get and calculation on click event (via xml). This does not work this way as they are triggered immediately. One of the approaches to solve this problem is to go the TextWatcher route. Check the below code built around that, I also refactored it a bit (should be lesser prone to memory leaks now):
public double mTotal;
private TextView mTextView;
private EditText[] mQuantityEditTexts = new EditText[5];
private EditText[] mPriceEditTexts = new EditText[5];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.txtExample);
mQuantityEditTexts[0] = (EditText) findViewById(R.id.editQuantity);
mQuantityEditTexts[1] = (EditText) findViewById(R.id.editQuantity2);
mQuantityEditTexts[2] = (EditText) findViewById(R.id.editQuantity3);
mQuantityEditTexts[3] = (EditText) findViewById(R.id.editQuantity4);
mQuantityEditTexts[4] = (EditText) findViewById(R.id.editQuantity5);
mPriceEditTexts[0] = (EditText) findViewById(R.id.editPrice);
mPriceEditTexts[1] = (EditText) findViewById(R.id.editPrice2);
mPriceEditTexts[2] = (EditText) findViewById(R.id.editPrice3);
mPriceEditTexts[3] = (EditText) findViewById(R.id.editPrice4);
mPriceEditTexts[4] = (EditText) findViewById(R.id.editPrice5);
for (int i = 0; i < 5; i++) {
mQuantityEditTexts[i].addTextChangedListener(mTextWatcher);
mPriceEditTexts[i].addTextChangedListener(mTextWatcher);
}
}
private TextWatcher mTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
calc();
}
#Override
public void afterTextChanged(Editable s) {
}
};
public void calc()
{
try {
for (int i = 0; i <= 4; i++)
mTotal += Integer.parseInt(mQuantityEditTexts[i].getText().toString()) *
Double.parseDouble(mPriceEditTexts[i].getText().toString());
String str = Double.toString(mTotal);
mTextView.setText(str);
} catch (NumberFormatException e) {
Toast.makeText(this, "WTF! Enter valid numbers!", Toast.LENGTH_SHORT).show();
}
}
I have created custom edittext which does not hangs.
SearchTimerEditText
I am creating a coffee ordering app for school. My intent for the code below is to increment or decrement the coffee integer based on whether the subtractCoffeeButton or addCoffeeButton is clicked. coffeeTV is used to show the user the number of coffee's queued to be ordered. subtotal and subtotalTV are used to hold the price and display it to the user.
As it is, the subtractCoffee and addCoffee buttons work to increment coffee and coffeeTV from 0 to 1 and vise-versa, subtotal and subtotalTV also work for displaying 0.00 and 2.5, but it won't increment any further than that. Further button clicks result in nothing happening when it is expected to increment coffee to 2,3,4,etc. and subtotal to 5.00,7.50,10.00,etc.
Code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_relative);
Button subtractCoffee = (Button) findViewById(R.id.subtractCoffeeButton);
subtractCoffee.setOnClickListener(this);
Button addCoffee = (Button) findViewById(R.id.addCoffeeButton);
addCoffee.setOnClickListener(this);
}
#Override
public void onClick(View v) {
double subtotal = 0.00;
int coffee = 0;
double coffeePrice = 2.50;
TextView coffeeTV = (TextView) findViewById(R.id.tvCoffeeOrder);
String coffeeString = coffeeTV.getText().toString();
int coffeeTracker = Integer.parseInt(coffeeString);
TextView subTotalTV = (TextView) findViewById(R.id.tvSubtotalCost);
switch (v.getId()) {
case R.id.subtractCoffeeButton:
if (coffeeTracker == 0) {
break;
} else if (coffeeTracker == 1) {
coffee = 0;
coffeeTracker = 0;
coffeeTV.setText(Integer.toString(coffee));
break;
} else {
coffee = coffee - 1;
coffeeTV.setText(Integer.toString(coffee));
subtotal = subtotal - coffeePrice;
subTotalTV.setText(Double.toString(subtotal));
}
break;
case R.id.addCoffeeButton:
coffee += 1;
coffeeTracker+=1;
coffeeTV.setText(Integer.toString(coffee));
subtotal = subtotal + coffeePrice;
subTotalTV.setText(Double.toString(subtotal));
break;
}
}
#Override
public void onClick(View v) {
double subtotal = 0.00;
int coffee = 0;
double coffeePrice = 2.50;
These variables have to be outside the onClick method.
Everytime you call onClick they get initiated again with 0.
because
double subtotal = 0.00;
int coffee = 0;
double coffeePrice = 2.50;
are in the local scope of your method. Declare as member variable and their value will persist as long as the current Activity is not destroyed
The problem is that you have
double subtotal = 0.00;
int coffee = 0;
at the beginning of your onClick() function. Thus, every time you click a button, you reset the number to 0 and then increment it to 1.
Besides, I'd recommend you to define separate OnClickListener instead of a global one. Something like:
public class MainActivity extends AppCompatActivity {
AppWidgetManager appWidgetManager;
SharedPreferences preferences;
SharedPreferences.Editor editor;
InputMethodManager inputMethodManager;
EditText mainEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ActivityManager.TaskDescription taskDescription =
new ActivityManager.TaskDescription(null, null, getResources().getColor(R.color.primaryDark));
setTaskDescription(taskDescription);
getWindow().setNavigationBarColor(getResources().getColor(R.color.primary));
}
appWidgetManager = AppWidgetManager.getInstance(this);
inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
editor = preferences.edit();
String savedText = preferences.getString("mainText", "");
mainEditText = (EditText) findViewById(R.id.mainEditText);
mainEditText.setMovementMethod(new ScrollAndSelectMovingMethod());
mainEditText.getText().append(savedText);
Selection.setSelection(mainEditText.getText(), savedText.length());
mainEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
inputMethodManager.showSoftInput(mainEditText, InputMethodManager.SHOW_IMPLICIT);
}
});
mainEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
onEditTextTextChanged(charSequence.toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
#Override
public void onBackPressed() {
finish();
}
private void onEditTextTextChanged(String text) {
saveText(text);
updateWidget();
}
private void saveText(String text) {
editor.putString("mainText", text);
editor.commit();
}
private void updateWidget() {
int[] ids = appWidgetManager.getAppWidgetIds(new ComponentName(this, Widget.class));
for (int id : ids)
Widget.updateAppWidget(appWidgetManager, id);
}
}
As already said subtotal, coffe and coffePrice need to be outside of the onClick function. Also coffeTracker should always be the same as coffe as far as I can see, so you dont need the variable
This should be your code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
double subtotal = 0.00;
int coffee = 0;
double coffeePrice = 2.50;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_relative);
Button subtractCoffee = (Button) findViewById(R.id.subtractCoffeeButton);
subtractCoffee.setOnClickListener(this);
Button addCoffee = (Button) findViewById(R.id.addCoffeeButton);
addCoffee.setOnClickListener(this);
}
#Override
public void onClick(View v) {
TextView coffeeTV = (TextView) findViewById(R.id.tvCoffeeOrder);
TextView subTotalTV = (TextView) findViewById(R.id.tvSubtotalCost);
switch (v.getId()) {
case R.id.subtractCoffeeButton:
if (coffee == 0) {
break;
} else if (coffee == 1) {
coffee = 0;
coffeeTV.setText(Integer.toString(coffee));
break;
} else {
coffee = coffee - 1;
coffeeTV.setText(Integer.toString(coffee));
subtotal = subtotal - coffeePrice;
subTotalTV.setText(Double.toString(subtotal));
}
break;
case R.id.addCoffeeButton:
coffee += 1;
coffeeTV.setText(Integer.toString(coffee));
subtotal = subtotal + coffeePrice;
subTotalTV.setText(Double.toString(subtotal));
break;
}
}
Either you go with the other answers approach (field variables) or you read and parse the amounts on each onClick(). In code it would look something like:
static final double COFFEE_PRICE = 2.50;
#Override
public void onClick(View v) {
TextView coffeeTV = (TextView) findViewById(R.id.tvCoffeeOrder);
String coffeeString = coffeeTV.getText().toString();
int coffee = Integer.parseInt(coffeeString);
TextView subtotalTV = (TextView) findViewById(R.id.tvSubtotalCost);
String subtotalString = subtotalTV.getText().toString();
double subtotal = Double.parseDouble(subtotalString);
switch (v.getId()) {
case R.id.subtractCoffeeButton:
if (coffee == 0) {
break;
}
coffee--;
subtotal -= COFFEE_PRICE;
coffeeTV.setText(Integer.toString(coffee));
subtotalTV.setText(Double.toString(subtotal));
break;
case R.id.addCoffeeButton:
coffee++;
subtotal += COFFEE_PRICE;
coffeeTV.setText(Integer.toString(coffee));
subtotalTV.setText(Double.toString(subtotal));
break;
}
}
I have to develop one shopping cart app and integrate Paypal. How can I set the Paypal payment invoice data?
How can I add productname, quantity, price to Paypal payment invoice?.
This is my code for product that is added to cart page:
public class SingleMenuItem extends Activity {
static final String KEY_TITLE = "Name";
static final String KEY_COST = "Price";
static final String KEY_TOTAL = "total";
static final String KEY_QTY = "qty";
static final String KEY_THUMB_URL = "Image";
private EditText edit_qty_code;
private TextView txt_total;
private TextView text_cost_code;
private double itemamount = 0;
private double itemquantity = 0;
String mTitle, mQty, mCost, mTotal;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single);
Intent in = getIntent();
String title = in.getStringExtra(KEY_TITLE);
String thumb_url = in.getStringExtra(KEY_THUMB_URL);
String cost = in.getStringExtra(KEY_COST);
String total = in.getStringExtra(KEY_TOTAL);
ImageLoader imageLoader = new ImageLoader(getApplicationContext());
ImageView imgv = (ImageView) findViewById(R.id.single_thumb);
final TextView txttitle = (TextView) findViewById(R.id.single_title);
TextView txtheader = (TextView) findViewById(R.id.actionbar);
text_cost_code = (TextView) findViewById(R.id.single_cost);
edit_qty_code = (EditText) findViewById(R.id.single_qty);
edit_qty_code.setText("1");
txt_total = (TextView) findViewById(R.id.single_total);
txttitle.setText(title);
txtheader.setText(title);
text_cost_code.setText(cost);
txt_total.setText(total);
imageLoader.DisplayImage(thumb_url, imgv);
itemamount = Double.parseDouble(text_cost_code.getText().toString());
txt_total.setText(Double.toString(itemamount));
edit_qty_code.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
if (!edit_qty_code.getText().toString().equals("")
|| !edit_qty_code.getText().toString().equals("")) {
itemquantity = Double.parseDouble(edit_qty_code.getText()
.toString());
itemamount = Double.parseDouble(text_cost_code.getText()
.toString());
txt_total.setText(Double
.toString(itemquantity * itemamount));
} else {
txt_total.setText("0.00");
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
}
});
ImageButton mImgAddCart = (ImageButton) findViewById(R.id.img_add);
mImgAddCart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mTitle = txttitle.getText().toString();
mCost = text_cost_code.getText().toString();
mCost = mCost.replace("From ", "");
mTotal = txt_total.getText().toString();
mTotal = mTotal.replace("From ", "");
mQty = edit_qty_code.getText().toString();
if (Constants.mItem_Detail.size() <= 0) {
HashMap<String, String> mTempObj = new HashMap<String, String>();
mTempObj.put(KEY_TITLE, mTitle);
mTempObj.put(KEY_QTY, mQty);
mTempObj.put(KEY_COST, mCost);
mTempObj.put(KEY_TOTAL, mTotal);
Constants.mItem_Detail.add(mTempObj);
} else {
for (int i = 0; i < Constants.mItem_Detail.size(); i++) {
if (Constants.mItem_Detail.get(i).get(KEY_TITLE)
.equals(mTitle)) {
Constants.mItem_Detail.remove(i);
break;
} else {
}
}
HashMap<String, String> mTempObj = new HashMap<String, String>();
mTempObj.put(KEY_TITLE, mTitle);
mTempObj.put(KEY_QTY, mQty);
mTempObj.put(KEY_COST, mCost);
mTempObj.put(KEY_TOTAL, mTotal);
Constants.mItem_Detail.add(mTempObj);
}
AlertDialog.Builder alertdialog = new AlertDialog.Builder(
SingleMenuItem.this);
alertdialog.setTitle(getResources()
.getString(R.string.app_name));
alertdialog.setMessage("Add in ViewCart");
alertdialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
//finish();
return;
}
});
alertdialog.show();
}
});
ImageButton mImgViewCart = (ImageButton) findViewById(R.id.img_view);
mImgViewCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent mInViewCart = new Intent(SingleMenuItem.this,
ViewCartActivity.class);
startActivity(mInViewCart);
}
});
This is code for product is added to cart:
ListView mLstView1 = (ListView) findViewById(R.id.listView1);
TextView mTxtViewGrandTotal = (TextView) findViewById(R.id.mTxtViewGrandTotalValue);
Button mBtnSubmit = (Button) findViewById(R.id.mBtnSubmit);
ViewCartAdapter mViewCartAdpt = new ViewCartAdapter(
ViewCartActivity.this);
mLstView1.setAdapter(mViewCartAdpt);
if (Constants.mItem_Detail.size() > 0) {
Double mGTotal = Double.parseDouble(Constants.mItem_Detail.get(0)
.get(SingleMenuItem.KEY_TOTAL));
for (int i = 1; i < Constants.mItem_Detail.size(); i++) {
mGTotal = mGTotal
+ Double.parseDouble(Constants.mItem_Detail.get(i).get(
SingleMenuItem.KEY_TOTAL));
}
mGrandTotal = String.valueOf(mGTotal);
mTxtViewGrandTotal.setText("$" + mGrandTotal);
}
mBtnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), CustomerLogin.class);
startActivity(i);
}
});
This is my paypalintegrationactivity:
public class PayPalIntegrationActivity extends Activity implements OnClickListener {
private PayPal mPayPal;
private CheckoutButton launchPayPalButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay_pal_integration);
mPayPal=PayPal.initWithAppID(this,Constants.PAYPAL_APP_ID,PayPal.ENV_SANDBOX);
initUI();
}
private void initUI() {
launchPayPalButton = mPayPal.getCheckoutButton(this,
PayPal.BUTTON_278x43, CheckoutButton.TEXT_PAY);
RelativeLayout.LayoutParams params = new
RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
params.bottomMargin = 10;
launchPayPalButton.setLayoutParams(params);
launchPayPalButton.setOnClickListener(this);
((RelativeLayout)findViewById(R.id.main_layout)).addView(launchPayPalButton);
}
#Override
public void onClick(View v) {
payWithPaypal();
}
private PayPalPayment payWithPaypal() {
PayPalPayment newPayment = new PayPalPayment();
BigDecimal bigDecimal=new BigDecimal(10);
newPayment.setSubtotal(bigDecimal);
newPayment.setCurrencyType(Currency.getInstance(Locale.US));
newPayment.setRecipient("krishnaveni.veeman#mercuryminds.com");
newPayment.setMerchantName("My Merchant");
newPayment.setSubtotal(new BigDecimal(mTotal));
newPayment.setPaymentType(PayPal.PAYMENT_TYPE_GOODS);
Intent paypalIntent = PayPal.getInstance().checkout(newPayment, this);
this.startActivityForResult(paypalIntent, 1);
PayPalInvoiceData invoice = new PayPalInvoiceData();
return newPayment;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(resultCode) {
case Activity.RESULT_OK:
String payKey =
data.getStringExtra(PayPalActivity.EXTRA_PAY_KEY);
Toast.makeText(this,"Payment Successful",Toast.LENGTH_LONG).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(this,"Payment Cancel",Toast.LENGTH_LONG).show();
break;
case PayPalActivity.RESULT_FAILURE:
Toast.makeText(this,"Payment Failed",Toast.LENGTH_LONG).show();
String errorID =
data.getStringExtra(PayPalActivity.EXTRA_ERROR_ID);
String errorMessage =
data.getStringExtra(PayPalActivity.EXTRA_ERROR_MESSAGE);
break;
}
Here how can i add productname to paypalpayment invoice.please help me.
you can add paypalinvoice object to your project, then you can add details to that invoice,
try this code
PayPalInvoiceItem item1 = new PayPalInvoiceItem();
item1.setName("Pink Stuffed Bunny");
item1.setTotalPrice(new BigDecimal("6.00"));
item1.setQuantity(3);
invoice.getInvoiceItems().add(item1);
hope it will help to you.