I have read many tutorial about CRUD SQLite, but most of them use Cursor to get values data and Button to call EditScreen. Any one lead me how to implementing i.putExtras in my Edit Menu Toolbar, please? I want to show again my data in EditText Form.
public class DetailStaffActivity extends AppCompatActivity {
private DBHandler dbHandler;
private TextView txt_resultnomor, txt_resultnama, txt_resulttempatlahir, txt_resulttanggallahir;
private List<Staff> staffList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.staff_details);
dbHandler = new DBHandler(this);
//ambil data
Intent i=getIntent();
final String nomor=i.getExtras().getString("nomor");
final String nama=i.getExtras().getString("nama");
final String tempatlahir = i.getExtras().getString("tempat_lahir");
final String tanggallahir=i.getExtras().getString("tanggal_lahir");
//inisialisasi dulu
txt_resultnomor = (TextView) findViewById(R.id.txt_resultnomor);
txt_resultnama = (TextView) findViewById(R.id.txt_resultnama);
txt_resulttempatlahir = (TextView) findViewById(R.id.txt_resulttempatlahir);
txt_resulttanggallahir = (TextView) findViewById(R.id.txt_resulttanggallahir);
//set inisial dengan data yang telah diambil di dengan intent
txt_resultnomor.setText(nomor);
txt_resultnama.setText(nama);
txt_resulttempatlahir.setText(tempatlahir);
txt_resulttanggallahir.setText(tanggallahir);
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_detail, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_edit) {
public void onItemClick(View view, int position) { //here, error when set position in this menu//
// TODO Handle item click
Intent in = new Intent(this, UpdateStaffActivity.class);
Staff staff = staffList.get(position);
String getNama = staffList.get(position).getNama();
in.putExtra("nama", getNama);
startActivity(in);
return true;
}
if (id == R.id.action_delete) {
return true;
}
if (id == R.id.action_settings) {
// Intent i = new Intent(this, About.class);
//startActivity(i);
}
return super.onOptionsItemSelected(item);
}
}
Please, how implementing putExtras in
if (id == R.id.action_edit) { }
I got error when set position in this menu. Thanks.
Just remove this line
public void onItemClick(View view, int position) { //here, error when set position in this menu//
// TODO Handle item click
Intent in = new Intent(this, UpdateStaffActivity.class);
Staff staff = staffList.get(position);
String getNama = staffList.get(position).getNama();
And write like this.
if (id == R.id.action_edit) {
Intent in = new Intent(this, UpdateMuriddActivity.class);
in.putExtra("nomor", txt_resultnomor.getText().toString());
in.putExtra("nama", txt_resultnama.getText().toString());
in.putExtra("tempat_lahir", txt_resulttempatlahir.getText().toString());
startActivity(in);
Hope its help.
Related
I'm stuck for few days, and unfortunately dont know how to fix it.
I have DetailScreen.java that show data from MainScreen (one of recyclerview's list).
I tried this code but there is no effect, when i try to change use
COLUMN_NOMOR in my update function, i can change the name but
getting error when change the nomor. I guess, its right to use
COLUMN_ID in my update function because id is my PK-AI. So whether
because I didnt call COLUMN_ID in my DetailScreen? But how i can call my
id in my DetailsScreen also in my UpdateScreen?
If the data success updated, the screen will be automatically go to the DetailScreen again, but still showing old data. I had to go to MainActivity first to get the new data. Where code should i modified?
Here my Update function in my DBHandler.java
public int updateDataSiswa(Siswa siswa) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NOMOR, siswa.getNomor());
values.put(COLUMN_NAMA, siswa.getNama());
return db.update(TABLE_SISWA, values, COLUMN_ID + " = ?",
new String[]{String.valueOf(siswa.getId())});
}
Here DetailScreen.java
public class DetailScreen extends AppCompatActivity {
private TextView txt_resultnomor, txt_resultnama;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_details);
//put data
Intent i = getIntent();
final String id = i.getExtras().getString("id");
final String nomor = i.getExtras().getString("nomor");
final String nama = i.getExtras().getString("nama");
//inisialisasi
txt_resultnomor = (TextView) findViewById(R.id.txt_resultnomor);
txt_resultnama = (TextView) findViewById(R.id.txt_resultnama);
//set
txt_resultnomor.setText(nomor);
txt_resultnama.setText(nama);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_detail, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_edit) {
Intent in = new Intent(this, UpdateScreen.class);
in.putExtra("nomor", txt_resultnomor.getText().toString());
in.putExtra("nama", txt_resultnama.getText().toString());
startActivity(in);
}
if (id == R.id.action_delete) {
return true;
}
if (id == R.id.action_settings) {
// Intent i = new Intent(this, About.class);
//startActivity(i);
}
return super.onOptionsItemSelected(item);
}
}
Then here my UpdateScreen.java
public class UpdateScreen extends AppCompatActivity {
private EditText et_nomor;
private EditText et_nama;
private Button button_updatedata;
private DBHandler dbHandler;
private SiswaAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_screen);
dbHandler = new DBHandler(this);
initComponents();
}
private void initComponents(){
et_nomor = (EditText) findViewById(R.id.et_nomor);
et_nama = (EditText) findViewById(R.id.et_nama);
//ambil data
Intent in=getIntent();
final String id=in.getExtras().getString("id_siswa");
final String nomor=in.getExtras().getString("nomor");
final String nama=in.getExtras().getString("nama");
//set inisial
et_nomor.setText(nomor);
et_nama.setText(nama);
button_updatedata = (Button) findViewById(R.id.button_updatedata);
button_updatedata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validasiForm();
}
});
}
private void validasiForm() {
String form_nomor = et_nomor.getText().toString();
String form_nama = et_nama.getText().toString();
if (form_nomor.isEmpty()){
et_nomor.setError("Nomor belum diisi");
et_nomor.requestFocus();
}
else if (form_nama.isEmpty()){
et_nama.setError("Nama belum diisi");
et_nama.requestFocus();
}
else {
dbHandler.updateDataSiswa(new Siswa(form_nomor, form_nama));
List<Siswa> siswaList = dbHandler.getSemuaSiswa();
adapter = new SiswaAdapter(siswaList);
adapter.notifyDataSetChanged();
Toast.makeText(UpdateScreen.this, "Berhasil Memperbarui Data Siswa", Toast.LENGTH_SHORT).show();
MainSiswaActivity.mma.refresh();
finish();
}
}
}
I hope i tell clearly, help me please. Thanks.
where is your call to the update method you given public int updateDataSiswa(Siswa siswa)..? Also based on what you have provided...your notifyDataSetChanged() for adapter just tries to update the listview of the RecyclerView..
but it does not understand what underlying data has changed for it..you need to create a method for your Database Handler where you can fetch a List of new records..and then use this method to update your adapter with it and then set the new adapter to your listView in validasiForm() method..
please check this for more details...Android ListView not refreshing after notifyDataSetChanged
I have a notebook sample project and I want to add a "note counter" to it using shared preferences and each time the user adds a note increment the counter in createNote() method. I also added a TextView to show the counter, but the counter is always zero and doesnt increment by creating a new note! ! Help me please!
public class MainActivity extends ListActivity {
private static final int EDITOR_ACTIVITY_REQUEST = 1001;
private static final int MENU_DELETE_ID = 1002;
private int currentNoteId;
private NotesDataSource datasource;
List<NoteItem> notesList;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
datasource = new NotesDataSource(this);
refreshDisplay();
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(""+count);
}
private void refreshDisplay() {
notesList = datasource.findAll();
ArrayAdapter<NoteItem> adapter =
new ArrayAdapter<NoteItem>(this, R.layout.list_item_layout, notesList);
setListAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_create) {
createNote(null);
}
return super.onOptionsItemSelected(item);
}
public void createNote(View v) {
NoteItem note = NoteItem.getNew();
Intent intent = new Intent(this, NoteEditorActivity.class);
intent.putExtra(NoteItem.KEY, note.getKey());
intent.putExtra(NoteItem.TEXT, note.getText());
startActivityForResult(intent, EDITOR_ACTIVITY_REQUEST);
int defaultValue = getPreferences(MODE_PRIVATE).getInt("count_key", count);
++defaultValue;
getPreferences(MODE_PRIVATE).edit().putInt("count_key", defaultValue).commit();
count = getPreferences(MODE_PRIVATE).getInt("count_key", count);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
NoteItem note = notesList.get(position);
Intent intent = new Intent(this, NoteEditorActivity.class);
intent.putExtra(NoteItem.KEY, note.getKey());
intent.putExtra(NoteItem.TEXT, note.getText());
startActivityForResult(intent, EDITOR_ACTIVITY_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == EDITOR_ACTIVITY_REQUEST && resultCode == RESULT_OK) {
NoteItem note = new NoteItem();
note.setKey(data.getStringExtra(NoteItem.KEY));
note.setText(data.getStringExtra(NoteItem.TEXT));
datasource.update(note);
refreshDisplay();
}
}
}
Your help is appreciated. Thanks!
Based on discussion and answer given by #Rahul Tiwari...do the following modifications in your code.....
First create the instance TextView variable
//your instance variables
int count;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
//your code...
tv = (TextView) findViewById(R.id.textView1);
count = getSharedPreferences("NAME_FOR_SHARED_PREFERENCES", Context.MODE_PRIVATE).getInt("count_key", 0);
updateTextView();
}
void updateTextView(){
tv.setText(""+count);
}
//your code till here....
public void createNote(View v) {
NoteItem note = NoteItem.getNew();
SharedPreferences sharedPref = getSharedPreferences("NAME_FOR_SHARED_PREFERENCES", Context.MODE_PRIVATE);
sharedPref.edit().putInt("count_key", ++count).commit();
updateTextView()
/*for intial testing commenting this code block
Intent intent = new Intent(this, NoteEditorActivity.class);
intent.putExtra(NoteItem.KEY, note.getKey());
intent.putExtra(NoteItem.TEXT, note.getText());
startActivityForResult(intent, EDITOR_ACTIVITY_REQUEST);
*/
}
//your code.
Then you can start app multiple times and check want is the count value.
Note: When naming your shared preference files, you should use a name
that's uniquely identifiable to your app, such as
"com.example.myapp.PREFERENCE_FILE_KEY" for more detail refer
your counter is not being refreshed as you are not changing text in your text view after changing the count.
you need to use
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(""+count);
at the end of your createNote function
use getDefaultSharedPreferences to access your shared preference across activities in your app. refer this answer for example.
I am trying to compare 2 scores that I have made oldScore and best_score(both in Main_Screen). I think the problem is that the ints are not saving properly. There are no errors but if the best_Score is lower than the old_score it still changes it in the textview even though the best_score should be higher than the old_score. Hopefully I can learn from this :)
Main_Screen
public class Main_Screen extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
getSupportActionBar().hide();
//SETS CUSTOM FONT
TextView main_screen_titleone = (TextView)findViewById(R.id.main_screen_titleone);
TextView main_screen_titletwo = (TextView)findViewById(R.id.main_screen_titletwo);
TextView best_score_tv = (TextView)findViewById(R.id.best_score_tv);
TextView best_score_number_tv = (TextView)findViewById(R.id.best_score_number_tv);
Typeface myCustomFont = Typeface.createFromAsset(getAssets(), "fonts/LemonMilk.otf");
main_screen_titleone.setTypeface(myCustomFont);
main_screen_titletwo.setTypeface(myCustomFont);
best_score_tv.setTypeface(myCustomFont);
best_score_number_tv.setTypeface(myCustomFont);
//******************;
int best_score = retrieveInt("BEST_SCORE");
int oldScore = Integer.valueOf(best_score_number_tv.getText().toString());
if (best_score > oldScore){
best_score_number_tv.setText(best_score + "");
}
}
public void startTheGame(View view){
Intent intent = new Intent(this, press_screen.class);
startActivity(intent);
}
public int retrieveInt(String key){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
return sp.getInt(key, 0);
}
Press_Screen
public class press_screen extends ActionBarActivity {
private int time_left;
private int amountOfTapsNumber;
private int bestScore;
TextView amountOfTaps;
TextView timeLeftNumber;
TextView time_left_tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_press_screen);
getSupportActionBar().hide();
amountOfTaps = (TextView)findViewById(R.id.amount_of_taps);
timeLeftNumber = (TextView)findViewById(R.id.time_left_number_tv);
time_left_tv = (TextView)findViewById(R.id.time_left_tv);
Typeface myCustomFont = Typeface.createFromAsset(getAssets(), "fonts/LemonMilk.otf");
amountOfTaps.setTypeface(myCustomFont);
timeLeftNumber.setTypeface(myCustomFont);
time_left_tv.setTypeface(myCustomFont);
timer.start();
}
//Create Timer
CountDownTimer timer = new CountDownTimer(21000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeftNumber = (TextView) findViewById(R.id.time_left_number_tv);
time_left = Integer.valueOf(timeLeftNumber.getText().toString()) - 1;
timeLeftNumber.setText(time_left + "");
}
#Override
public void onFinish() {
if(amountOfTapsNumber > bestScore){
bestScore = amountOfTapsNumber;
saveInfo("BEST_SCORE", bestScore);
}
TextView best_score_number_tv = (TextView)findViewById(R.id.best_score_number_tv);
Intent goBackToMainActivity = new Intent(press_screen.this, Main_Screen.class);
startActivity(goBackToMainActivity);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_press_screen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void triggerTapOnMainButton(View view) {
amountOfTaps = (TextView) findViewById(R.id.amount_of_taps);
amountOfTapsNumber = Integer.valueOf(amountOfTaps.getText().toString()) + 1;
amountOfTaps.setText(amountOfTapsNumber + "");
}
public void saveInfo(String key, int bestScore){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = sp.edit();
edit.putInt("BEST_SCORE", bestScore);
edit.commit();
}
}
When your timer finishes, you send your tapsNumber on the Intent to MainActivity, like this:
Intent goBackToMainActivity = new Intent(press_screen.this, Main_Screen.class);
Bundle bundle = new Bundle();
bundle.putInt("lastScore", amountOfTapsNumber);
goBackToMainActivity.putExtras(bundle);
startActivity(goBackToMainActivity);
Then, in your MainActivity onCreate(), check if your Intent has the oldScore. If it does, compare it to the best_score.
int lastScore = 0;
if(getIntent() !=null && getIntent().getIntExtra("lastScore",0)>0)
lastScore = getIntent().getIntExtra("lastScore",0);
//comparing the lastScore with the bestScore
if (lastScore > best_Score){
best_score_number_tv.setText(lastScore + "");
}
else{
best_score_number_tv.setText(best_Score + "");
}
This way your bestScore will be updated if your lastScore is higher than your old best_score.
I want to make simple converter app.
here is the image of what i want to create. There are actually three layout (Activities)
But actually those two are matters most. There might be unwanted code lines cus am not familiar with android developments. I tryed hard to do this. I think now am getting converted answer to int but still i dont knw how to display it on other view's Textview.
here is the image
https://drive.google.com/file/d/0B3siMB02QAyJLW1Ec3lkbDBWUVE/edit?usp=sharing
here is my code. Appreciate any help!
public class SecondActivity extends ActionBarActivity {
EditText text = null;
int enterValue = 0;
public void convert(View view) {
RadioButton celsiusButton = (RadioButton) findViewById(R.id.farenhite);
RadioButton fahrenheitButton = (RadioButton) findViewById(R.id.celcius);
text = (EditText) findViewById(R.id.editText1);
String temporary = text.getText().toString();
int check = Integer.parseInt(temporary);
if (check == 0) {
Toast.makeText(this, "Not a valid number", Toast.LENGTH_LONG)
.show();
return;
}
float inputValue = check;
if (celsiusButton.isChecked()) {
// celFinal = inputValue;
convertCelsiusToFahrenheit(inputValue);
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
startActivity(intent);
}
if (fahrenheitButton.isChecked()) {
convertFahrenheitToCelsius(inputValue);
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
startActivity(intent);
}
if (celsiusButton.isChecked() && fahrenheitButton.isChecked()) {
Toast.makeText(this, "You have selected both!", Toast.LENGTH_LONG)
.show();
}
/*
* make buttons true and false if (fahrenheitButton.isChecked()) {
* fahrenheitButton.setChecked(false); celsiusButton.setChecked(true); }
* else { fahrenheitButton.setChecked(true);
* celsiusButton.setChecked(false); }
*/
}
// Converts to celsius
private double convertFahrenheitToCelsius(double fahrenheit) {
double temp = ((fahrenheit - 32) * 5 / 9);
Intent myintent = new Intent(SecondActivity.this, ThirdActivity.class);
myintent.putExtra("tempthing", temp);
startActivity(myintent);
return temp;
}
// Converts to fahrenheit
private double convertCelsiusToFahrenheit(double celsius) {
double temp = ((celsius * 9) / 5) + 32;
Intent myintent = new Intent(SecondActivity.this, ThirdActivity.class);
myintent.putExtra("tempthing", temp);
startActivity(myintent);
return temp;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is the code of next view
public class ThirdActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
Intent intent = getIntent();
if((intent.getExtras()!=null) && !intent.getExtras().isEmpty()){
Intent myintent = getIntent();
int intValue = myintent.getIntExtra("tempthing", 0);
final TextView textViewTEST=(TextView) findViewById(R.id.textView1);
textViewTEST.setText(intValue);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.third, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The reason:
In SecondActivity you put a double extra called "tempthing" to intent extras using putExtra(String key, Double value) method. If you will hold mouse over putExtra method you will see that it uses variant with double argument.
double temp = ((fahrenheit - 32) * 5 / 9);
[...]
myintent.putExtra("tempthing", temp); <- puts double
But in your ThirdActivity you're asking for an int extra using getIntExtra method.
int intValue = myintent.getIntExtra("tempthing", 0);
There is no int extra called "tempthing" inside - there is however a double extra with that key.
Solution:
So either you will put the int value in SecondActivity:
myintent.putExtra("tempthing", (int)temp);
or get a double value in ThirdActivity:
double doubleValue = myintent.getDoubleExtra("tempthing", 0);
They just need to match. If you put double - read double. If you put int - read int :)
Example :
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
intent.putExtra("INTEGER",value);
startActivity(intent);
You can use below code
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
intent.putExtra("your_key",value); // your_key => tempthing
startActivity(intent);
and set value int ThirdActivity
final TextView textViewTEST=(TextView) findViewById(R.id.textView1);
textViewTEST.setText(String.valueOf(intValue));
I have the ArrayList...
ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
and I want it so that when the user closes the app or leaves the app, all the ColorSaver objects in the ArrayList will be there when the user reopens the app. I would prefer to use the SharedPreferences but I can't do that because the list is a custom object...
I have looked around and found out that I can do a serializable but I tried that and failed horribly, so if somebody could guide me through the serializable deal that would be great. Oh and where do I put the code, like in onCreate() in my mainActivity or in the activity that is displaying the ArrayList
My mainActivity class
public class MainActivity extends Activity {
ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
private static final String TAG = "Main Activity";
public static final String PREFS_NAME = "MyPrefsFile";
final Intent intent = new Intent();
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
final NumberPicker rednp = (NumberPicker) findViewById(R.id.redNumberPicker1);
final NumberPicker bluenp = (NumberPicker) findViewById(R.id.blueNumberPicker);
final NumberPicker greennp = (NumberPicker) findViewById(R.id.greenNumberPicker);
switch(item.getItemId())
{
case R.id.save:
Log.i(TAG, "Save item clicked!");
Intent intent = new Intent(this, SaveActivity.class);
intent.putExtra("RedValue", rednp.getValue());
intent.putExtra("BlueValue", bluenp.getValue());
intent.putExtra("GreenValue", greennp.getValue());
intent.putExtra("temparray", tempList);
startActivity(intent);
return true;
case R.id.recall:
Log.i(TAG, "Recall item clicked!");
Intent intent2 = new Intent(this, RecallActivity.class);
intent2.putExtra("temparray", tempList);
startActivity(intent2);
return true;
default:
return super.onOptionsItemSelected(item);
}//End Switch
}
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
Bundle extras = getIntent().getExtras();
final SurfaceView sView = (SurfaceView) findViewById(R.id.surfaceView1);
final NumberPicker np = (NumberPicker) findViewById(R.id.redNumberPicker1);
np.setMaxValue(255);
np.setMinValue(0);
final NumberPicker np2 = (NumberPicker) findViewById(R.id.greenNumberPicker);
np2.setMaxValue(255);
np2.setMinValue(0);
final NumberPicker np3 = (NumberPicker) findViewById(R.id.blueNumberPicker);
np3.setMaxValue(255);
np3.setMinValue(0);
if( extras != null )
{
np.setValue(extras.getInt("savedRValue"));
//np.setValue(intent.getIntExtra("savedRValue", 255));
np2.setValue(extras.getInt("savedGValue"));
//np2.setValue(intent.getIntExtra("savedGValue", 255));
np3.setValue(extras.getInt("savedBValue"));
//np3.setValue(intent.getIntExtra("savedBValue", 255));
tempList = (ArrayList<ColorSaver>) extras.getSerializable("array");
sView.setBackgroundColor(Color.argb(255, np.getValue(), np2.getValue(), np3.getValue()));
}
else
{
Log.i(TAG, "I just don't get it...WTF");
}
np.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
//GREEN NUMBERPICKER LISTENER
np2.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
np3.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
}//End onCreate()
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}//END onCreateOptionsMenu()
}//END CLASS
My saveActivity, where the user saves their color combo to the ArrayList...
public class SaveActivity extends Activity implements Serializable {
private static final String TAG = "Save Activity";
public ArrayList<ColorSaver> savedColors = new ArrayList<ColorSaver>();
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save);
// Show the Up button in the action bar.
setupActionBar();
Bundle extras = getIntent().getExtras();
final Intent intent1 = new Intent(this, MainActivity.class);
Button saveButton = (Button) findViewById(R.id.saveButton1);
final EditText nameField = (EditText) findViewById(R.id.colorNameField);
//final Intent intent = new Intent();
savedColors = (ArrayList<ColorSaver>) extras.getSerializable("temparray");
//Making sure the savedColors arrayList has something in it.
if( savedColors.isEmpty() )
{
ColorSaver temp = new ColorSaver("Rockies Purple", 180, 80, 255);
savedColors.add(temp);
}
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Bundle extras = getIntent().getExtras();
int redcolor, greencolor, bluecolor;
redcolor = extras.getInt("RedValue");
greencolor = extras.getInt("GreenValue");
bluecolor = extras.getInt("BlueValue");
String colorName = nameField.getText().toString();
//Build the new color and add it to the arrayList
ColorSaver saver = new ColorSaver(colorName, redcolor, greencolor, bluecolor);
savedColors.add(saver);
intent1.putExtra("array", savedColors);
Log.i(TAG, savedColors.get(savedColors.size()-1).getColorName());
startActivity(intent1);
}
});
}//END OnCreate()
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.save, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}//END CLASS
My recallActivity where the user recalls their color combos...
public class RecallActivity extends SaveActivity {
private static final String TAG = "Recall Activity";
ArrayList<ColorSaver> colorsArray = new ArrayList<ColorSaver>();
SaveActivity sActivity = new SaveActivity();
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recall);
// Show the Up button in the action bar.
setupActionBar();
final Intent intent1 = new Intent(this, MainActivity.class);
final Spinner colorList = (Spinner) findViewById(R.id.colorsSpinner);
Button grabButton = (Button) findViewById(R.id.grabButton);
Bundle extras = getIntent().getExtras();
colorsArray = (ArrayList<ColorSaver>) extras.getSerializable("temparray");
//Load the spinner with the saved colors
addColorNames(colorsArray);
grabButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
ColorSaver selectedItem = (ColorSaver) colorList.getSelectedItem();
int redValue, greenValue, blueValue;
String name;
redValue = selectedItem.getRedValue();
greenValue = selectedItem.getGreenValue();
blueValue = selectedItem.getBlueValue();
name = selectedItem.getColorName();
intent1.putExtra("savedRValue", redValue);
intent1.putExtra("savedGValue", greenValue);
intent1.putExtra("savedBValue", blueValue);
intent1.putExtra("savedName", name);
intent1.putExtra("array", colorsArray);
startActivity(intent1);
}//END onClick
});
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.recall, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}// END onOptionsItemSelected(MenuItem item)
public void addColorNames(ArrayList<ColorSaver> colorsArray1)
{
colorsArray = colorsArray1;
//if( !colorsArray.isEmpty() )
//{
Spinner colorsSpinner = (Spinner) findViewById(R.id.colorsSpinner);
ArrayAdapter<ColorSaver> dataAdapter
= new ArrayAdapter<ColorSaver>
(RecallActivity.this, android.R.layout.simple_spinner_item, colorsArray);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
colorsSpinner.setAdapter(dataAdapter);
Log.i(TAG, savedColors.get(savedColors.size() - 1).toString());
//}
//else
//{
// Log.i(TAG, "colorsSpinner came out to be null....WTF???");
//}
}//End addColorNames()
}//END CLASS
I am greatful of any help!
Take a look at Android's Parcelable implementation.
So, I'm just guessing on your ColorSaver class since it wasn't posted, but you would implement it the following way:
ColorSaver.java
public class ColorSaver implements Parcelable {
private String mName;
private int mRed;
private int mGreen;
private int mBlue;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(mName);
out.writeInt(mRed);
out.writeInt(mGreen);
out.writeInt(mBlue);
}
public static final Parcelable.Creator<ColorSaver> CREATOR
= new Parcelable.Creator<ColorSaver>() {
public ColorSaver createFromParcel(Parcel in) {
return new ColorSaver(in);
}
public ColorSaver[] newArray(int size) {
return new ColorSaver[size];
}
};
private ColorSaver(Parcel in) {
mName = in.readString();
mRed = in.readInt();
mGreen = in.readInt();
mBlue = in.readInt();
}
}
MyActivity.java
public class MyActivity extends Activity {
private static final String COLOR_SAVER_LIST = "com.example.android.ColorSaverList";
private List<ColorSaver> colorSaverList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null && savedInstanceState.containsKey(COLOR_SAVER_LIST)) {
colorSaverList = new ArrayList<ColorSaver>();
colorSaverList = savedInstanceState.getParcelableArrayList(COLOR_SAVER_LIST);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(COLOR_SAVER_LIST, colorSaverList);
}
}