Advice with DatePicker code structure Android Studio - android

So I'm very new to android programming, and have no real experience with software building however I do have a basic background with PHP so I get some of the theory behind it all.
I'm currently making a basic Form activity that will store the entries into a DB, which can be recalled in another activity where it can be viewed and edited etc etc.
I have found lots of helpful advice to get to where I am but currently having trouble with how I need to structure the code to implement the DatePicker dialog, the problem I'm facing is the example code for the date picker has
public class MainActivity extends Activity implements OnClickListener {
Where as the code in my project is public class New extends ActionBarActivity {
So when I edit the line to "implements OnClickListener" my spinner drop downs don't like it.
I have tried entering the code in without the "implements OnClickListener"
Please take a look at what I have and point me in the right direction, I need to understand where its going wrong and how it should be structured.
public class New extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
//Product List
Spinner productList = (Spinner) findViewById(R.id.product);
String[] products = new String[] { "1", "2", "3" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, products);
productList.setAdapter(adapter);
productList.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Log.v("products", (String) parent.getItemAtPosition(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
//Reason List
Spinner reasonList = (Spinner) findViewById(R.id.reason);
String[] reasons = new String[] { "A", "B", "C" };
ArrayAdapter<String> adapters = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, reasons);
reasonList.setAdapter(adapters);
reasonList.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Log.v("reasons", (String) parent.getItemAtPosition(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
//Start Date Picker
private EditText StartDate;
private DatePickerDialog StartdatePickerDialog;
private SimpleDateFormat dateFormatter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
findViewsById();
setDateTimeField();
}
private void findViewsById() {
StartDate = (EditText) findViewById(R.id.startdate);
StartDate.setInputType(InputType.TYPE_NULL);
StartDate.requestFocus();
}
private void setDateTimeField() {
StartDate.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
StartdatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
StartDate.setText(dateFormatter.format(newDate.getTime()));
}
}, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
#Override
public void onClick(View view) {
if(view == StartDate) {
StartDatePickerDialog.show();
}
}
#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_new, 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);
}
}

Unless I'm mistaken, try removing the implements OnClickListener from your activity and replacing
StartDate.setOnClickListener(this);
with
StartDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(view == StartDate) {
StartDatePickerDialog.show();
}
}
});
and removing the onclick method in Start Date Picker. Basically, what implements OnClickListener does is that it can be attached to components (the EditText, in this case) which, when clicked, will be redirected to your implementation of onClick. You're replacing your Activity listener (which can be used by any component in that activity via setOnClickListener(this)) with a specific listener designed for the StartDate alone. Note how your spinners all have onItemSelectedListeners, which work on the same basic principle.
Words are hard, let me know if that doesn't make sense.

Related

Why list view not showing the array of data in android app?

I am trying to fill data from SQLite database to list view but my list view does not show anything.When i bedug the project list_collections varible fill of data
Here is my sample code.
public class Collection_List_Activity extends ActionBarActivity {
private DB_Nabege_helper nabege_db = new DB_Nabege_helper(this);
private ListView list_collections;
private Button btn_Go_to_add_collection;
private int[] id_tbl_collection;
private String[] name_collection_tbl_collection;
private EditText word_search_collection;
private Cursor cur_collection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection__list_);
// =================================================================
list_collections = (ListView) findViewById(R.id.listView_collections);
TextView textViwempty = (TextView) findViewById(R.id.textview_no_subject);
list_collections.setEmptyView(textViwempty);
// =================================================================
go_to_add_collection();
fill_listView("");
word_search_collection = (EditText) findViewById(R.id.txt_search_collection);
list_collections.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent goTo_SubjectsActivity = new Intent(Collection_List_Activity.this, Subjects_Activity.class);
goTo_SubjectsActivity.putExtra("id_collection", id_tbl_collection[arg2]);
startActivity(goTo_SubjectsActivity);
}
});
word_search_collection.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 2) {
fill_listView(word_search_collection.toString());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private void go_to_add_collection() {
btn_Go_to_add_collection = (Button) findViewById(R.id.btn_new_collection);
btn_Go_to_add_collection.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent goToHelpActivity = new Intent(Collection_List_Activity.this, AddCollectionActivity.class);
startActivity(goToHelpActivity);
}
});
}
private void fill_listView(String word) {
int count_tbl_collection = nabege_db.count_collection(word);
id_tbl_collection = new int[count_tbl_collection];
name_collection_tbl_collection = new String[count_tbl_collection];
nabege_db.open();
cur_collection = nabege_db.display_collection(word);
try {
if (cur_collection != null)
for (int i = 0; i < count_tbl_collection; i++) {
cur_collection.moveToPosition(i);
id_tbl_collection[i] = cur_collection.getInt(0);
name_collection_tbl_collection[i] = cur_collection.getString(1);
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
Log.d("mylog", e.toString());
}
list_collections.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, name_collection_tbl_collection));
nabege_db.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.collection__list_, 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);
}
#Override
protected void onResume() {
super.onResume();
fill_listView(word_search_collection.toString());
}
// end class
}
Once again I am trying to fill data By new array .I change this line
list_collections.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, name_collection_tbl_collection));
like this:
list_collections.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,new String[]{"5","4","3","2","1"}));
List view show all data. I don't understand problem because no error in logcat.Please give me hint or suggestion.
Change
fill_listView(word_search_collection.toString());
to
fill_listView(word_search_collection.getText().toString());
This will assign correct String to word variable and your program will work
Thanks

Android Spinner is not clickable or working while running app

I am relatively new to programming and recently started working with android. I have been breaking my brains all day over this problem I have with a spinner. I read several similar questions and found several solutions and examples but none of them work for me :(
package com.deitel.welcome;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.view.View;
import android.widget.AdapterView.OnItemSelectedListener;
public class Preferences extends Activity {
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preferences);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.preferences, 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_profile) {
Intent intent = new Intent(Preferences.this, Profile.class);
startActivity(intent);
}
else if (id == R.id.action_home) {
Intent intent = new Intent(Preferences.this, HomeScreen.class);
startActivity(intent);
}
else if (id == R.id.action_calendar) {
Intent intent = new Intent(Preferences.this, CalendarActivity.class);
startActivity(intent);
}
else if (id == R.id.action_statistics) {
Intent intent = new Intent(Preferences.this, Statistics.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
public class MainActivity extends Activity {
private String[] states;
private Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
states = getResources().getStringArray(R.array.countries_list);
spinner = (Spinner) findViewById(R.id.country_spinner);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, states);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
}
And this is my customOnItemSelected java file:
package com.deitel.welcome;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
Toast.makeText(parent.getContext(),
"On Item Select : \n" + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
This is my resources file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="spinner_prompt">Choose a country</string>
<string-array name="country_arrays">
<item>Malaysia</item>
<item>United States</item>
<item>Indonesia</item>
<item>France</item>
<item>Italy</item>
<item>Singapore</item>
<item>New Zealand</item>
<item>India</item>
</string-array>
</resources>
And this is of course my XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dip" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="#string/country_label"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Spinner
android:id="#+id/country_spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#string/country_label" />
</LinearLayout>
Can anyone figure out what I did wrong?
Greetings! Rosa
This fragment of your code:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Adds listener without any logic because you didn;t provide any inside overriden methods. What you should do is add your custom listener like that:
spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener())
you have done nothing in your on item selected . try adding a toast message in your main activity's on item selected and why is there a need for creating a custom listener when you can use the default one?
try like this in your main activity:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(parent.getContext(),"spinner clicked",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
just try adding a toast in your default listener or else set the custom listener you have made.You are not setting it as your listener and hence nothing is happening.
Simple Spinner Example and Onclick listner
String[] tracks_time = { "3min", "5min", "10min" };
Spinner spinner_time = (Spinner)promptsView.findViewById(R.id.sp_time);
ArrayAdapter<String> sptime = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, tracks_time);
spinner_time.setAdapter(sptime);
spinner_time.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int position ,long arg3)
{
int index = parent.getSelectedItemPosition();
// get stuff as per index
}
public void onNothingSelected(AdapterView<?> arg0)
{
}
});
Thanks everyone! You are right... I found out that I actually created another class within my activity and did nothing in the original activity. Thanks for your help!
I kind of copied everything into the first class and added some stuff. Here is the code that worked for me in the end:
public class Preferences extends Activity {
protected CharSequence[] _options = { "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday" };
protected boolean[] _selections = new boolean[_options.length];
protected Button _optionsButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preferences);
_optionsButton = (Button) findViewById(R.id.button1);
_optionsButton.setOnClickListener(new ButtonClickHandler());
}
public class ButtonClickHandler implements View.OnClickListener {
public void onClick(View view) {
showDialog(0);
}
}
#Override
protected Dialog onCreateDialog (int id) {
return new AlertDialog.Builder(this)
.setTitle("Preferred Exercise Days")
.setMultiChoiceItems(_options, _selections,
new DialogSelectionClickHandler())
.setPositiveButton("OK", new DialogButtonClickHandler())
.create();
}
}
public class DialogSelectionClickHandler implements
DialogInterface.OnMultiChoiceClickListener {
public void onClick(DialogInterface dialog, int clicked,
boolean selected) {
Log.i("ME", _options[clicked] + " selected: " + selected);
}
}
public class DialogButtonClickHandler implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int clicked) {
switch (clicked) {
case DialogInterface.BUTTON_POSITIVE:
String selected = "";
int i = 0;
for (boolean b : _selections) {
if (b) {
selected += _options[i] + " ;";
}
i++;
}
printSelectedDays();
Toast.makeText(Preferences.this, "Selected: " + selected,
Toast.LENGTH_SHORT).show();
break;
}
}
}
protected void printSelectedDays() {
for (int i = 0; i < _options.length; i++) {
Log.i("ME", _options[i] + " selected: " + _selections[i]);
}
}
The solution is kind of different but it is actually what I wanted to achieve in the first place so I hope someone can use this after all.

switch case with two spinners and audio player

In my activity i have two spinners, one image view and two buttons.
depending on first spinner the second spinners should change. and while selecting birds in first spinner the second spinner should show parrot peacock etc. while selecting parrot in second spinner i should get the image of parrot.
till this i am getting.
but now what i want is while i press a button then i should get the voice of parrot.
in this code when i am pressing the button i am getting the same voice for every picture change in second spinner
public class MainActivity extends Activity {
ImageView displayIV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
;
Button b1;
b1=(Button)findViewById(R.id.button1);
Spinner friend = (Spinner) findViewById(R.id.spinner1);
final Spinner subFriend = (Spinner) findViewById(R.id.spinner2);
displayIV=(ImageView)findViewById(R.id.imageView1);
final ArrayList<String> friend_options = new ArrayList<String>();
final ArrayList<String> subfriend_options = new ArrayList<String>();
friend_options.add("Nuz");
friend_options.add("Dur");
friend_options.add("Tara");
friend_options.add("Sama");
ArrayAdapter<String> friendAdapter = new ArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_spinner_item,
friend_options);
friend.setAdapter(friendAdapter);
ArrayAdapter<String> subFriendAdapter = new ArrayAdapter<String>(
getApplicationContext(),
android.R.layout.simple_spinner_item,subfriend_options);
subFriend.setAdapter(subFriendAdapter);
friend.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view,
int position, long id) {
String friendName =
friend_options.get(position).toString();
resetFriend(friendName);
// subFriend.setAdapter(null);
}
private void resetFriend(String friendName) {
subfriend_options.removeAll(subfriend_options);
if (friendName.equals("Nuz")) {
subfriend_options.add("Nuz_1");
subfriend_options.add("Nuz_2");
subfriend_options.add("Nuz_3");
subfriend_options.add("Nuz_4");
} else if (friendName.equals("Dur")) {
subfriend_options.add("Dur_1");
subfriend_options.add("Dur_2");
subfriend_options.add("Dur_3");
subfriend_options.add("Dur_4");
} else if (friendName.equals("Tara")) {
subfriend_options.add("Tara_1");
subfriend_options.add("Tara_2");
subfriend_options.add("Tara_3");
subfriend_options.add("Tara_4");
} else {
subfriend_options.add("Sama_1");
subfriend_options.add("Sama_2");
subfriend_options.add("Sama_3");
subfriend_options.add("Sama_4");
}
ArrayAdapter<String> subFriendAdapter = new
ArrayAdapter<String>( getApplicationContext(),
android.R.layout.simple_spinner_item,
subfriend_options);
subFriend.setAdapter(subFriendAdapter);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
subFriend.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
arg0.getItemAtPosition(arg2);
final ImageView im =
(ImageView)findViewById(R.id.imageView1);
String s=((TextView)arg1).getText().toString();
if(s.equals("Tara_1")){
im.setImageDrawable(getResources().getDrawable(R.drawable.crow));
}
if(s.equals("Tara_2"))
im.setImageDrawable(getResources().getDrawable(R.drawable.india1));
if(s.equals("Tara_3"))
im.setImageDrawable(getResources().getDrawable(R.drawable.peacock));
if(s.equals("Tara_4"))
im.setImageDrawable(getResources().getDrawable(R.drawable.robin1));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//MediaPlayer mMediaPlayer = MediaPlayer.create(this,
R.raw.Kalimba);
MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.abc);
mp.start();
}
});
}
#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;
}
}
In the setOnClickListener method of your button, b1, you need to know which image has been selected on the spinner (your description is a little bit confusing so i don't have clear exactly which spinner is going to change the sound that you app has to reproduce).
Anyway, let think that the spinner is "friend_options".
In you setOnClickListener we have to know which item has been selected for the user when click on the button, right? And depending of which item was selected, we will play one specific sound.
So....
Another important poin is that you should create the variable of the mediaplayer outside of the onclickListener, like a class variable:
//Class variable:
public MediaPlayer mp;
In the onCreate method you should initialize the MediaPlayer component:
public void onCreate()
{
MediaPlayer.create(MainActivity.this, R.raw.abc); //Default sound, it is not
//importat because we are going
//to chain the value of the
//file to reproduce in the next
//step.
}
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Here we are going to take the item selected:
String itemSelected = spinner.getSelectedItem().toString();
int soundToPlayId=0;
if(itemSelected.equals("Nuz"))
{
soundToPlayId = R.raw.Kalimba ;
}
else if(itemSelected.equals("Dur"))
{
soundToPlayId = R.raw.abc;
}
// etc etc etc --> you should put all the sound associated to all the
// friends
//And now you only have to reproduce if the item was selected properly:
if(soundToPlayId !=0) //if the id is different to 0:
{
mp = MediaPlayer.setDataSource(MainActivity.this, soundToPlayId);
mp.start();
}
}
});
Let see if it is working!!! Ask me if you have any doubt...and if the answer is correct, vote me and check as correct!!! (I need points, thanks!)

Passing data between fragments and the next activity

Firstly, this is my first question here, Thanks for any reply:)
I have a fragment extends SherlockListFragment that has a list of (events) saved in database, i want when i click on any item in the list , to get all event data and fill in another activity that has editText(s) ....
this is the frgment.java code
public class EventsFragment extends SherlockListFragment {
EditText _eventName_;
EditText next_activty_text;
List<String> presidents = new ArrayList<String>();
public DBAdapter db;
String buf = "";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_events, container, false);
_eventName_ = (EditText) v.findViewById(R.id.editText11);
next_activty_text = (EditText) v.findViewById(R.id.editText12);
// The most Important part in action bar menus :)
setHasOptionsMenu(true);
/*
//This is how to link a button in fragment by its .xml file :Ds
Button create_btn = (Button) v.findViewById(R.id.button1);
create_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//startActivity(new Intent("com.nazmy.CreateEventActivity"));
}
});*/
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
db = new DBAdapter(getActivity());
db.open();
int i = 1;
while(db.getEvent(i).isLast()){
Cursor c = db.getEvent(i);
presidents.add(c.getString(1));
i++;
}
db.close();
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, presidents));
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, presidents));
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_events_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.add:
startActivity(new Intent("com.nazmy.CreateEventActivity"));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
//startActivity(new Intent("com.nazmy.CreateEventActivity"));
db = new DBAdapter(getActivity());
db.open();
Cursor c = db.getEvent(id+1);
//populate(c.getString(1));
_eventName_.setText(c.getString(1));
db.close();
}
}
`
and this is the activity code
public class CreateEventActivity extends FragmentActivity {
EditText mEdit;
EditText mEdit2;
EditText mEditFromTime;
EditText mEditToTime;
int whichDateBtn;
int whichTimeBtn;
DBAdapter db = new DBAdapter(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_event);
db.open();
Cursor c = db.getAllEvents();
if (c.moveToFirst())
{
do {
DisplayEvent(c);
} while (c.moveToNext());
}
db.close();
Button cancel_btn = (Button) findViewById(R.id.button4);
Button save_btn = (Button) findViewById(R.id.button1); //if clicked -> save in data-base
save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.open();
EditText event_name = (EditText)findViewById(R.id.editText12);
EditText event_place = (EditText)findViewById(R.id.editText13);
EditText from_date = (EditText)findViewById(R.id.editText14);
EditText from_time = (EditText)findViewById(R.id.editText15);
EditText to_date = (EditText)findViewById(R.id.EditText16);
EditText to_time = (EditText)findViewById(R.id.EditText17);
CheckBox share = (CheckBox)findViewById(R.id.checkBox1);
CheckBox alarm = (CheckBox)findViewById(R.id.checkBox2);
long id2 = db.insertEvent(event_name.getText().toString(), event_place.getText().toString(),
from_date.getText().toString(), to_date.getText().toString(),
from_time.getText().toString(),
to_time.getText().toString(),
share.isChecked(),alarm.isChecked());
db.close();
event_name.setText("");
event_place.setText("");
from_date.setText("");
to_date.setText("");
from_time.setText("");
to_time.setText("");
if (share.isChecked()) {
share.setChecked(false);
}
if (alarm.isChecked()) {
alarm.setChecked(false);
}
startActivity(new Intent("com.nazmy.HomeActivity"));
}
});
cancel_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.nazmy.HomeActivity"));
}
});
}
//This method shows the dialog when Button is clicked
public void selectFromtDate(View view) {
DialogFragment mDialog = new SelectDateFragment();
mDialog.show(getFragmentManager(), "DatePicker");
whichDateBtn = 0;
}
public void selectToDate(View view) {
DialogFragment mDialog2 = new SelectDateFragment();
mDialog2.show(getFragmentManager(), "DatePicker");
whichDateBtn = 1;
}
//This method will update the EditText field with the following code.
public void populateSetDate(int year, int month, int day) {
mEdit = (EditText)findViewById(R.id.editText14); //brbt el editText (mEdit) be el text ely hayzhar fel text Field
mEdit2 = (EditText)findViewById(R.id.EditText16);
if(whichDateBtn==0) {
mEdit.setText(month+"/"+day+"/"+year);
}
else if (whichDateBtn == 1) {
mEdit2.setText(month+"/"+day+"/"+year);
}
}
//This subclass includes method to display the datepicker fragment to the user.
//It also has the method to handle the event on setting the date.
public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
//The onCreateDialog() method creates a calendar object.
//Using this object the current day, month and year that will be retrieved.
//This current instance will return to the activity to display the date picker with the current date by default.
//onDateSet() method calls the populateSetDate() with the selected date parameters.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
public void onDateSet(DatePicker view, int yy, int mm, int dd) {
populateSetDate(yy, mm+1, dd);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
// Time Pickers
////////////////////////////////////////////////////////////////////////////////////////////////////////
public void selectFromTime(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "TimePicker");
whichTimeBtn = 0;
}
public void selectToTime(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "TimePicker");
whichTimeBtn = 1;
}
public void populateSetTime(int hour, int min) {
mEditFromTime = (EditText)findViewById(R.id.editText15); //brbt el editText (mEdit) be el text ely hayzhar fel text Field
mEditToTime = (EditText)findViewById(R.id.EditText17);
if(whichTimeBtn==0) {
mEditFromTime.setText(hour+":"+min);
}
else if (whichTimeBtn == 1) {
mEditToTime.setText(hour+":"+min);
}
}
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
populateSetTime(hourOfDay, minute);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_create_event, menu);
return true;
}
public void DisplayEvent(Cursor c)
{
Toast.makeText(this,
"id : " + c.getString(0) + "\n" +
"Event Name: " + c.getString(1) + "\n" +
"Place : " + c.getString(2) + "\n" +
"From Date : " + c.getString(3)+ "\n" +
"From Time : " + c.getString(5)+ "\n" +
"To Date : " + c.getString(4)+ "\n" +
"To Time : " + c.getString(6),
Toast.LENGTH_LONG).show();
}
}
`
Thanks in advance :)
You have two choices. Either fetch the data from your database in EventsFragment.onListItemClick(), and pass that data to your second Activity as Intent extras. Or you can pass the id of the clicked item, and do the database operations in your second Activity. Either way you have to pass data using Intents
public class EventsFragment extends SherlockListFragment {
.
.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(this, CreateEventActivity.class);
// OPTION 1: Fetch data here, and pass it with the intent
db = new DBAdapter(getActivity());
db.open();
Cursor c = db.getEvent(id+1);
intent.putExtra("id", c.getString(1));
intent.putExtra("event_name", c.getString(2));
// Do this for all your values.
db.close();
startActivity(intent);
// OPTION 2: Pass the id of the selected item, and fetch the data in second activity
intent.putExtra("selected_id", id+1);
startActivity(intent);
}
}
In CreateEventActivity you then have to get the extras you chose to pass with the Intent.
#Override
protected void onCreate(Bundle savedInstanceState) {
.
.
Intent intent = getIntent();
// If you chose option 1, you have to get all the extras you attached to the Intent.
long id = intent.getLongExtra("id", -1)
String eventName = intent.getStringExtra("event_name", "defValue");
// Fetch all the values here..
// If you chose option 2, you fetch the id and do the database operations to retrive
// the data
long id = intent.getLongExtra("selected_id", -1);
// DB stuff here..
}

How to store dropdown item of the spinner to the sqlite database of android

I want to store the dropdown value of the spinner to the database. I am able to get dopdown as per the tutorial in the android developer site but i am not able to store that dropdown value to the database when user click on save button.I don't know it is possible or not if yes please tell me how to do that with some example.
Thanks in advance
This is my code
public class Akshay extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Spinner For Selecting Room
Spinner spinner_room = (Spinner) findViewById(R.id.spinner_for_Room_type_screen_2);
ArrayAdapter adapter_room = ArrayAdapter.createFromResource(this,
R.array.room_array, android.R.layout.simple_spinner_item);
adapter_room.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_room.setAdapter(adapter_room);
spinner_room.setOnItemSelectedListener(new MyOnItemSelectedListener_room());
}
}
// Listener Implementation of Spinner For Selecting Room
public class MyOnItemSelectedListener_room implements OnItemSelectedListener
{
public void onItemSelected(AdapterView parent, View view, int pos, long id)
{
}
public void onNothingSelected(AdapterView parent)
{ // Do nothing.}
};
}
public class Akshay extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.configuration);
// Spinner For Selecting Room
Spinner spinner_room = (Spinner) findViewById(R.id.spinner_for_Room_type_screen_2);
ArrayAdapter<CharSequence> adapter_room = ArrayAdapter.createFromResource(this,
R.array.room_array,android.R.layout.simple_spinner_item);
adapter_room.setDropDownViewResourc(android.R.layout.simple_spinner_dropdown_item);
spinner_room.setAdapter(adapter_room);
spinner_room.setOnItemSelectedListener(new Listener_Of_Selecting_Room_Spinner());
}
// Listener Implementation of Spinner For Selecting Room
public static class Listener_Of_Selecting_Room_Spinner implements OnItemSelectedListener
{
static String RoomType;
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id)
{
// By using this you can get the position of item which you
// have selected from the dropdown
RoomType = (parent.getItemAtPosition(pos)).toString();
}
public void onNothingSelected(AdapterView<?> parent)
{
// Do nothing.
}
};
// Listener Implementation For Saving Number Of Board
private OnClickListener btnListener_Btn_Save_Room_Board = new OnClickListener()
{
public void onClick(View view)
{
DBAdapter dbAdapter1 = new DBAdapter(view.getContext());
String room;
try {
dbAdapter1.createDataBase();
dbAdapter1.openDataBase();
// Here i am using the object RoomType which i have got from
// the Listener of spinner
room = Listener_Of_Selecting_Room_Spinner.RoomType;
ContentValues initialValues1 = new ContentValues();
initialValues1.put("RoomType", room);
//Here i am storing it(RoomType) to the database
dbAdapter1.InsertNumberOfBoardInDB("Configuration", null,initialValues1);
}
catch (Exception e) {
}
finally {
dbAdapter1.close();
}
}
};
}
If you're looking for information on how to use SQLite databases in an Android app, I highly recommend going through the Notepad tutorial.
Or are you stuck at handling the button click?
This doesn't directly answer the question, but design-wise and for simplicity's sake it may make some sense to store UI values as preference.
For example:
public static final String PREFS_NAME = "MyPrefsFile";
public static final String SPINNER_VALUE = "SPINNER VALUE";
SharedPreferences settings = getSharedPreferences(PREFS_NAME , 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(SPINNER_VALUE, <the spinner value>);
editor.commit();
Of course this depends on your requirement, ymmv.

Categories

Resources