I'm trying to set a second inflated layout in my activity, the one that works inflates to set an alarm from a timepicker, the second one inflates a number picker to set an amount. So far the second button will not respond or, based on another set of code (one shown) I get a runtime error. Can anyone tell me what I am doing wrong?
package org.iimed.www;
import java.util.Calendar;
import org.iimed.www.DateTimePicker.DateWatcher;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class CaAdd extends Activity implements OnClickListener {
Button button_click, amount;
TextView dateResult, date2;
int hrs, min;
int amountt = 0;
EditText amountedit;
String amountText;
Dialog amountdialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.datetimeactivity);
dateResult = (TextView) findViewById(R.id.textview1);
date2 = (TextView) findViewById(R.id.textView2);
button_click = (Button) findViewById(R.id.setbtn);
amount = (Button) findViewById(R.id.amountbtn);
amount.setOnClickListener(this);
button_click.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.setbtn:
amountdialog = new Dialog(this);
final Dialog mDateTimeDialog = new Dialog(this);
// Inflate the root layout
final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater()
.inflate(R.layout.date_time_dialog, null);
// Grab widget instance
final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView
.findViewById(R.id.DateTimePicker);
mDateTimePicker.initData();
Button setDateBtn = (Button) mDateTimeDialogView
.findViewById(R.id.SetDateTime);
// Update demo TextViews when the "OK" button is clicked
setDateBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(CaAdd.this, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getActivity(CaAdd.this, 2,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
hrs = mDateTimePicker.getHour();
min = mDateTimePicker.getMinute();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hrs);
calendar.set(Calendar.MINUTE, min);
calendar.set(Calendar.SECOND, 0);
alm.set(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), pi);
mDateTimePicker.clearFocus();
String result_string = mDateTimePicker.getMonth() + "/"
+ String.valueOf(mDateTimePicker.getDay()) + "/"
+ String.valueOf(mDateTimePicker.getYear()) + " "
+ String.valueOf(mDateTimePicker.getHour()) + ":"
+ String.valueOf(mDateTimePicker.getMinute());
if (mDateTimePicker.getHour() > 12)
result_string = result_string + "PM";
else
result_string = result_string + "AM";
date2.setText(result_string);
mDateTimeDialog.dismiss();
}
});
Button cancelBtn = (Button) mDateTimeDialogView
.findViewById(R.id.CancelDialog);
// Cancel the dialog when the "Cancel" button is clicked
cancelBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mDateTimePicker.reset();
mDateTimeDialog.cancel();
}
});
// Reset Date and Time pickers when the "Reset" button is clicked
Button resetBtn = (Button) mDateTimeDialogView
.findViewById(R.id.ResetDateTime);
resetBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mDateTimePicker.reset();
}
});
Button amountbtn = (Button) findViewById(R.id.amountbtn);
amountbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Inflate the root layout
final RelativeLayout amountView = (RelativeLayout) getLayoutInflater()
.inflate(R.layout.amount, null);
// Grab widget instance
amountdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
amountdialog.setContentView(amountView);
amountdialog.show();
amountedit = (EditText) amountView
.findViewById(R.id.amount);
ImageButton increase = (ImageButton) amountView
.findViewById(R.id.increase);
increase.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
amountt++;
amountText = Integer.toString(amountt);
amountedit.setHint(amountText);
}
});
ImageButton decrease = (ImageButton) amountView
.findViewById(R.id.decrease);
decrease.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
amountt--;
amountText = Integer.toString(amountt);
amountedit.setHint(amountText);
}
});
amountdialog.dismiss();
// No title on the dialog window
mDateTimeDialog
.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Set the dialog content view
mDateTimeDialog.setContentView(mDateTimeDialogView);
// Display the dialog
mDateTimeDialog.show();
}
});
}
}
}
Related
I will make this as specific as possible. I've created a Page Which uses RecyclerAdapter to show card items in grid.And I have set a Default Activity for each card using OnclickListner ,So when you click any card item it will take you to that Default Activity Like this Image.And mine one Look Like this click here.My question is how can I open a perticular card in recyler Adapter from a different activity.In my app I want that when I press Go button on popup It will it toggle lvl2 or the next card to open the game activity.
Java file for RecyclerAdapter
package com.example.apptuzzle;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private Context mcontext;
private List<InGameContent> mData;
public RecyclerViewAdapter(Context mcontext, List<InGameContent> mData){
this.mcontext = mcontext;
this.mData = mData;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater mInflater = LayoutInflater.from(mcontext);
view = mInflater.inflate(R.layout.cardview_items1,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.Title.setText(mData.get(position).getTitle());
holder.Title.setTag(position);
holder.cardview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = (int) getItemId(position) + 1;
Intent intent = new Intent(mcontext,InGame_wrkfunction.class);
intent.putExtra("pos", pos);
//passing data to the InGame_wrkfunction.class
intent.putExtra("Answrr",mData.get(position).getAnswrr());
intent.putExtra("Thumbnail",mData.get(position).getThumbnail());
intent.putExtra("Description",mData.get(position).getDescription());
// start the activity
mcontext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView Title;
CardView cardview;
public MyViewHolder(View itemView) {
super(itemView);
Title = (TextView) itemView.findViewById(R.id.LvL_id1);
cardview = (CardView) itemView.findViewById(R.id.cardview_id);
}
}
}
Default Game Activity
package com.example.apptuzzle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class InGame_wrkfunction extends AppCompatActivity {
private Button btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, btndot; //Buttons Declaration
private Button btnclr, btnsubm, popup_g_button1;
private TextView txtv1, txtv2, popup_g_msg1, popup_g_des1,highscore1;
int scores = 0;
private LinearLayout Popup_layout11;
private Animation pop_animation;
private ImageView img,popup_g_img1,popup_b_img; //Question Declaration
private TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_in_game_wrkfunction);
btn0 = (Button) findViewById(R.id.Btn0);
btn1 = (Button) findViewById(R.id.Btn1);
btn2 = (Button) findViewById(R.id.Btn2);
btn3 = (Button) findViewById(R.id.Btn3);
btn4 = (Button) findViewById(R.id.Btn4);
btn5 = (Button) findViewById(R.id.Btn5);
btn6 = (Button) findViewById(R.id.Btn6);
btn7 = (Button) findViewById(R.id.Btn7);
btn8 = (Button) findViewById(R.id.Btn8);
btn9 = (Button) findViewById(R.id.Btn9);
btndot = (Button) findViewById(R.id.Btndot);
btnclr = (Button) findViewById(R.id.BtnClr);
btnsubm = (Button) findViewById(R.id.BtnSubm);
img = (ImageView) findViewById(R.id.gamethumbnail);
txtv1 = (TextView) findViewById(R.id.TxtV1);
txt = (TextView) findViewById(R.id.TxtV2);
Popup_layout11 = findViewById(R.id.Popup_layout11);
txt = (TextView) findViewById(R.id.TxtV2);
popup_g_button1 = findViewById(R.id.Popup_G_button1);
popup_g_msg1 = findViewById(R.id.Popup_G_msg1);
popup_g_des1 = findViewById(R.id.Popup_G_des1);
popup_g_img1 = findViewById(R.id.Popup_G_Img12);
highscore1 = findViewById(R.id.ScoreCounter1);
pop_animation = AnimationUtils.loadAnimation(this, R.anim.pop_up);
btn0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + "0");
}
});
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + "1");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + "2");
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + "3");
}
});
btn4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + "4");
}
});
btn5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + "5");
}
});
btn6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + "6");
}
});
btn7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + "7");
}
});
btn8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + "8");
}
});
btn9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + "9");
}
});
btndot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + ".");
}
});
btnclr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackground(null);
txtv1.setText(null);
}
});
// Receive data
Intent intent = getIntent();
String Description = intent.getExtras().getString("Description"); //It ll fetch data from Description()
int image = intent.getExtras().getInt("Thumbnail");
int pos = intent.getExtras().getInt("pos");
final String answrr1 = intent.getExtras().getString("Answrr");
//Setting Values
img.setImageResource(image); ////It ll replace the image that was fetched previously
txt.setText(Description);
//Load Scores
SharedPreferences myscores = this.getSharedPreferences("MyAwesomeScores", Context.MODE_PRIVATE);
scores = myscores.getInt("scores", 0); //0 tha phehele
highscore1.setText("Scores:" + scores);
btnsubm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String a = txtv1.getText().toString();
if (a.equals(answrr1)) {
scores += 30;
//Save scores
SharedPreferences myscores = getSharedPreferences("MyAwesomeScores", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = myscores.edit();
editor.putInt("scores", scores);
editor.commit();
v.setOnClickListener(null);//Remove setOnClickListener
highscore1.setText("Scores:" + scores);
Popup_layout11.setVisibility(LinearLayout.VISIBLE);
Popup_layout11.setAnimation(pop_animation);
Popup_layout11.animate();
pop_animation.start();
} else {
scores -= 30;
//Save scores
SharedPreferences myscores = getSharedPreferences("MyAwesomeScores", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = myscores.edit();
editor.putInt("scores", scores);
editor.commit();
v.setOnClickListener(null);//Remove setOnClickListener
highscore1.setText("Scores:" + scores);
popup_g_img1.setImageResource(R.drawable.sadface11);
popup_g_msg1.setText("Ohh Snap!");
popup_g_des1.setText("Don't worry Kid you just tap the button to move on to the next lesson. REMEMBER 'never waste time'.");
Popup_layout11.setVisibility(LinearLayout.VISIBLE);
Popup_layout11.setAnimation(pop_animation);
Popup_layout11.animate();
pop_animation.start();
}
}
});
}
}
/*Two Ways of Putting One Animation In an activity
* 1st One
* Anim1 = AnimationUtils.loadAnimation(this, R.anim.new_animfile1);
// pop_img1.setVisibility(View.GONE);
Btn1.setOnClickListener(new View.OnClickListener() { <-----In this type you can put animation inside On Click Listener
#Override
public void onClick(View v) {
Layout1.setVisibility(LinearLayout.VISIBLE);
Anim1.setDuration(500);
Layout1.setAnimation(Anim1);
Layout1.animate();
Anim1.start();
}
});
*
*
* 2nd One
* public class MyActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); <-----In this type you can set another class outside the OnCreate Bundle
}
public void animate(View view){
LinearLayout dialog = (LinearLayout)findViewById(R.id.dialog);
dialog.setVisibility(LinearLayout.VISIBLE);
Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim);
animation.setDuration(500);
dialog.setAnimation(animation);
dialog.animate();
animation.start();
}
}
* */
What I understand is you want to open different activities on each card click.If it's correct then,
use switch inside your onClick and open your activity on a particular item click
#Override
public void onClick(View v) {
final Intent intent;
switch (getAdapterPostion()){
case 0:
intent = new Intent(context, FirstActivity.class);
break;
case 1:
intent = new Intent(context, SecondActivity.class);
break;
...
default:
intent = new Intent(context, DefaultActivity.class);
break;
}
context.startActivity(intent);
}
Or Use:-
#Override
public void onClick(View v) {
final Intent intent;
if (getAdapterPosition() == sth){
intent = new Intent(context, OneActivity.class);
} else if (getPosition() == sth2){
intent = new Intent(context, SecondActivity.class);
} else {
intent = new Intent(context, DifferentActivity.class);
}
context.startActivity(intent);
}
I'm trying to Save an editText to Sharedprefrences so that it displays in the TextView amnt. It's displaying it but not saving it? what am I doing wrong? I am new to this, just a little weekend hobby so I'm sorry if this is a stupid question, thanks for your time.
package org.iimed.www;
import java.util.Calendar;
import org.iimed.www.DateTimePicker.DateWatcher;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.inputmethodservice.Keyboard.Key;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class CaAdd extends Activity implements DateWatcher,OnClickListener{
Button button_click,amount;
int amountt = 0;
Key at;
EditText amountedit;
String amountText;
String amountString;
TextView dateResult, date2,amnt;
int hrs,min;
SharedPreferences.Editor editor ;
SharedPreferences prefs;
String amntprefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.datetimeactivity);
dateResult = (TextView)findViewById(R.id.textview1);
date2 = (TextView)findViewById(R.id.textView2);
button_click = (Button)findViewById(R.id.setbtn);
button_click.setOnClickListener(this);
amnt = (TextView)findViewById(R.id.amountText);
}
public final String AT = "Amount";
public void loadDefaultSharedPreferences() {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs != null) {
String loadUsername= prefs.getString(
AT , null);
if (loadUsername != null && !loadUsername.isEmpty()) {
amnt.setText(loadUsername);
}}}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.setbtn:
final Dialog mDateTimeDialog = new Dialog(this);
// Inflate the root layout
final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater().inflate(R.layout.date_time_dialog, null);
// Grab widget instance
final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView.findViewById(R.id.DateTimePicker);
mDateTimePicker.setDateChangedListener(this);
mDateTimePicker.initData();
amountedit = (EditText)mDateTimeDialogView.findViewById(R.id.amountedit);
ImageButton increase = (ImageButton)mDateTimeDialogView.findViewById(R.id.increase);
increase.setOnClickListener(new OnClickListener(){
public void onClick(View v){
amountt++;
amountText = Integer.toString(amountt);
amountedit.setHint(amountText);
amnt.setText(amountText);
}
});
ImageButton decrease = (ImageButton)mDateTimeDialogView.findViewById(R.id.decrease);
decrease.setOnClickListener(new OnClickListener(){
public void onClick(View v){
amountt--;
amountText = Integer.toString(amountt);
amountedit.setHint(amountText);
amnt.setText(amountText);
}
});
Button setDateBtn = (Button)mDateTimeDialogView.findViewById(R.id.SetDateTime);
// Update demo TextViews when the "OK" button is clicked
setDateBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent=new Intent(CaAdd.this,AlarmReceiver.class);
PendingIntent pi=PendingIntent.getActivity(CaAdd.this, 2, intent,PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alm=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
hrs=mDateTimePicker.getHour();
min=mDateTimePicker.getMinute();
Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,hrs);
calendar.set(Calendar.MINUTE, min);
calendar.set(Calendar.SECOND, 0);
alm.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(), pi);
mDateTimePicker.clearFocus();
String result_string = mDateTimePicker.getMonth() + "/" + String.valueOf(mDateTimePicker.getDay()) + "/" + String.valueOf(mDateTimePicker.getYear())
+ " " + String.valueOf(mDateTimePicker.getHour()) + ":" + String.valueOf(mDateTimePicker.getMinute());
if(mDateTimePicker.getHour() > 12) result_string = result_string + "PM";
else result_string = result_string + "AM";
date2.setText(result_string);
mDateTimeDialog.dismiss();
}
});
Button cancelBtn = (Button)mDateTimeDialogView.findViewById(R.id.CancelDialog);
// Cancel the dialog when the "Cancel" button is clicked
cancelBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mDateTimePicker.reset();
mDateTimeDialog.cancel();
}
});
// Reset Date and Time pickers when the "Reset" button is clicked
Button resetBtn = (Button)mDateTimeDialogView.findViewById(R.id.ResetDateTime);
resetBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mDateTimePicker.reset();
}
});
mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Set the dialog content view
mDateTimeDialog.setContentView(mDateTimeDialogView);
//Display the dialog
mDateTimeDialog.show();
}}
public void onDateChanged(Calendar c) {
Log.e("","" + c.get(Calendar.MONTH) + " " + c.get(Calendar.DAY_OF_MONTH)+ " " + c.get(Calendar.YEAR));
String result_string =String.valueOf(c.get(Calendar.MONTH)+1) + "/" + String.valueOf(c.get(Calendar.DAY_OF_MONTH)) + "/" + String.valueOf(c.get(Calendar.YEAR));
// _tvUserDOB.setTypeface(CGlobalVariables.tfFoEnglish);
dateResult.setText(result_string+" (mm/dd/yyyy)");
}
public void saveDefaultPreferences() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);{
SharedPreferences.Editor editor = prefs.edit();
final String AT = "Amount";
editor.putString(AT,amountText);
editor.commit();}
}}
Shared preferences allows you to save and retrieve key, value pair data.
Initialization:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
// 0 - for private mode
Editor editor = pref.edit();
Storing Data:
editor.putString("key_name", "string value"); // Storing string
editor.commit(); // commit changes
Retrieving Data:
pref.getString("key_name", null); // getting String
To know more about SharedPreferences or to try out a simple example, check this
You can only save key-value pairs for some of the primitives and String (String set also) only. Android views can never be saved anywhere.
SharedPreferences manager =PreferenceManager.getDefaultSharedPreferences(context);
Use it for saving and retrieving data as follows
// for saving data
manager.edit().putString(context.getString(AT), YOUR_TEXT).commit()
// for retrieving data
manager.getString(context.getString(AT), "");
I have a DateTimePicker with a little "amount" editext that I save the Sharedpref
but for some reason if I "touch" the EditText and enter the amount in manually, the text is black and doesn't transfer to the TextView, if using the imagebuttons increase and decrease the editText will work as intended. If I enter the dates and times in this manner though it does work, what am I missing?
ImageButton increase = (ImageButton)mDateTimeDialogView.findViewById(R.id.increase);
increase.setOnClickListener(new OnClickListener(){
public void onClick(View v){
amountt++;
amountText = Integer.toString(amountt);
amountedit.setHint(amountText);
amnt.setText(amountText);
editor.putString("numbers", amountText);
editor.commit();
}
});
ImageButton decrease = (ImageButton)mDateTimeDialogView.findViewById(R.id.decrease);
decrease.setOnClickListener(new OnClickListener(){
public void onClick(View v){
amountt--;
amountText = Integer.toString(amountt);
amountedit.setHint(amountText);
amnt.setText(amountText);
editor.putString("numbers", amountText);
editor.commit();
}
});
The relevant EditText info
amountedit=(EditText)mDateTimeDialogView.findViewById(R.id.amountedit);
The TextView it displays to
amnt = (TextView)findViewById(R.id.amountText);
The XML of EditText
<EditText
android:id="#+id/amountedit"
android:layout_width="50dp"
android:key = "amntkey"
android:layout_height="wrap_content"
android:layout_above="#+id/linearLayout1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="62dp"
android:ems="10"
android:inputType="number"
android:persistent="true" />
The complete java activity it takes place:
import java.util.Calendar;
import java.util.HashMap;
import org.iimed.www.DateTimePicker.DateWatcher;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.inputmethodservice.Keyboard.Key;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class CaAdd extends Activity implements DateWatcher,OnClickListener{
Button button_click;
int amountt = 0;
String amountText;
String number = "numbers";
TextView amnt;
TextView dateResult, date2;
int hrs,min;
SharedPreferences pref;
String time = "time";
String get;
String sTime;
String amount ;
EditText amountedit;
String result_string;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.datetimeactivity);
dateResult = (TextView)findViewById(R.id.textview1);
date2 = (TextView)findViewById(R.id.textView2);
button_click = (Button)findViewById(R.id.setbtn);
pref = getSharedPreferences("prefs", Context.MODE_PRIVATE);
button_click.setOnClickListener(this);
amnt = (TextView)findViewById(R.id.amountText);
pref = getSharedPreferences("prefs", Context.MODE_PRIVATE);
amountText = Integer.toString(amountt);
amount = amnt.toString();
get = pref.getString("numbers",amountText);
sTime = pref.getString("time", result_string);
amnt.setText(get);
date2.setText(sTime) ;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.setbtn:
final Dialog mDateTimeDialog = new Dialog(this);
// Inflate the root layout
final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater().inflate(R.layout.date_time_dialog, null);
// Grab widget instance
final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView.findViewById(R.id.DateTimePicker);
mDateTimePicker.setDateChangedListener(this);
mDateTimePicker.initData();
amountedit=(EditText)mDateTimeDialogView.findViewById(R.id.amountedit);
ImageButton increase = (ImageButton)mDateTimeDialogView.findViewById(R.id.increase);
increase.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Editor editor = pref.edit();
amountt++;
amountText = Integer.toString(amountt);
amountedit.setHint(amountText);
amnt.setText(amountText);
String amount =amnt.toString();
editor.putString("numbers", amountText);
editor.commit();
}
});
ImageButton decrease = (ImageButton)mDateTimeDialogView.findViewById(R.id.decrease);
decrease.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Editor editor = pref.edit();
amountt--;
amountText = Integer.toString(amountt);
amountedit.setHint(amountText);
amnt.setText(amountText);
String edi = amountedit.toString();
editor.putString("numbers", amountText);
editor.commit();
}
});
Button setDateBtn = (Button)mDateTimeDialogView.findViewById(R.id.SetDateTime);
setDateBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent=new Intent(CaAdd.this,AlarmReceiver.class);
PendingIntent pi=PendingIntent.getActivity(CaAdd.this, 2, intent,PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alm=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
Editor editor = pref.edit();
hrs=mDateTimePicker.getHour();
min=mDateTimePicker.getMinute();
Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,hrs);
calendar.set(Calendar.MINUTE, min);
calendar.set(Calendar.SECOND, 0);
alm.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(), pi);
mDateTimePicker.clearFocus();
result_string =
String.valueOf(mDateTimePicker.getHour()) + ":" + String.valueOf(mDateTimePicker.getMinute());
if(mDateTimePicker.getHour() > 12) result_string = result_string + "PM";
else result_string = result_string + "AM";
date2.setText(result_string);
editor.putString("time",result_string);
editor.commit();
mDateTimeDialog.dismiss();
}
});
Button cancelBtn = (Button)mDateTimeDialogView.findViewById(R.id.CancelDialog);
cancelBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mDateTimePicker.reset();
mDateTimeDialog.cancel();
}
});
Button resetBtn = (Button)mDateTimeDialogView.findViewById(R.id.ResetDateTime);
resetBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mDateTimePicker.reset();
}
});
mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDateTimeDialog.setContentView(mDateTimeDialogView);
mDateTimeDialog.show();}}
public void onDateChanged(Calendar c) {
Log.e("","" + c.get(Calendar.MONTH) + " " + c.get(Calendar.DAY_OF_MONTH)+ " " + c.get(Calendar.YEAR));
String result_string =String.valueOf(c.get(Calendar.MONTH)+1) + "/" + String.valueOf(c.get(Calendar.DAY_OF_MONTH)) + "/" + String.valueOf(c.get(Calendar.YEAR));
dateResult.setText(null);
}}
Your code isn't clear, you should post code about that EditText you're talking about.
BTW, to get what you would like, you can try to do Sharedpref's edit & commit
when your EditText's text changed, although it's a bad design...
You need a Text change listener
EditText.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{}
#Override
public void afterTextChanged(Editable s)
{}
});
In my project i several onClick listeners, and all of them are fine, but one, i can not find and error in the code, if i delete the code and retype it and save it, it is fine without errors, if i close and eclipse and comeback later, variable cant be resolved again.
This is where it cant be resolved in the code:
Button webButton = (Button) newStockRow.findViewById(R.id.webButton);
webButton.setOnClickListener(getStockFromWebClickListener);
and this is how i create it:
public OnClickListener getStockFromWebClickListener = new OnClickListener(){
#Override
public void onClick(View arg0) {
TableRow tableR = (TableRow) arg0.getParent();
TextView stock = (TextView) tableR.findViewById(R.id.stockSymbolTextView);
String stockSymbol = stock.getText().toString();
String stockURL = getString(R.string.yahoo_stock_url) + stockSymbol;
Intent getStockWebPage = new Intent(Intent.ACTION_VIEW, Uri.parse(stockURL));
startActivity(getStockWebPage);
}
};
Code for full File:
package com.gscore.quotestock;
import java.util.Arrays;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class StockQ extends Activity {
public final static String STOCK_SYMBOL = "com.gscore.quotestock.STOCK";
private SharedPreferences stockSymbolsEntered;
private TableLayout stockTableScrollView;
private EditText stockSymbolET;
Button enterStockSymbolButton;
Button deleteStocksButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stock_q);
// Get user stock list
stockSymbolsEntered = getSharedPreferences("stockList", MODE_PRIVATE);
// Initialize UI components
stockTableScrollView = (TableLayout) findViewById(R.id.stockTableLayout);
stockSymbolET = (EditText) findViewById(R.id.stockSymbolEditText);
enterStockSymbolButton= (Button) findViewById(R.id.enterButton);
deleteStocksButton= (Button) findViewById(R.id.deleteAllButton);
// Set ClickListeners
enterStockSymbolButton.setOnClickListener(enterButtonClickListener);
deleteStocksButton.setOnClickListener(deleteButtonClickListener);
updateSavedStockList(null);
}
private void updateSavedStockList(String newStockSymbol){
String[] stocks = stockSymbolsEntered.getAll().keySet().toArray(new String[0]);
Arrays.sort(stocks, String.CASE_INSENSITIVE_ORDER);
if (newStockSymbol != null){
insertStockInStockTable(newStockSymbol, Arrays.binarySearch(stocks, newStockSymbol));
} else {
for(int i = 0; i < stocks.length; i++){
insertStockInStockTable(stocks[i], i);
}
}
}
private void saveStockSymbol(String newStock){
String isTheStockNew = stockSymbolsEntered.getString(newStock, null);
SharedPreferences.Editor preferencesEditor = stockSymbolsEntered.edit();
preferencesEditor.putString(newStock, newStock);
preferencesEditor.commit();
if(isTheStockNew == null){
updateSavedStockList(newStock);
}
}
private void insertStockInStockTable(String stock, int arrayIndex){
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View newStockRow = inflater.inflate(R.layout.stock_quote_row, null);
TextView newStockTextView = (TextView) newStockRow.findViewById(R.id.stockSymbolTextView);
newStockTextView.setText(stock);
Button stockQuoteButton = (Button) newStockRow.findViewById(R.id.stockQuoteButton);
stockQuoteButton.setOnClickListener(getStockActivityListener);
Button webButton = (Button) newStockRow.findViewById(R.id.webButton);
webButton.setOnClickListener(getStockFromWebClickListener);
stockTableScrollView.addView(newStockRow, arrayIndex);
}
public OnClickListener enterButtonClickListener= new OnClickListener(){
#Override
public void onClick(View v) {
if(stockSymbolET.getText().length() > 0){
saveStockSymbol(stockSymbolET.getText().toString());
stockSymbolET.setText("");
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(stockSymbolET.getWindowToken(), 0);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(StockQ.this);
builder.setTitle(R.string.invalid_stock_symbol);
builder.setPositiveButton(R.string.ok, null);
builder.setMessage(R.string.missing_stock_symbol);
AlertDialog theAlertDialog = builder.create();
theAlertDialog.show();
}
}
};
private void deleteAllStocks(){
stockTableScrollView.removeAllViews();
}
public OnClickListener deleteButtonClickListener = new OnClickListener(){
#Override
public void onClick(View v) {
deleteAllStocks();
SharedPreferences.Editor preferencesEditor = stockSymbolsEntered.edit();
preferencesEditor.clear();
preferencesEditor.commit();
}
};
public OnClickListener getStockActivityListener = new OnClickListener(){
#Override
public void onClick(View v) {
TableRow tableR = (TableRow) v.getParent();
TextView stock = (TextView) tableR.findViewById(R.id.stockSymbolTextView);
String stockSymbol = stock.getText().toString();
Intent intent = new Intent(StockQ.this, StockInfoActivity.class);
intent.putExtra(STOCK_SYMBOL, stockSymbol);
startActivity(intent);
}
};
public OnClickListener getStockFromWebClickListener = new OnClickListener(){
#Override
public void onClick(View arg0) {
TableRow tableR = (TableRow) arg0.getParent();
TextView stock = (TextView) tableR.findViewById(R.id.stockSymbolTextView);
String stockSymbol = stock.getText().toString();
String stockURL = getString(R.string.yahoo_stock_url) + stockSymbol;
Intent getStockWebPage = new Intent(Intent.ACTION_VIEW, Uri.parse(stockURL));
startActivity(getStockWebPage);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.stock_q, menu);
return true;
}
}
That's indeed an annoying problem with importing an inner class (or interface) on Eclipse.
What you have to do is instead of:
new OnClickListener()
Write:
new View.OnClickListener()
And make sure that android.view.View is imported.
Im having problem sharing a global variable that I need to retain across multiple activities. This variable is created in TextPlay class and copied onto DailyDataEntry class. I have done some research sharing variables between two activities using Intent but Im looking to share that variable to multiple classes. I think I will have to extends Application but all my other classes are extending Activity already. How am I supposed to extend Application while extending Activity? Thanks a million
///TextPlay Class///
package com.armstrong.y.android.app;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;
public class TextPlay extends Activity implements View.OnClickListener {
Button chkCmd;
ToggleButton passTog;
EditText input;
TextView display;
EditText etUserId;
Button btnUserId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
baconAndEggs();
passTog.setOnClickListener(this);
chkCmd.setOnClickListener(this);
// Share variables between classes controls
etUserId = (EditText) findViewById(R.id.etUserId);
btnUserId = (Button) findViewById(R.id.btnUserId);
}
private void baconAndEggs() {
// TODO Auto-generated method stub
chkCmd = (Button) findViewById(R.id.bResults);
passTog = (ToggleButton) findViewById(R.id.tbPassword);
input = (EditText) findViewById(R.id.etCommands);
display = (TextView) findViewById(R.id.tvResults);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bResults:
// get the text from the command box then convert it to string
String check = input.getText().toString();
display.setText(check);
if (check.contentEquals("left")) {
display.setGravity(Gravity.LEFT);
} else if (check.contentEquals("center")) {
display.setGravity(Gravity.CENTER);
} else if (check.contentEquals("right")) {
display.setGravity(Gravity.RIGHT);
} else if (check.contentEquals("blue")) {
display.setTextColor(Color.BLUE);
display.setText("blue");
} else if (check.contains("hellow")) {
Random crazy = new Random();
display.setText("hello!!!!");
display.setTextSize(crazy.nextInt(75));
display.setTextColor(Color.rgb(crazy.nextInt(255),
crazy.nextInt(255), crazy.nextInt(255)));
switch (crazy.nextInt(3)) {
case 0:
display.setGravity(Gravity.LEFT);
break;
case 1:
display.setGravity(Gravity.CENTER);
break;
case 2:
display.setGravity(Gravity.RIGHT);
break;
}
} else {
display.setText("invalid");
display.setGravity(Gravity.CENTER);
display.setTextColor(Color.BLACK);
}
break;
case R.id.tbPassword:
// If toggle button is set to ON, password will be ***
if (passTog.isChecked()) {
input.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_PASSWORD);
} else {
// if toggle is off, its going be plain text
input.setInputType(InputType.TYPE_CLASS_TEXT);
}
break;
}
}
}
///DailyDataEntry Class///
package com.armstrong.y.android.app;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class DailyDataEntry extends Activity {
String strdate;
EditText etGetDate;
Calendar calendarDateToday = Calendar.getInstance();
Calendar calendarDateNext = Calendar.getInstance();
Calendar calendarDatePrevious = Calendar.getInstance();
int counterNext = 0;
int counterPrevious = 0;
Button btnTodayDate;
Button btnPreviousDate;
Button btnGetNextDate;
EditText etDailyCaloriesIn;
EditText etDailyCaloriesOut;
EditText etDailyAnxietyLevel;
EditText etDailySleepQuality;
TextView tvUserId;
Button btnSubmit;
Button btnReset;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.daily_data_entry);
// Toast Message Warning
Toast.makeText(getApplicationContext(),
"DO NOT LEAVE FIELD BLANK OR CRASH IS ON YOU!",
Toast.LENGTH_LONG).show();
btnTodayDate = (Button) findViewById(R.id.btnGetTodayDate);
btnPreviousDate = (Button) findViewById(R.id.btnGetPreviousDate);
btnGetNextDate = (Button) findViewById(R.id.btnGetNextDate);
etGetDate = (EditText) findViewById(R.id.etGetDate);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnReset = (Button) findViewById(R.id.btnReset);
etDailyCaloriesIn = (EditText) findViewById(R.id.etDailyCaloriesIn);
etDailyCaloriesOut = (EditText) findViewById(R.id.etDailyCaloriesOut);
etDailyAnxietyLevel = (EditText) findViewById(R.id.etDailyAnxietyLevel);
etDailySleepQuality = (EditText) findViewById(R.id.etDailySleepQuality);
tvUserId = (TextView) findViewById(R.id.tvUserId);
// When Submit Button is clicked
btnSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Grab User Input from EditText and Convert input String to
// Integer
int check1 = Integer.parseInt(etDailyCaloriesIn.getText()
.toString());
int check2 = Integer.parseInt(etDailyCaloriesOut.getText()
.toString());
int check4 = Integer.parseInt(etDailyAnxietyLevel.getText()
.toString());
int check5 = Integer.parseInt(etDailySleepQuality.getText()
.toString());
strdate = etGetDate.getText().toString();
// Run Legal Value Integrity Check
if (strdate.length() != 8) {
etGetDate.setText("Please enter in the correct format.");
} else if (strdate.equals("")) {
etGetDate.setText("Please enter a date.");
} else if (check1 > 10 || check1 < 1) {
etDailyCaloriesIn.setText("Incorrect Value!");
} else if (check2 > 10 || check2 < 1) {
etDailyCaloriesOut.setText("Incorrect Value!");
} else if (check4 > 10 || check4 < 1) {
etDailyAnxietyLevel.setText("Incorrect Value!");
} else if (check5 > 10 || check5 < 1) {
etDailySleepQuality.setText("Incorrect Value!");
} else {
etGetDate.setText("Submited!");
etDailyCaloriesIn.setText("Submited!");
etDailyCaloriesOut.setText("Submited!");
etDailyAnxietyLevel.setText("Submited!");
etDailySleepQuality.setText("Submited!");
}
}
});
// When Reset Button is Clicked
btnReset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String empty = "";
etDailyCaloriesIn.setText(empty);
etDailyCaloriesOut.setText(empty);
etDailyAnxietyLevel.setText(empty);
etDailySleepQuality.setText(empty);
etGetDate.setText(empty);
}
});
// Capture Today's Date
btnTodayDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy");
strdate = sdf.format(calendarDateToday.getTime());
etGetDate.setText(strdate);
}
});
// Capture Previous's Date
btnPreviousDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy");
if (counterPrevious == 0) {
calendarDatePrevious.add(Calendar.DATE, -1);
}
strdate = sdf.format(calendarDatePrevious.getTime());
etGetDate.setText(strdate);
counterPrevious++;
}
});
// Capture Next's Date
btnGetNextDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy");
if (counterNext == 0) {
calendarDateNext.add(Calendar.DATE, +1);
}
strdate = sdf.format(calendarDateNext.getTime());
etGetDate.setText(strdate);
counterNext++;
}
});
}
}
Create class that will extends to Application and use it in the following manner whenever you need it:
MyApplication myAppHelper = (MyApplication) context.getApplication();
myAppHelper.setWhatever(whatever);
Whatever whatever = myAppHelper.getWhatever();