How to pass checkbox values to an ACTION_SEND - java

I'm trying to do my first app, I'm self-taught in Java and I started 2 month ago so please forgive my errors.
I want to pass the CheckBoxes values to an email text but I think I need to refresh "something" before sending the email because the values are always false..and I don't know how can I do.
Here is the code:
public class Appuntamento extends Activity{
String paziente;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appuntamento);
//riceviamo id e lo mettiamo come nome utente
final EditText nomePaziente = (EditText)findViewById(R.id.nomePaziente);
Bundle dati = this.getIntent().getExtras();
nomePaziente.setText(dati.getString("id"));
final String id = dati.getString("id");
EditText noteAppuntamento = (EditText)findViewById(R.id.noteAppuntamento);
final String note = noteAppuntamento.getText().toString();
final CheckBox lunedi = (CheckBox) findViewById(R.id.checkboxLunedi);
final boolean lun = lunedi.isSelected();
final CheckBox martedi = (CheckBox) findViewById(R.id.checkboxMartedì);
final boolean mar = martedi.isSelected();
final CheckBox mercoledi = (CheckBox) findViewById(R.id.checkboxMercoledi);
final boolean mer = mercoledi.isSelected();
final CheckBox giovedi = (CheckBox) findViewById(R.id.checkboxGiovedi);
final boolean giov = giovedi.isSelected();
final CheckBox venerdi = (CheckBox) findViewById(R.id.checkboxVenerdi);
final boolean ven = venerdi.isSelected();
StringBuilder testoMail = new StringBuilder();
if (lun ){
testoMail.append("Lunedì");
} else if (mar){
testoMail.append("Martedì");
}else if (mer) {
testoMail.append("Mercoledì");
} else if (giov) {
testoMail.append("Giovedì");
} else if (ven) {
testoMail.append("Venerdì");
}
final String giorni = testoMail.toString();
Button richiestaAppuntamento = (Button)findViewById(R.id.btnRichiestaAppuntamento);
richiestaAppuntamento.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mail = new Intent(Intent.ACTION_SEND);
mail.setType("message/rfc822");
mail.putExtra(Intent.EXTRA_SUBJECT, "Richiesta appuntamento");
mail.putExtra(Intent.EXTRA_TEXT, "Nome paziente: " + id + " " + giorni + " " + "Note: " + note);
mail.putExtra(Intent.EXTRA_EMAIL, new String[] {"dottcastellitto#gmail.com"});
startActivity(mail);
}
});
}
}

two way you can do this one
like
public class Appuntamento extends Activity
{
String paziente;
boolean lun,mar ,mer,giov,ven;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appuntamento);
//riceviamo id e lo mettiamo come nome utente
final EditText nomePaziente = (EditText)findViewById(R.id.nomePaziente);
Bundle dati = this.getIntent().getExtras();
nomePaziente.setText(dati.getString("id"));
final String id = dati.getString("id");
EditText noteAppuntamento = (EditText)findViewById(R.id.noteAppuntamento);
final String note = noteAppuntamento.getText().toString();
final CheckBox lunedi = (CheckBox) findViewById(R.id.checkboxLunedi);
final CheckBox martedi = (CheckBox) findViewById(R.id.checkboxMartedì);
final CheckBox mercoledi =(CheckBox)findViewById(R.id.checkboxMercoledi);
final CheckBox giovedi = (CheckBox) findViewById(R.id.checkboxGiovedi);
final CheckBox venerdi = (CheckBox) findViewById(R.id.checkboxVenerdi);
Button richiestaAppuntamento = (Button) findViewById(R.id.btnRichiestaAppuntamento);
richiestaAppuntamento.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ven = venerdi.isChecked();
lun = lunedi.isChecked();
mar = martedi.isChecked();
mer = mercoledi.isChecked();
giov = giovedi.isChecked();
StringBuilder testoMail = new StringBuilder();
//your code this is fine if only one selected item info or data you want to send in mail
if (lun ){
testoMail.append("Lunedì");
} else if (mar){
testoMail.append("Martedì");
}else if (mer) {
testoMail.append("Mercoledì");
} else if (giov) {
testoMail.append("Giovedì");
} else if (ven) {
testoMail.append("Venerdì");
}
// if you want all then comment above code and uncomment below code
/*
if (lun ){
testoMail.append("Lunedì");
}
if (mar){
testoMail.append("Martedì");
}
if (mer) {
testoMail.append("Mercoledì");
}
if (giov) {
testoMail.append("Giovedì");
}
if (ven) {
testoMail.append("Venerdì");
}
*/
String giorni = testoMail.toString();
Intent mail = new Intent(Intent.ACTION_SEND);
mail.setType("message/rfc822");
mail.putExtra(Intent.EXTRA_SUBJECT, "Richiesta appuntamento");
mail.putExtra(Intent.EXTRA_TEXT, "Nome paziente: " + id + " " + giorni + " " + "Note: " + note);
mail.putExtra(Intent.EXTRA_EMAIL, new String[] {"dottcastellitto#gmail.com"});
startActivity(mail);
}
});
}
}
other way is
like
public class Appuntamento extends Activity
{
String paziente;
boolean lun,mar ,mer,giov,ven;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appuntamento);
//riceviamo id e lo mettiamo come nome utente
final EditText nomePaziente = (EditText)findViewById(R.id.nomePaziente);
Bundle dati = this.getIntent().getExtras();
nomePaziente.setText(dati.getString("id"));
final String id = dati.getString("id");
EditText noteAppuntamento = (EditText)findViewById(R.id.noteAppuntamento);
final String note = noteAppuntamento.getText().toString();
final CheckBox lunedi = (CheckBox) findViewById(R.id.checkboxLunedi);
lunedi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
lun=isChecked;
//either one above or below
//lun = lunedi.isChecked();
}
}
);
final CheckBox martedi = (CheckBox) findViewById(R.id.checkboxMartedì);
martedi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
mar=isChecked;
//either one above or below
//mar = martedi.isChecked();
}
}
);
final CheckBox mercoledi =(CheckBox)findViewById(R.id.checkboxMercoledi);
mercoledi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
mer=isChecked;
//either one above or below
// mer = mercoledi.isChecked();
}
}
);
final CheckBox giovedi = (CheckBox) findViewById(R.id.checkboxGiovedi);
giovedi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
giov=isChecked;
//either one above or below
// giov = giovedi.isChecked();
}
}
);
final CheckBox venerdi = (CheckBox) findViewById(R.id.checkboxVenerdi);
venerdi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
ven=isChecked;
//either one above or below
//ven = venerdi.isChecked();
}
}
);
Button richiestaAppuntamento = (Button) findViewById(R.id.btnRichiestaAppuntamento);
richiestaAppuntamento.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// ven = venerdi.isChecked();
// lun = lunedi.isChecked();
// mar = martedi.isChecked();
// mer = mercoledi.isChecked();
// giov = giovedi.isChecked();
StringBuilder testoMail = new StringBuilder();
//your code this is fine if only one selected item info or data you want to send in mail
if (lun ){
testoMail.append("Lunedì");
} else if (mar){
testoMail.append("Martedì");
}else if (mer) {
testoMail.append("Mercoledì");
} else if (giov) {
testoMail.append("Giovedì");
} else if (ven) {
testoMail.append("Venerdì");
}
// if you want all then comment above code and uncomment below code
/*
if (lun ){
testoMail.append("Lunedì");
}
if (mar){
testoMail.append("Martedì");
}
if (mer) {
testoMail.append("Mercoledì");
}
if (giov) {
testoMail.append("Giovedì");
}
if (ven) {
testoMail.append("Venerdì");
}
*/
String giorni = testoMail.toString();
Intent mail = new Intent(Intent.ACTION_SEND);
mail.setType("message/rfc822");
mail.putExtra(Intent.EXTRA_SUBJECT, "Richiesta appuntamento");
mail.putExtra(Intent.EXTRA_TEXT, "Nome paziente: " + id + " " + giorni + " " + "Note: " + note);
mail.putExtra(Intent.EXTRA_EMAIL, new String[] {"dottcastellitto#gmail.com"});
startActivity(mail);
}
});
}
}

Related

Why List for Recyclerview returning same items in all positions? [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 5 years ago.
In my android app, I am using recycler view to show items.
(Note: This is not a duplicate question because I tried many answers from stackoverflow but no solution.)
My Problem
The recycler view showing repeated items. A single item is repeating many times even though it occurs only single time in the source DB.
I checked for the reason and note that the List object in Adapter class returning same values in all iterations. But the Fragment that sends List object to adapter class having unique values.
But only the adapter class after receiving the List object contains duplicate items
Solutions I tried
I checked Stackoverflow and added getItemId(int position) and getItemViewType(int position) in adaptor class but no solution
I checked the DB and also List view sending class both dont have duplicate items.
My Code:
InboxHostFragment.java = This class sends List object to adaptor class of recycler view:
public class HostInboxFragment extends Fragment {
View hostinbox;
Toolbar toolbar;
ImageView archive, alert, search;
TextView blank;
Bundle args = new Bundle();
private static final String TAG = "Listinbox_host";
private InboxHostAdapter adapter;
String Liveurl = "";
RelativeLayout layout, host_inbox;
String country_symbol;
String userid;
String login_status, login_status1;
ImageButton back;
String roomid;
RecyclerView listView;
String name = "ramesh";
private int start = 1;
private List < ListFeed > movieList = new ArrayList < > ();
String currency1;
// RecyclerView recyclerView;
public HostInboxFragment() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#RequiresApi(api = Build.VERSION_CODES.M)
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
hostinbox = inflater.inflate(R.layout.fragment_host_inbox, container, false);
FontChangeCrawler fontChanger = new FontChangeCrawler(getContext().getAssets(), getString(R.string.app_font));
fontChanger.replaceFonts((ViewGroup) hostinbox);
SharedPreferences prefs = getActivity().getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE);
userid = prefs.getString("userid", null);
currency1 = prefs.getString("currenycode", null);
toolbar = (Toolbar) hostinbox.findViewById(R.id.toolbar);
archive = (ImageView) hostinbox.findViewById(R.id.archive);
alert = (ImageView) hostinbox.findViewById(R.id.alert);
search = (ImageView) hostinbox.findViewById(R.id.search);
blank = (TextView) hostinbox.findViewById(R.id.blank);
host_inbox = (RelativeLayout) hostinbox.findViewById(R.id.host_inbox);
layout.setVisibility(View.INVISIBLE);
start = 1;
final String url = Constants.DETAIL_PAGE_URL + "payment/host_reservation_inbox?userto=" + userid + "&start=" + start + "&common_currency=" + currency1;
//*******************************************ListView code start*****************************************************
System.out.println("url in Inbox page===" + url);
movieList.clear();
JsonObjectRequest movieReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () {
#SuppressWarnings("deprecation")
#Override
public void onResponse(JSONObject response) {
// progressBar.setVisibility(View.GONE);
// Parsing json
// for (int i = 0; i < response.length(); i++) {
try {
JSONArray contact = response.getJSONArray("contact");
obj_contact = contact.optJSONObject(0);
login_status1 = obj_contact.getString("Status");
// progressBar.setVisibility(View.VISIBLE);
layout.setVisibility(View.INVISIBLE);
listView.setVisibility(View.VISIBLE);
host_inbox.setBackgroundColor(Color.parseColor("#FFFFFF"));
ListFeed movie = new ListFeed();
for (int i = 0; i < contact.length(); i++) {
JSONObject obj1 = contact.optJSONObject(i);
movie.getuserby(obj1.getString("userby"));
movie.resid(obj1.getString("reservation_id"));
movie.setresidinbox(obj1.getString("reservation_id"));
System.out.println("reservation iddgdsds" + obj1.getString("reservation_id"));
movie.setuserbys(obj1.getString("userby"));
movie.setuserto(obj1.getString("userto"));
movie.setid(obj1.getString("room_id"));
movie.getid1(obj1.getString("id"));
movie.userto(obj1.getString("userto"));
movie.isread(obj1.getString("isread"));
movie.userbyname(obj1.getString("userbyname"));
country_symbol = obj1.getString("currency_code");
Currency c = Currency.getInstance(country_symbol);
country_symbol = c.getSymbol();
movie.setsymbol(country_symbol);
movie.setTitle(obj1.getString("title"));
movie.setThumbnailUrl(obj1.getString("profile_pic"));
movie.setstatus(obj1.getString("status"));
movie.setcheckin(obj1.getString("checkin"));
movie.setcheckout(obj1.getString("checkout"));
movie.setcreated(obj1.getString("created"));
movie.guest(obj1.getString("guest"));
movie.userbyname(obj1.getString("username"));
movie.getprice(obj1.getString("price"));
String msg = obj1.getString("message");
msg = msg.replaceAll("<b>You have a new contact request from ", "");
msg = msg.replaceAll("</b><br><br", "");
msg = msg.replaceAll("\\w*\\>", "");
movie.message(msg);
movieList.add(movie);
System.out.println(movieList.get(i).message()); // returning unique values
adapter.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
// progressBar.setVisibility(View.GONE);
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
stopAnim();
//progressBar.setVisibility(View.GONE);
if (error instanceof NoConnectionError) {
Toast.makeText(getActivity(),
"Check your Internet Connection",
Toast.LENGTH_LONG).show();
}
//progressBar.setVisibility(View.GONE);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
movieReq.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
return hostinbox;
}
#Override
public void onStop() {
Log.w(TAG, "App stopped");
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
public boolean isOnline(Context c) {
ConnectivityManager cm = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnected();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
In the above code , System.out.println(movieList.get(i).message()); returning unique values without any problem.
Inboxhostadapter.java = This is the adapter for recycleview
public class InboxHostAdapter extends RecyclerView.Adapter < InboxHostAdapter.CustomViewHolder > {
private List < ListFeed > feedItemList;
private ListFeed listFeed = new ListFeed();
String userid = "",
tag,
str_currency;
String reservation_id,
Liveurl,
india2 = "0";
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
String currency1;
String status1;
//private Activity activity;
public Context activity;
public InboxHostAdapter(Context activity, List < ListFeed > feedItemList, String tag) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
Liveurl = sharedPreferences.getString("liveurl", null);
userid = sharedPreferences.getString("userid", null);
currency1 = sharedPreferences.getString("currenycode", null);
this.feedItemList = feedItemList; // returning duplicate items
this.activity = activity;
listFeed = new ListFeed();
this.tag = tag;
SharedPreferences prefs1 = activity.getSharedPreferences(Constants.MY_PREFS_LANGUAGE, MODE_PRIVATE);
str_currency = prefs1.getString("currencysymbol", null);
if (str_currency == null) {
str_currency = "$";
}
}
#Override
public InboxHostAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.hostinbox, parent, false);
FontChangeCrawler fontChanger = new FontChangeCrawler(activity.getAssets(), activity.getString(R.string.app_font_light));
fontChanger.replaceFonts((ViewGroup) view);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(InboxHostAdapter.CustomViewHolder holder, int position) {
// This block returning duplicate items
listFeed = feedItemList.get(position); // This list feedItemList returning duplicate items
reservation_id = listFeed.getid();
System.out.println("reservation id after getting in inbox adapter" + reservation_id);
System.out.println("check out after getting" + listFeed.getcheckout());
System.out.println("message after getting in inbox adapter" + listFeed.getTitle());
System.out.println("symbol after getting" + listFeed.getsymbol());
System.out.println("username after getting" + listFeed.getaddress());
System.out.println("price after getting" + listFeed.getprice());
System.out.println("status after getting" + listFeed.getstatus());
System.out.println("check in after getting" + listFeed.getcheckin());
System.out.println("check out after getting" + listFeed.getcheckout());
System.out.println("userby after getting====" + listFeed.getuserby());
System.out.println("message after getting====" + listFeed.message());
String msg;
msg = listFeed.message();
holder.name.setText(listFeed.userbyname());
holder.time.setText(listFeed.getcreated());
holder.date1.setText(listFeed.getcheckin());
holder.date2.setText(listFeed.getcheckout());
if (listFeed.guest().equals("1")) {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
} else {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
}
if (tag.equals("Listinbox_service_host")) {
holder.guest.setText("");
holder.ttt.setVisibility(View.INVISIBLE);
} else {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
}
// holder.status.setText(listFeed.getstatus());
holder.title.setText(listFeed.getTitle());
status1 = listFeed.getstatus();
if (status1.equals("Accepted")) {
holder.status.setText(activity.getResources().getString(R.string.accepted_details));
}
} else if (status1.equals("Contact Host")) {
holder.status.setText(activity.getResources().getString(R.string.Contact_Host));
holder.guestmsg.setText(listFeed.message());
} else {
holder.status.setText(status1);
}
if (currency1 == null) {
currency1 = "$";
}
if (listFeed.getprice() != null && !listFeed.getprice().equals("null")) {
DecimalFormat money = new DecimalFormat("00.00");
money.setRoundingMode(RoundingMode.UP);
india2 = money.format(new Double(listFeed.getprice()));
holder.currency.setText(listFeed.getsymbol() + " " + india2);
holder.currency.addTextChangedListener(new NumberTextWatcher(holder.currency));
}
//view.imgViewFlag.setImageResource(listFlag.get(position));
System.out.println("listview price" + listFeed.getprice());
System.out.println("listview useds" + listFeed.getresidinbox());
System.out.println("listview dffdd" + listFeed.getuserbys());
System.out.println("listview dfffdgjf" + listFeed.getuserto());
//holder.bucket.setTag(position);
System.out.println("Activity name" + tag);
holder.inbox.setTag(position);
holder.inbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int) v.getTag();
Intent search = new Intent(activity, Inbox_detailshost.class);
search.putExtra("userid", userid);
search.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(search);
System.out.println("listview useds" + listFeed.getresidinbox());
System.out.println("listview dffdd" + listFeed.getuserbys());
System.out.println("listview dfffdgjf" + listFeed.getuserto());
}
});
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getItemCount() {
System.out.println("list item size" + feedItemList.size());
return (null != feedItemList ? feedItemList.size() : 0);
}
#Override
public int getItemViewType(int position) {
return position;
}
class CustomViewHolder extends RecyclerView.ViewHolder {
ImageView thumbNail;
TextView name, time, date1, date2, currency, guest, status, title, ttt, guestmsg;
RelativeLayout inbox;
CustomViewHolder(View view) {
super(view);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
this.thumbNail = (ImageView) view.findViewById(R.id.list_image);
this.name = (TextView) view.findViewById(R.id.title2);
this.time = (TextView) view.findViewById(R.id.TextView4);
this.date1 = (TextView) view.findViewById(R.id.TextView2);
this.date2 = (TextView) view.findViewById(R.id.TextView22);
this.currency = (TextView) view.findViewById(R.id.TextView23);
this.guest = (TextView) view.findViewById(R.id.TextView25);
this.ttt = (TextView) view.findViewById(R.id.TextView24);
this.status = (TextView) view.findViewById(R.id.TextView26);
this.title = (TextView) view.findViewById(R.id.TextView28);
this.inbox = (RelativeLayout) view.findViewById(R.id.inbox);
this.guestmsg = (TextView) view.findViewById(R.id.guestmessage);
}
}
public class NumberTextWatcher implements TextWatcher {
private DecimalFormat df;
private DecimalFormat dfnd;
private boolean hasFractionalPart;
private TextView et;
public NumberTextWatcher(TextView et) {
df = new DecimalFormat("#,###");
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###.##");
this.et = et;
hasFractionalPart = false;
}
#SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";
#Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelected(true);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
et.addTextChangedListener(this);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()))) {
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
}
}
In the above code , feedItemList returning duplicate values eventhogh the movieList list from source clas Inboxfragment.java contains unique values.
Kindly please help me with this issue. I tried many answers in Stackoverflow but I can't get solutions. I can't figure out the problem.
Use this code
for (int i = 0; i < contact.length(); i++) {
JSONObject obj1 = contact.optJSONObject(i);
ListFeed movie = new ListFeed();
movie.getuserby(obj1.getString("userby"));
movie.resid(obj1.getString("reservation_id"));
movie.setresidinbox(obj1.getString("reservation_id"));
System.out.println("reservation iddgdsds" + obj1.getString("reservation_id"));
movie.setuserbys(obj1.getString("userby"));
movie.setuserto(obj1.getString("userto"));
movie.setid(obj1.getString("room_id"));
movie.getid1(obj1.getString("id"));
movie.userto(obj1.getString("userto"));
movie.isread(obj1.getString("isread"));
movie.userbyname(obj1.getString("userbyname"));
country_symbol = obj1.getString("currency_code");
Currency c = Currency.getInstance(country_symbol);
country_symbol = c.getSymbol();
movie.setsymbol(country_symbol);
movie.setTitle(obj1.getString("title"));
movie.setThumbnailUrl(obj1.getString("profile_pic"));
movie.setstatus(obj1.getString("status"));
movie.setcheckin(obj1.getString("checkin"));
movie.setcheckout(obj1.getString("checkout"));
movie.setcreated(obj1.getString("created"));
movie.guest(obj1.getString("guest"));
movie.userbyname(obj1.getString("username"));
movie.getprice(obj1.getString("price"));
String msg = obj1.getString("message");
msg = msg.replaceAll("<b>You have a new contact request from ", "");
msg = msg.replaceAll("</b><br><br", "");
msg = msg.replaceAll("\\w*\\>", "");
movie.message(msg);
movieList.add(movie);
System.out.println(movieList.get(i).message()); // returning unique value
}
Declare ListFeed movie = new ListFeed(); into the for Loop
And remove the adapter.notifyDataSetChanged(); from for Loop.
I think this help you.

Crash on button click when I try to add items in ListView dynamically

I have an activity named EfortActivity which contains 3 EditText, a Spinner, a RadioGroup and a Button - saveButton. My goal is to add data dynamically in a ListView (the listView is implemented in another activity called HistoryActivity).
The problem is that when I click on the saveButton my app crash.
Here is the code in EfortActivity:
public class EfortMonitorizareActivity extends AppCompatActivity {
RadioGroup radioGroupDaNu;
Spinner spinnerTip;
EditText editTextDurata;
EditText editTextInainte;
EditText editTextDupa;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_efort_monitorizare);
intent = getIntent();
initializareComponente();
}
private void initializareComponente() {
radioGroupDaNu = (RadioGroup) findViewById(R.id.rg_activitateDANU);
spinnerTip = (Spinner) findViewById(R.id.spin_tip_efort);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getApplicationContext(),
R.array.TipEfort, R.layout.support_simple_spinner_dropdown_item);
spinnerTip.setAdapter(adapter);
editTextDurata = (EditText) findViewById(R.id.edt_durataAnt_efort);
editTextInainte = (EditText) findViewById(R.id.edt_greuteInainteAnt_efort);
editTextDupa = (EditText) findViewById(R.id.edt_greutateDupaAnt_efort);
Button btn_inregistrareDate = (Button) findViewById(R.id.btn_adaugaDate_efort);
btn_inregistrareDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (validare()) {
Efort efort = createPlayerFromComponents();
if (efort != null) {
intent.putExtra(Constants.ADD_EFORT_KEY,efort);
setResult(RESULT_OK,intent);
finish();
}
}
}
});
}
private Efort createPlayerFromComponents() {
RadioButton checkDaNu = (RadioButton) findViewById(radioGroupDaNu.getCheckedRadioButtonId());
String radioDaNu = checkDaNu.getText().toString();
String tip = spinnerTip.getSelectedItem().toString();
Integer durata = Integer.parseInt(editTextDurata.getText().toString());
Integer inainte = Integer.parseInt(editTextInainte.getText().toString());
Integer dupa = Integer.parseInt(editTextDupa.getText().toString());
return new Efort(radioDaNu, tip, durata, inainte, dupa);
}
private boolean validare() {
RadioButton nu = (RadioButton) findViewById(R.id.button_nu_efort);
if (editTextDurata.getText() == null || editTextDurata.getText().toString().trim().isEmpty()) {
Toast.makeText(getApplicationContext(), R.string.addplayer_number_error, Toast.LENGTH_SHORT).show();
return false;
}
if (editTextInainte.getText() == null || editTextDurata.getText().toString().trim().isEmpty()) {
Toast.makeText(getApplicationContext(), R.string.addplayer_number_error, Toast.LENGTH_SHORT).show();
return false;
}
if (editTextDupa.getText() == null || editTextDurata.getText().toString().trim().isEmpty()) {
Toast.makeText(getApplicationContext(), R.string.addplayer_number_error, Toast.LENGTH_SHORT).show();
return false;
} }
Here is the code for HistoryActivity:
public class IstoricActivity extends AppCompatActivity {
ListView lvEfort;
List<String> listaEfort = new ArrayList<>();
Button deconectare;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_istoric);
deconectare=(Button)findViewById(R.id.btn_deconectareIstoric);
deconectare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
//initializare componente
lvEfort = (ListView) findViewById(R.id.lw_listaEfort);
Efort efortDefault = new Efort("Da", "Tennis", 40, 55, 53);
listaEfort.add(efortDefault.toString());
//declarare + initializare adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, listaEfort);
lvEfort.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
And the class Efort:
public class Efort implements Parcelable {
private String radioDaNu;
private String tip;
private Integer durata;
private Integer inainte;
private Integer dupa;
public Efort(String radioDaNu, String tip, Integer durata, Integer inainte, Integer dupa) {
this.radioDaNu = radioDaNu;
this.tip = tip;
this.durata = durata;
this.inainte = inainte;
this.dupa = dupa;
}
public String getRadioDaNu() {
return radioDaNu;
}
public void setRadioDaNu(String radioDaNu) {
this.radioDaNu = radioDaNu;
}
public String getTip() {
return tip;
}
public void setTip(String tip) {
this.tip = tip;
}
public Integer getDurata() {
return durata;
}
public void setDurata(Integer durata) {
this.durata = durata;
}
public Integer getInainte() {
return inainte;
}
public void setInainte(Integer inainte) {
this.inainte = inainte;
}
public Integer getDupa() {
return dupa;
}
public void setDupa(Integer dupa) {
this.dupa = dupa;
}
#Override
public String toString() {
return "Efort{" +
// ", datePicker=" + datePicker +
", Activitate efort :" + radioDaNu +
", tip : '" + tip + '\'' +
", tipm de : " + durata +
", inainte de antrenamnet aveam : " + inainte +
", dupa antrenamnet am : " + dupa +
'}';
}
public Efort(Parcel in) {
this.radioDaNu = in.readString();
this.tip = in.readString();
this.durata = in.readInt();
this.inainte = in.readInt();
this.dupa = in.readInt();
}
public static Parcelable.Creator<Efort> CREATOR = new Creator<Efort>() {
#Override
public Efort createFromParcel(Parcel parcel) {
return new Efort(parcel);
}
#Override
public Efort[] newArray(int i) {
return new Efort[i];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(radioDaNu);
parcel.writeString(tip);
parcel.writeInt(durata);
parcel.writeInt(inainte);
parcel.writeInt(dupa);
}
}
When you called,
finish()
it will stop your activity and finish it. Please remove that finish()

How to transfer and save numbers

This code right here is a random math questionnaire and I want to know how to be able to transfer the amount of questions answered right and wrong to a separate stats page after each time they answer a question. I want the stats page to save the numbers so that if the user exits the program and then goes back on later they can still look at their total right answered questions and wrong answered questions. Ive been looking all over the internet and cant find a good way to learn this. If anyone has some advice I would really appreciate it. btw this is pretty much all the code in the main page; I didn't add the stats page code (because it has pretty much nothing.)
Pushme1-4 are the buttons and the AdditionEasyRight and AdditionEasyWrong are the number counts that are displayed on the main page.
public class AdditionEasy extends AppCompatActivity {
int countCNumAddE = 0;
int countWNumAddE = 0;
boolean hasAnswered;
public static final String MY_PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addition);
final TextView count = (TextView) findViewById(R.id.Count);
final TextView count2 = (TextView) findViewById(R.id.Count2);
Button homeButton = (Button) findViewById(R.id.homeButton);
super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
final TextView textOne = (TextView) findViewById(R.id.textView);
final TextView textTwo = (TextView) findViewById(R.id.textView2);
final Button pushMe1 = (Button) findViewById(R.id.button1);
final Button pushMe2 = (Button) findViewById(R.id.button2);
final Button pushMe3 = (Button) findViewById(R.id.button3);
final Button pushMe4 = (Button) findViewById(R.id.button4);
final Button begin = (Button) findViewById(R.id.begin);
begin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
hasAnswered = false;
pushMe1.setEnabled(true);
pushMe2.setEnabled(true);
pushMe3.setEnabled(true);
pushMe4.setEnabled(true);
begin.setVisibility(View.INVISIBLE);
pushMe1.setVisibility(View.VISIBLE);
pushMe2.setVisibility(View.VISIBLE);
pushMe3.setVisibility(View.VISIBLE);
pushMe4.setVisibility(View.VISIBLE);
pushMe1.setTextColor(Color.BLACK);
pushMe2.setTextColor(Color.BLACK);
pushMe3.setTextColor(Color.BLACK);
pushMe4.setTextColor(Color.BLACK);
pushMe1.setTextSize(20);
pushMe2.setTextSize(20);
pushMe3.setTextSize(20);
pushMe4.setTextSize(20);
textTwo.setText("");
String randGenChoice1 = "";
String randGenChoice2 = "";
String randGenChoice3 = "";
String randGenChoice4 = "";
String randText2 = "";
String randText3 = "";
Random RandomNum = new Random();
int randChoice1 = RandomNum.nextInt(40) + 1;
int randChoice2 = RandomNum.nextInt(40) + 1;
int randChoice3 = RandomNum.nextInt(40) + 1;
int randChoice4 = RandomNum.nextInt(40) + 1;
int rando2 = RandomNum.nextInt(20) + 1;
int rando3 = RandomNum.nextInt(20) + 1;
int pick = RandomNum.nextInt(4);
randGenChoice1 = Integer.toString(randChoice1);
randGenChoice2 = Integer.toString(randChoice2);
randGenChoice3 = Integer.toString(randChoice3);
randGenChoice4 = Integer.toString(randChoice4);
randText2 = Integer.toString(rando2);
randText3 = Integer.toString(rando3);
int value1;
int value2;
value1 = Integer.parseInt(randText2);
value2 = Integer.parseInt(randText3);
final int value = value1 + value2;
String line = randText2 + " + " + randText3;
textOne.setText(line);
final String answer;
answer = Integer.toString(value);
pushMe1.setText(randGenChoice1);
pushMe2.setText(randGenChoice2);
pushMe3.setText(randGenChoice3);
pushMe4.setText(randGenChoice4);
Button[] choice = {pushMe1, pushMe2, pushMe3, pushMe4};
Button display = choice[pick];
display.setText(answer);
pushMe1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonAnswer = Integer.parseInt(pushMe1.getText().toString());
if (buttonAnswer == value) {
begin.setVisibility(View.VISIBLE);
textTwo.setText("Correct!");
textTwo.setTextColor(Color.BLACK);
pushMe1.setTextColor(Color.GREEN);
pushMe1.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyRight = Integer.toString(++countCNumAddE);
count.setText(AdditionEasyRight);
hasAnswered = true;
}
begin.setText("New Question");
begin.setTextSize(20);
pushMe2.setVisibility(View.INVISIBLE);
pushMe3.setVisibility(View.INVISIBLE);
pushMe4.setVisibility(View.INVISIBLE);
pushMe1.setEnabled(false);
pushMe2.setEnabled(false);
pushMe3.setEnabled(false);
pushMe4.setEnabled(false);
}else{
textTwo.setText("Wrong!");
textTwo.setTextColor(Color.BLACK);
pushMe1.setTextColor(Color.RED);
pushMe1.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyWrong = Integer.toString(++countWNumAddE);
count2.setText(AdditionEasyWrong);
hasAnswered = true;
}
pushMe1.setEnabled(false);
}
}
});
pushMe2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonAnswer = Integer.parseInt(pushMe2.getText().toString());
if (buttonAnswer == value) {
begin.setVisibility(View.VISIBLE);
textTwo.setText("Correct!");
textTwo.setTextColor(Color.BLACK);
pushMe2.setTextColor(Color.GREEN);
pushMe2.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyRight = Integer.toString(++countCNumAddE);
count.setText(AdditionEasyRight);
hasAnswered = true;
}
begin.setText("New Question");
begin.setTextSize(20);
pushMe1.setVisibility(View.INVISIBLE);
pushMe3.setVisibility(View.INVISIBLE);
pushMe4.setVisibility(View.INVISIBLE);
pushMe1.setEnabled(false);
pushMe2.setEnabled(false);
pushMe3.setEnabled(false);
pushMe4.setEnabled(false);
}else{
textTwo.setText("Wrong!");
textTwo.setTextColor(Color.BLACK);
pushMe2.setTextColor(Color.RED);
pushMe2.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyWrong = Integer.toString(++countWNumAddE);
count2.setText(AdditionEasyWrong);
hasAnswered = true;
}
pushMe2.setEnabled(false);
}
}
});
pushMe3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonAnswer = Integer.parseInt(pushMe3.getText().toString());
if (buttonAnswer == value) {
begin.setVisibility(View.VISIBLE);
textTwo.setText("Correct!");
textTwo.setTextColor(Color.BLACK);
pushMe3.setTextColor(Color.GREEN);
pushMe3.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyRight = Integer.toString(++countCNumAddE);
count.setText(AdditionEasyRight);
hasAnswered = true;
}
begin.setText("New Question");
begin.setTextSize(20);
pushMe1.setVisibility(View.INVISIBLE);
pushMe2.setVisibility(View.INVISIBLE);
pushMe4.setVisibility(View.INVISIBLE);
pushMe1.setEnabled(false);
pushMe2.setEnabled(false);
pushMe3.setEnabled(false);
pushMe4.setEnabled(false);
}else{
textTwo.setText("Wrong!");
textTwo.setTextColor(Color.BLACK);
pushMe3.setTextColor(Color.RED);
pushMe3.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyWrong = Integer.toString(++countWNumAddE);
count2.setText(AdditionEasyWrong);
hasAnswered = true;
}
pushMe3.setEnabled(false);
}
}
});
pushMe4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonAnswer = Integer.parseInt(pushMe4.getText().toString());
if (buttonAnswer == value) {
begin.setVisibility(View.VISIBLE);
textTwo.setText("Correct!");
textTwo.setTextColor(Color.BLACK);
pushMe4.setTextColor(Color.GREEN);
pushMe4.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyRight = Integer.toString(++countCNumAddE);
count.setText(AdditionEasyRight);
hasAnswered = true;
}
begin.setText("New Question");
begin.setTextSize(20);
pushMe1.setVisibility(View.INVISIBLE);
pushMe2.setVisibility(View.INVISIBLE);
pushMe3.setVisibility(View.INVISIBLE);
pushMe1.setEnabled(false);
pushMe2.setEnabled(false);
pushMe3.setEnabled(false);
pushMe4.setEnabled(false);
}else{
textTwo.setText("Wrong!");
textTwo.setTextColor(Color.BLACK);
pushMe4.setTextColor(Color.RED);
pushMe4.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyWrong = Integer.toString(++countWNumAddE);
count2.setText(AdditionEasyWrong);
hasAnswered = true;
}
pushMe4.setEnabled(false);
}
}
});
}
});
homeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent homepage = new Intent(AdditionEasy.this , Menu.class);
startActivity(homepage);
}
});
}
}

below calculation work in API?

i created checkoutpage then it contain total,payment due and payment balance. If give total it show the payment due amount & payment balance amount in mobile app. But it doesn't update the browser?
public class FinalCheckOutActivity extends Activity implements View.OnClickListener {
private AQuery mAQuery;
private TransparentProgressDialog mTransparentProgressDialog;
private String mStrCheckOut = "", mStrGEtData = "", mStrAddressData = "", mStrPaypAl = "";
private Spinner mSpnDefualtAddress, mSpnShipAddress;
private Button mBtnPlaceOrder;
private CheckBox mChBxSameAddres, mChkBxDiffAddress, mChkBoxAccept;
private RadioButton mRdoPayPal, mRdoCash;
private RadioGroup mRdoGroupPay;
private ImageView mIvBack;
private TextView mTvAddAddress, mTvSubTot, mTvDiscount, mTVGrandTot, mTvPendingAmt, mTvPayNow, mIvAddAddress;
private ArrayList<SpinnerData> mArrayListAddres;
private LinearLayout mLinearLayoutShiipingMethod, mLinearLayoutPayMethod, mLinearLayoutOrderDetails;
private RadioGroup mRbnOptionshippingmethods;
private ArrayList<UserAddressData> mArrayListshippingMethod;
private ArrayList<UserAddressData> mArrayListPaymentMethods;
private String shippingMethodId;
private RadioGroup mRbnOptionPaymentMethods;
private String shippingPaymentID;
private View viewOrderData;
private JSONObject mJsonObject, jsonObjectData;
private LinearLayout mLinearLayoutTabShiping;
private RadioButton newRadioButton;
private ArrayList<SpinnerData> mArrayListBilign;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final_check_out);
//setUI();
}
private void setUI() {
mAQuery = new AQuery(this);
mTransparentProgressDialog = new TransparentProgressDialog(this, R.drawable.ic_loader_image);
mSpnDefualtAddress = (Spinner) findViewById(R.id.spn_default_address);
mSpnShipAddress = (Spinner) findViewById(R.id.spn_ship_address);
mBtnPlaceOrder = (Button) findViewById(R.id.btn_place_order);
mRdoGroupPay = (RadioGroup) findViewById(R.id.rdo_payment);
mRdoCash = (RadioButton) findViewById(R.id.rdo_cash);
mRdoPayPal = (RadioButton) findViewById(R.id.rdo_paypal);
mLinearLayoutTabShiping = (LinearLayout) findViewById(R.id.layout_shiping);
mChBxSameAddres = (CheckBox) findViewById(R.id.chk_ship_to_same_address);
mChkBxDiffAddress = (CheckBox) findViewById(R.id.chk_diff_ship_address);
mChkBoxAccept = (CheckBox) findViewById(R.id.chk_acceept);
mLinearLayoutShiipingMethod = (LinearLayout) findViewById(R.id.layout_shipping_method);
mLinearLayoutPayMethod = (LinearLayout) findViewById(R.id.layout_payment_method);
mLinearLayoutOrderDetails = (LinearLayout) findViewById(R.id.lv_shipping_order_view);
mIvAddAddress = (TextView) findViewById(R.id.img_add_address);
mTvSubTot = (TextView) findViewById(R.id.tv_subtotal);
mTvDiscount = (TextView) findViewById(R.id.tv_discount);
mTVGrandTot = (TextView) findViewById(R.id.tv_grand_tot);
mTvPendingAmt = (TextView) findViewById(R.id.tv_pending_pay);
mTvPayNow = (TextView) findViewById(R.id.tv_payable_now);
mIvBack = (ImageView) findViewById(R.id.img_back_one_page);
mArrayListAddres = new ArrayList<>();
mArrayListshippingMethod = new ArrayList<>();
mArrayListPaymentMethods = new ArrayList<>();
mArrayListBilign = new ArrayList<>();
mBtnPlaceOrder.setOnClickListener(this);
mIvAddAddress.setOnClickListener(this);
// mTvAddAddress.setOnClickListener(this);
mIvBack.setOnClickListener(this);
ajaxCallback.setTimeout(Integer.parseInt(getString(R.string.ajax_timeout)));
mChBxSameAddres.setChecked(true);
mLinearLayoutTabShiping.setVisibility(View.GONE);
mChBxSameAddres.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mLinearLayoutTabShiping.setVisibility(View.GONE);
//mSpnShipAddress.setVisibility(View.GONE);
// perform logic
}
}
});
mChkBxDiffAddress.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mChBxSameAddres.setChecked(false);
mLinearLayoutTabShiping.setVisibility(View.VISIBLE);
}
}
});
SpinnerData data = new SpinnerData();
data.setmStrName("Select Address");
mArrayListAddres.add(data);
mSpnDefualtAddress.setAdapter(new SpinnerAdapter(this, mArrayListAddres));
getFinalCheckOutData();
}
#Override
protected void onResume() {
super.onResume();
setUI();
//getAddressData();
}
/**
* get user address web service call
**/
private void getAddressData() {
mStrAddressData = getString(R.string.WS_HOST) + getString(R.string.WS_GET_MULTIPLE_ADDRESS);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("customer_id", SessionClass.getUserId(this));
Log.e("Hash map final data", "Hash map->" + hashMap.toString());
if (AvailableNetwork.isConnectingToInternet(this)) {
mAQuery.progress(mTransparentProgressDialog).ajax(mStrAddressData, hashMap, JSONObject.class, ajaxCallback);
} else {
// showAlert(getString(R.string.no_internt_connection), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_internt_connection, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
/**
* get user address web service call
**/
private void getPaypalData() {
mStrPaypAl = getString(R.string.WS_HOST) + getString(R.string.WS_PAYPAL);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("order_increment_id", orderID);
Log.e("Hash map final data", "Hash map->" + hashMap.toString());
if (AvailableNetwork.isConnectingToInternet(this)) {
mAQuery.progress(mTransparentProgressDialog).ajax(mStrPaypAl, hashMap, JSONObject.class, ajaxCallback);
} else {
// showAlert(getString(R.string.no_internt_connection), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_internt_connection, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
/**
* Get final checkout data
**/
private void getFinalCheckOutData() {
mStrGEtData = getString(R.string.WS_HOST) + getString(R.string.WS_FINAL_CHECKOUT_DETAIls);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("cart_id", IntermediateCheckoutActivity.cartId);
Log.e("Hash map final data", "Hash map->" + hashMap.toString());
if (AvailableNetwork.isConnectingToInternet(this)) {
mAQuery.progress(mTransparentProgressDialog).ajax(mStrGEtData, hashMap, JSONObject.class, ajaxCallback);
} else {
// showAlert(getString(R.string.no_internt_connection), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_internt_connection, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
/**
* Place order web service call
**/
private void placeOrder() {
mStrCheckOut = getString(R.string.WS_HOST) + getString(R.string.WS_PLACE_ORDER);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("cart_id", IntermediateCheckoutActivity.cartId);
hashMap.put("checkoutdetails", jsonObjectData.toString());
Log.e("Place order", "hash map-->" + hashMap.toString());
if (AvailableNetwork.isConnectingToInternet(this)) {
mAQuery.progress(mTransparentProgressDialog).ajax(mStrCheckOut, hashMap, JSONObject.class, ajaxCallback);
} else {
//showAlert(getString(R.string.no_internt_connection), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_internt_connection, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
private boolean checkValidationn() {
if (mSpnDefualtAddress.getSelectedItemPosition() == 0) {
showAlert("Please select billing address first.", -1);
mSpnDefualtAddress.requestFocus();
return false;
} else if (mRbnOptionshippingmethods.getCheckedRadioButtonId() == -1) {
showAlert("Please select shipping method first.", -1);
mRbnOptionshippingmethods.requestFocus();
return false;
} else if (mRdoGroupPay.getCheckedRadioButtonId() == -1) {
showAlert("Please select payment method first.", -1);
mRdoGroupPay.requestFocus();
return false;
} else if (!mChkBoxAccept.isChecked()) {
showAlert("Please select terms and conditions first.", -1);
mChkBoxAccept.requestFocus();
return false;
}
return true;
}
private void showAlert(String message, final int flg) {
AlertDialog.Builder aBuilder = new AlertDialog.Builder(this);
aBuilder.setCancelable(false);
aBuilder.setMessage(message);
aBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
setNxtFlg(flg);
}
});
aBuilder.create();
aBuilder.show();
}
private void setNxtFlg(int flg) {
switch (flg) {
case 3:
Intent intent = new Intent(FinalCheckOutActivity.this, PayPalPaymentActivity.class);
intent.putExtra("key", urlMain);
intent.putExtra("order_id", orderID);
overridePendingTransition(R.anim.anim_left_in, R.anim.anim_left_out);
startActivity(intent);
break;
case 1:
Intent intent1 = new Intent(FinalCheckOutActivity.this, MainActivity.class);
intent1.putExtra("key", "4");
startActivity(intent1);
overridePendingTransition(R.anim.anim_left_in, R.anim.anim_left_out);
break;
}
}
#Override
public void onClick(View v) {
Intent intent;
switch (v.getId()) {
case R.id.btn_place_order:
getCheckOutData();
if (checkValidationn()) {
placeOrder();
}
break;
case R.id.img_back_one_page:
onBackPressed();
//finish();
overridePendingTransition(R.anim.anim_left_in, R.anim.anim_left_out);
break;
case R.id.img_add_address:
intent = new Intent(FinalCheckOutActivity.this, CheckoutActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.anim_left_in, R.anim.anim_left_out);
break;
/*case R.id.txt_add_address:
intent = new Intent(FinalCheckOutActivity.this, AddUserAddressActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.anim_left_in, R.anim.anim_left_out);
//finish();
break;*/
}
}
private void getCheckOutData() {
mJsonObject = new JSONObject();
jsonObjectData = new JSONObject();
try {
if (mChBxSameAddres.isChecked()) {
jsonObjectData.put("billing_id", mArrayListAddres.get(mSpnDefualtAddress.getSelectedItemPosition()).getmStrId());
jsonObjectData.put("shipping_id", mArrayListAddres.get(mSpnDefualtAddress.getSelectedItemPosition()).getmStrId());
} else {
// jsonObjectData.put("shipping_id", mArrayListAddres.get(mSpnShipAddress.getSelectedItemPosition()).getmStrId());
}
if (mChkBxDiffAddress.isChecked()) {
jsonObjectData.put("billing_id", mArrayListAddres.get(mSpnDefualtAddress.getSelectedItemPosition()).getmStrId());
jsonObjectData.put("shipping_id", mArrayListAddres.get(mSpnShipAddress.getSelectedItemPosition()).getmStrId());
} else {
jsonObjectData.put("shipping_id", mArrayListAddres.get(mSpnDefualtAddress.getSelectedItemPosition()).getmStrId());
}
JSONObject mJsonObjectPay = new JSONObject();
if (mRdoCash.isChecked()) {
shippingPaymentID = "checkmo";
mJsonObjectPay.put("method", shippingPaymentID);
} else if (mRdoPayPal.isChecked()) {
shippingPaymentID = "paypaladaptive";
mJsonObjectPay.put("method", shippingPaymentID);
}
jsonObjectData.put("payment", mJsonObjectPay);
jsonObjectData.put("shipping_method", shippingMethodId);
jsonObjectData.put("checkout_method", "customer");
jsonObjectData.put("onestepcheckout_feedback_freetext", "");
jsonObjectData.put("accept_terms", 1);
jsonObjectData.put("customer_id", SessionClass.getUserId(FinalCheckOutActivity.this));
mJsonObject.put("checkoutdetails", jsonObjectData);
//showAlert("place order array" + jsonObjectData.toString(), -1);
//Log.e("Place order", "Data-->" + jsonObjectData.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
private String orderID;
private String urlMain;
/**
* web service responce
**/
AjaxCallback<JSONObject> ajaxCallback = new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject object, AjaxStatus status) {
super.callback(url, object, status);
Log.e("Check out", "Url-->" + url);
Log.e("Check out", "Responce-->" + object);
if (object != null) {
if (status.getCode() == 200) {
if (mTransparentProgressDialog.isShowing()) {
mTransparentProgressDialog.dismiss();
}
if (url.equalsIgnoreCase(mStrAddressData)) {
try {
if (object.getString("errorcode").equalsIgnoreCase("0")) {
setAddressData(object.getJSONArray("data"));
//getFinalCheckOutData();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else if (url.equalsIgnoreCase(mStrGEtData)) {
try {
String now = getIntent().getExtras().getString("pay_now");
String due = getIntent().getExtras().getString("pay_due");
if (object.getString("errorcode").equalsIgnoreCase("0")) {
JSONObject mJsonObject = object.getJSONObject("data");
setShippingMethods(mJsonObject.getJSONArray("shippingmethods"));
setPaymentMethods(mJsonObject.getJSONArray("paymentmethods"));
if (!mJsonObject.isNull("items")) {
setOrderView(mJsonObject.getJSONArray("items"));
}
mTvSubTot.setText(mJsonObject.getString("subtotal"));
mTvDiscount.setText(mJsonObject.getString("discount"));
mTVGrandTot.setText(mJsonObject.getString("grandtotal"));
// mTvPendingAmt.setText(mJsonObject.getString("pendingpayment"));
// mTvPayNow.setText(mJsonObject.getString("payablenow"));
mTvPendingAmt.setText(now);
mTvPayNow.setText(due);
getAddressData();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else if (url.equalsIgnoreCase(mStrCheckOut)) {
try {
if (object.getString("errorcode").equalsIgnoreCase("0")) {
//showAlert("Your order placed successfully.", -1);
if (shippingPaymentID.equalsIgnoreCase("paypaladaptive")) {
JSONObject mJsonObject = object.getJSONObject("data");
orderID = mJsonObject.getString("order_increment_id");
getPaypalData();
} else {
showAlert("Your order placed successfully.", 1);
}
//SessionClass.logout(FinalCheckOutActivity.this);
SessionClass.setUrerCartId(FinalCheckOutActivity.this, "");
} else if (object.getString("errorcode").equalsIgnoreCase("1")) {
showAlert("There is error in order creation.", -1);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else if (url.equalsIgnoreCase(mStrPaypAl)) {
try {
if (object.getString("errorcode").equalsIgnoreCase("0")) {
JSONObject mJsonObject = object.getJSONObject("data");
urlMain = mJsonObject.getString("url").replace("/\\/", "");
Log.e("Final url", "Url-->" + urlMain);
showAlert("Click on ok to continue.", 3);
} else if (object.getString("errorcode").equalsIgnoreCase("2")) {
showAlert("Paypal API call failed. Account not found. Unilateral receiver not allowed in chained payment is restricted.", -1);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
// showAlert(getString(R.string.no_connection_server), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_connection_server, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
}
};
/**
* Set order view data from web servicie responce
**/
private void setOrderView(JSONArray items) {
try {
mLinearLayoutOrderDetails.removeAllViews();
//mArrayListMethod.clear();
for (int i = 0; i < items.length(); i++) {
JSONObject mJsonObject = items.getJSONObject(i);
viewOrderData = getLayoutInflater().inflate(R.layout.single_chkout_order_listing, null);
TextView mTvName = (TextView) viewOrderData.findViewById(R.id.tv_order_name);
TextView mTvPrice = (TextView) viewOrderData.findViewById(R.id.tv_order_price);
TextView mTvQuan = (TextView) viewOrderData.findViewById(R.id.tv_order_quantity);
TextView mTvSubTot = (TextView) viewOrderData.findViewById(R.id.tv_order_sub_total);
mTvName.setText(mJsonObject.getString("name"));
mTvPrice.setText(mJsonObject.getString("price"));
mTvQuan.setText(mJsonObject.getString("quantity"));
mTvSubTot.setText(mJsonObject.getString("rowtotal"));
mLinearLayoutOrderDetails.addView(viewOrderData);
}
} catch (Exception e) {
e.printStackTrace();
}
}

TimePicker Saves Zero Value in SQLite Database

I have a TimePicker which I'd like to use to determine a length of time a user can stay connected. Lets say the time now is 10:00 if the user selects 11:00 - I'd like the source code below to determine that there are 60 minutes between the current time - and the time selected and set that to a string/long (minutes) which I then have displayed as a textview.
I've coded everything as I thought it should be - however the textview never seems to update with minutes value. Everytime I attempt to view the data - I get a value of 0 not matter what the timepicker is set to.
Anyone have any suggestions? I'm stumped at the moment and I'm not sure what else to try.
ADDEDITDEVICE.JAVA (where the timepicker and minutes determination takes place)
public class AddEditDevice extends Activity {
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private TimePicker timeEt;
private TextView ssidTextView;
Date date = new Date();
TimePicker tp;
// #Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_country);
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
String ssidString = info.getSSID();
if (ssidString.startsWith("\"") && ssidString.endsWith("\"")){
ssidString = ssidString.substring(1, ssidString.length()-1);
//TextView ssidTextView = (TextView) findViewById(R.id.wifiSSID);
ssidTextView = (TextView) findViewById(R.id.wifiSSID);
ssidTextView.setText(ssidString);
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
timeEt = (TimePicker) findViewById(R.id.timeEdit);
Bundle extras = getIntent().getExtras();
if (extras != null)
{
rowID = extras.getLong("row_id");
nameEt.setText(extras.getString("name"));
capEt.setText(extras.getString("cap"));
codeEt.setText(extras.getString("code"));
String time = extras.getString("time");
String[] parts = time.split(":");
timeEt.setCurrentHour(Integer.valueOf(parts[0]));
timeEt.setCurrentMinute(Integer.valueOf(parts[1]));
timeEt.setIs24HourView(false);
date.setMinutes(tp.getCurrentMinute());
date.setHours(tp.getCurrentHour());
Long.toString(minutes);
}
Button saveButton =(Button) findViewById(R.id.saveBtn);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
if (nameEt.getText().length() != 0)
{
AsyncTask<Object, Object, Object> saveContactTask =
new AsyncTask<Object, Object, Object>()
{
#Override
protected Object doInBackground(Object... params)
{
saveContact();
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
saveContactTask.execute((Object[]) null);
}
else
{
AlertDialog.Builder alert = new AlertDialog.Builder(AddEditDevice.this);
alert.setTitle(R.string.errorTitle);
alert.setMessage(R.string.errorMessage);
alert.setPositiveButton(R.string.errorButton, null);
alert.show();
}
}
});}
}
long minutes = ((new Date()).getTime() - date.getTime()) / (1000 * 60);
private void saveContact()
{
DatabaseConnector dbConnector = new DatabaseConnector(this);
if (getIntent().getExtras() == null)
{
// Log.i("Test for Null", ""+dbConnector+" "+nameEt+" "+capEt+" "+timeEt+" "+codeEt+" "+ssidTextView);
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
Long.toString(minutes),
ssidTextView.getText().toString());
}
else
{
dbConnector.updateContact(rowID,
nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
Long.toString(minutes),
ssidTextView.getText().toString());
}
}
}
VIEW COUNTRY.JAVA (where the minutes data set by the timepicker should be visible)
public class ViewCountry extends NfcBeamWriterActivity {
private static final String TAG = ViewCountry.class.getName();
protected Message message;
NfcAdapter mNfcAdapter;
private static final int MESSAGE_SENT = 1;
private long rowID;
private TextView nameTv;
private TextView capTv;
private TextView codeTv;
private TextView timeTv;
private TextView ssidTv;
private TextView combined;
private TextView minutes;
//String timetest = "300";
// String a="\"";
// String b="\"";
// String message1 = a + ssidTv.getText().toString() +"," +
// capTv.getText().toString()+b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_country);
SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("name", true);
editor.putBoolean("cap", true);
editor.putBoolean("code", true);
editor.putBoolean("time", true);
editor.putBoolean("ssid",true);
editor.putBoolean("minutes",true);
editor.putBoolean("timetest",true);
editor.commit();
setDetecting(true);
startPushing();
setUpViews();
Bundle extras = getIntent().getExtras();
rowID = extras.getLong(CountryList.ROW_ID);
}
private void setUpViews() {
nameTv = (TextView) findViewById(R.id.nameText);
capTv = (TextView) findViewById(R.id.capText);
timeTv = (TextView) findViewById(R.id.timeEdit);
codeTv = (TextView) findViewById(R.id.codeText);
ssidTv = (TextView) findViewById(R.id.wifiSSID);
minutes = (TextView) findViewById(R.id.Minutes);
}
#Override
protected void onResume() {
super.onResume();
new LoadContacts().execute(rowID);
}
private class LoadContacts extends AsyncTask<Long, Object, Cursor> {
DatabaseConnector dbConnector = new DatabaseConnector(ViewCountry.this);
#Override
protected Cursor doInBackground(Long... params) {
dbConnector.open();
return dbConnector.getOneContact(params[0]);
}
#Override
protected void onPostExecute(Cursor result) {
super.onPostExecute(result);
result.moveToFirst();
int nameIndex = result.getColumnIndex("name");
int capIndex = result.getColumnIndex("cap");
int codeIndex = result.getColumnIndex("code");
int timeIndex = result.getColumnIndex("time");
int ssidIndex = result.getColumnIndex("ssid");
nameTv.setText(result.getString(nameIndex));
capTv.setText(result.getString(capIndex));
timeTv.setText(result.getString(timeIndex));
codeTv.setText(result.getString(codeIndex));
ssidTv.setText(result.getString(ssidIndex));
result.close();
dbConnector.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view_country_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.editItem:
Intent addEditContact = new Intent(this, AddEditDevice.class);
// addEditContact.putExtra(CountryList.ROW_ID, rowID);
// addEditContact.putExtra("name", nameTv.getText());
// addEditContact.putExtra("cap", capTv.getText());
// addEditContact.putExtra("code", codeTv.getText());
startActivity(addEditContact);
return true;
case R.id.user1SettingsSave:
Intent Tap = new Intent(this, Tap.class);
startActivity(Tap);
return true;
case R.id.deleteItem:
deleteContact();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void deleteContact() {
AlertDialog.Builder alert = new AlertDialog.Builder(ViewCountry.this);
alert.setTitle(R.string.confirmTitle);
alert.setMessage(R.string.confirmMessage);
alert.setPositiveButton(R.string.delete_btn,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int button) {
final DatabaseConnector dbConnector = new DatabaseConnector(
ViewCountry.this);
AsyncTask<Long, Object, Object> deleteTask = new AsyncTask<Long, Object, Object>() {
#Override
protected Object doInBackground(Long... params) {
dbConnector.deleteContact(params[0]);
return null;
}
#Override
protected void onPostExecute(Object result) {
finish();
}
};
deleteTask.execute(new Long[] { rowID });
}
});
alert.setNegativeButton(R.string.cancel_btn, null).show();
}
}
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":" + timeEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
minutes,
Long.toString(minutes),
ssidTextView.getText().toString());
You have that code to add a contact, BUT in your database conector you have:
public void insertContact(String name,
String cap,
String code,
String time,
long minutes,
String ssid,
String string){
I think that don't match, so this is why don't insert correctly.
BTW i can't comment at the moment because i need 50 reputation.
Regards
USE CREATE TABLE IF NOT EXISTS T/N then your problem wil be solved.
otherwise it will override the current table at the same time all the data will be lost.

Categories