I am working on an app and I need to pass the contents of some textviews to a new activity, but I want to save the content I pass while the app is open so that the user can select more items from other activities and send them to the final checkout activity.
right now I have spinners which save the selection to a Textview
public class Americano extends AppCompatActivity {
// MyDBHandler dbHandler;
String result;
TextView tvSize;
Spinner spinner;
int mPos;
String mSelection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_americano);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Spinner spinnerSize = (Spinner) findViewById(R.id.spinner_size);
AdapterView.OnItemSelectedListener listener = new myOnItemSelectedListener();
spinnerSize.setOnItemSelectedListener(listener);
Spinner spinnerSyrups = (Spinner) findViewById(R.id.spinner_syrups);
AdapterView.OnItemSelectedListener listenerSyrups = new myOnItemSelectedListener2();
spinnerSyrups.setOnItemSelectedListener(listenerSyrups);
Spinner spinnerTopping = (Spinner) findViewById(R.id.spinner_toppings);
AdapterView.OnItemSelectedListener listenerTopping = new myOnItemSelectedListener3();
spinnerTopping.setOnItemSelectedListener(listenerTopping);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DBAdapter dbAdapter = new DBAdapter(view.getContext());
}
});
}
public class myOnItemSelectedListener implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
Americano.this.mPos = pos;
Americano.this.mSelection = parent.getItemAtPosition(pos).toString();
TextView resultText = (TextView) findViewById(R.id.tvSize);
resultText.setText(Americano.this.mSelection);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
public class myOnItemSelectedListener2 implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
Americano.this.mPos = pos;
Americano.this.mSelection = parent.getItemAtPosition(pos).toString();
TextView resultText = (TextView) findViewById(R.id.tvSyrup);
resultText.setText(Americano.this.mSelection);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
public class myOnItemSelectedListener3 implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
Americano.this.mPos = pos;
Americano.this.mSelection = parent.getItemAtPosition(pos).toString();
TextView resultText = (TextView) findViewById(R.id.tvTopping);
resultText.setText(Americano.this.mSelection);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
I have more menu item classes exactly like this one
I want to pass the textview data to the checkout page. But save that data in that page until the user closes the app.
thanks
You can do it sending the information through an Intent.
In your listener you would go to another actvity like this:
Intent intent = new Intent(getActivity(), NewActivity.class);
intent.putExtra("RESULT_TEXT", resultText);
startActivity(intent);
And on the NewActivity you can get the information like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
Bundle bundle = getIntent().getExtras();
String resultText = bundle.getString("RESULT_TEXT", "");
}
Hope it helps.
Related
I have MainActivity and SpinnerActivity, I want to get selected spinner item value from SpinnerActivity into the MainActivity. I tried to declare String as Static, I also tried with getter but without any success.
in Spinner Activity I also have if statement, how can I get value outside "if statement" and "#Override method" into another class?
MainActivity.class
public class MainActivity extends AppCompatActivity {
SpinnerActivity spinnerActivity = new SpinnerActivity();
Spinner spinnerProvince;
String selectedSpinnerProvince = spinnerActivity.inSpinnerSelectedProvince;
// String selectedSpinnerProvince = SpinnerActivity.inSpinnerSelectedProvince;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinnerProvince = findViewById(R.id.spinnerProvince);
populateSpinnerProvinces();
spinnerProvince.setOnItemSelectedListener(spinnerActivity);
}
public void populateSpinnerProvinces() {
ArrayAdapter<String> provincesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.province));
provincesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerProvince.setAdapter(provincesAdapter);
}
}
SpinnerActivity.class
public class SpinnerActivity implements android.widget.AdapterView.OnItemSelectedListener {
public String inSpinnerSelectedProvince;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.spinnerProvince) {
inSpinnerSelectedProvince = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
} else {// code here}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
I were about to advice you to use Intent to share data between both activities when i noticed that your "SpinnerActivity" is not really an Activity since it not extends Android Activity class (AppCompactActivity or other classes like this).
Your SpinnerActivity is a Listener. You can use it to implement the action to trigger when an action is performed on your Spinner view. For that you need to do it inside the "#Override" method of onItemSelected.
If you don't like to use the previous methode because of the Override methode you should implement directly the action to trigger at on click events on your spinner view in your MainActivity by doing this:
public class MainActivity extends AppCompatActivity {
SpinnerActivity spinnerActivity = new SpinnerActivity();
Spinner spinnerProvince;
String selectedSpinnerProvince = spinnerActivity.inSpinnerSelectedProvince;
// String selectedSpinnerProvince =
SpinnerActivity.inSpinnerSelectedProvince;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinnerProvince = findViewById(R.id.spinnerProvince);
populateSpinnerProvinces();
//spinnerProvince.setOnItemSelectedListener(spinnerActivity);
spinnerProvince.setOnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.spinnerProvince) {
inSpinnerSelectedProvince = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
} else {// code here}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void populateSpinnerProvinces() {
ArrayAdapter<String> provincesAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_item,
getResources().getStringArray(R.array.province));
provincesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerProvince.setAdapter(provincesAdapter);
}
}
I am trying to pass some data from one activity to another and I have made a toast in the other activity to see if data is being passed.When the toast shows up it is blank.I have done everything right and tried many different times with different methods I have also created another app but the problem still stays.It gives me null.
My java code in the first activity
public class titleandcuisine extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
public static final String TITLE_GET = "title";
public static final String CUISINE_GET = "cuisine";
ImageView imageView;
Button button;
Spinner spinner;
EditText dish;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_titleandcuisine);
dish = findViewById(R.id.editText);
spinner = findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.cuisines,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
button = findViewById(R.id.next);
imageView = findViewById(R.id.close);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), homepage.class));
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = dish.getText().toString();
String text2 = spinner.getSelectedItem().toString();
Intent data = new Intent(getBaseContext(),imagepost.class);
data.putExtra(TITLE_GET,text);
data.putExtra(CUISINE_GET,text2);
startActivity(data);
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Second activity java code
public class reviewactivity extends AppCompatActivity {
TextView cuisine,title;
ImageView displayimage,back;
Uri myUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reviewactivity);
Intent intent = getIntent();
String titleget = intent.getStringExtra(titleandcuisine.TITLE_GET);
String cuisineget = intent.getStringExtra(titleandcuisine.CUISINE_GET);
Toast.makeText(this, titleget + cuisineget, Toast.LENGTH_SHORT).show();
cuisine = findViewById(R.id.reviewcuisine);
title = findViewById(R.id.reviewtitle);
back = findViewById(R.id.backtopostvideo);
displayimage = findViewById(R.id.reviewdisplaimage);
// cuisine.setText(cuisineget);
// title.setText(titleget);
// myUri = Uri.parse(uri);
displayimage.setImageURI(myUri);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),videopost.class));
}
});
}
}
You need to read the text from the EditText when the button is clicked. Something like:
title = dish.getText().toString(); // Add this
Intent data = new Intent(getBaseContext(),imagepost.class);
data.putExtra(Intent.EXTRA_TEXT, title);
...
One more thing: You are trying to read the Intent.EXTRA_TEXT at the reviewactivity activity. However, nothing is starting that activity (at least within the piece of code that you shared).
my promblem is : i cant use animition for intent becuse this calss extend recyclerView adapter i know overridePendingTransition();but its dont work for tis class
It does not know => overridePendingTransition(R.layout.one,R.layout.two);
public class ListAdapterw extends RecyclerView.Adapter {
List<cardViewhomeinfo> sliders;
ImageLoader imageLoader=ImageLoader.getInstance();
public ListAdapterw(List<cardViewhomeinfo> sliders) {
this.sliders = sliders;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View view=inflater.inflate(R.layout.recycleview_home,parent,false);
return new Holder(view);
}
#Override
public void onBindViewHolder(Holder holder, int position) {
holder.title.setText(sliders.get(position).getTitle());
holder.id=sliders.get(position).getId();
imageLoader.displayImage("http://wwwww"+sliders.get(position).getPicture(),holder.pic);
}
#Override
public int getItemCount() {
return sliders.size();
}
public class Holder extends RecyclerView.ViewHolder{
public TextView title;
public ImageView pic;
public String id="";
CardView cardView;
public Holder(final View itemView) {
super(itemView);
title=(TextView)itemView.findViewById(R.id.TitleCardView_home);
pic=(ImageView)itemView.findViewById(R.id.imageCardView_home);
cardView= (CardView) itemView.findViewById(R.id.cardView);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(itemView.getContext(),subCat.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("id",id);
overridePendingTransition(R.layout.one,R.layout.two);
itemView.getContext().startActivity(intent);
}
});
}
}
}
and my activtity
public class Home extends Fragment {
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view= inflater.inflate(R.layout.fragment_home, container, false);
JSON();
return view;
}
private void JSON() {
final RecyclerView recyclerView1 = (RecyclerView) view.findViewById(R.id.recycle_home);
StringRequest request=new StringRequest(Request.Method.GET, "", new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
List<cardViewhomeinfo> sliders = new ArrayList<>();
JSONArray jsonArray=new JSONArray(s);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
cardViewhomeinfo slider = new cardViewhomeinfo();
slider.setTitle(jsonObject.getString("title"));
slider.setPicture(jsonObject.getString("pic"));
slider.setId(jsonObject.getString("id"));
sliders.add(slider);
}
ListAdapterw adapter = new ListAdapterw(sliders);
recyclerView1.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
recyclerView1.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
dialog();
}
});
Volley.newRequestQueue(getActivity().getApplicationContext()).add(request);
}
private void dialog() {
Toast.makeText(getActivity().getApplicationContext(),"No INTENT",Toast.LENGTH_LONG).show();
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Home");
}
}
and subActivty
public class subCat extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_cat);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
final String idCat = intent.getStringExtra("id");
Toast.makeText(getApplicationContext(),idCat,Toast.LENGTH_LONG).show();}
Put your overridePendingTransition(R.layout.one,R.layout.two); code into the onCreate of the activity that you're going to when you click on cardView.
It should be something like this in your onCreate method of the activity:
public class subCat extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_cat);
overridePendingTransition(R.layout.one,R.layout.two); //Put it here.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
final String idCat = intent.getStringExtra("id");
Toast.makeText(getApplicationContext(),idCat,Toast.LENGTH_LONG).show();
}
Remove overridePendingTransition(R.layout.one,R.layout.two); this from the adapter class of your recycler view.
On the other hand,
overridePendingTransition(R.layout.one,R.layout.two);
it should be called
after finish();
or
after startActivity();
I have a problem with sending data from fragment to fragment. I have DialogFragment named fmonday, it is Viewpager's fragment.
I call other DialogFragment, named AlertDFragment to add some data to my fragment. I can read the data from spinner, it's working good.
Now I need to send one variable, type string, from AlertDFragment to fmonday.
Here is the code of fmonday:
public class fmonday extends DialogFragment implements LoaderManager.LoaderCallbacks<Cursor> {
DB db;
Button button12;
DialogFragment dlg1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dlg1 = new AlertDFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fmonday, container, false);
button12 = (Button) rootView.findViewById(R.id.button12);
button12.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dlg1.show(getFragmentManager(), "dlg1");
}
});
return rootView;
}
And code of AlertDFragment:
public class AlertDFragment extends DialogFragment {
Spinner spin;
DB db;
String string1;
Button button13;
private String namestr;
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
LayoutInflater li = LayoutInflater.from(getActivity());
View fdfS = li.inflate(R.layout.fdf, null);
adb.setView(fdfS);
spin=(Spinner)fdfS.findViewById(R.id.spinner);
db = new DB(getActivity());
db.open();
spin.setOnItemSelectedListener(new OnSpinnerItemClicked());
loadSpinnerData();
button13 = (Button) fdfS.findViewById(R.id.button13);
button13.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getActivity().getApplicationContext(), "Clicked : " +
string1, Toast.LENGTH_LONG).show();
getDialog().dismiss();
}
});
return adb.create();
}
I can't find the way to send this string1 variable to my fmonday DialogFragment, because simple intent doesn't work with non-activity things. Also read some advices about bundle, but couldn't find out how to work with it.
Thanks
UPDATE
fmonday:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dlg1 = new AlertDFragment();
string1 = getArguments().getString("latitude");
}
AlertDFragment:
public class AlertDFragment extends DialogFragment {
Spinner spin;
DB db;
String string1;
Button button13;
private String namestr;
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
LayoutInflater li = LayoutInflater.from(getActivity());
View fdfS = li.inflate(R.layout.fdf, null);
adb.setView(fdfS);
spin=(Spinner)fdfS.findViewById(R.id.spinner);
db = new DB(getActivity());
db.open();
spin.setOnItemSelectedListener(new OnSpinnerItemClicked());
loadSpinnerData();
button13 = (Button) fdfS.findViewById(R.id.button13);
button13.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getActivity().getApplicationContext(), "Clicked : " +
string1, Toast.LENGTH_LONG).show();
Bundle bundle = new Bundle();
bundle.putString("latitude", string1);
fmonday alertdfragment= new fmonday();
alertdfragment.setArguments(bundle);
getDialog().dismiss();
}
});
return adb.create();
}
To Set Data:
Bundle bundle = new Bundle();
bundle.putString("latitude", latitude);
MapFragment mapFragment = new MapFragment();
mapFragment.setArguments(bundle);
To Get Data
String latitude = getArguments().getString("latitude")
You can crate a setter to your second dialogFragment ex:
public void setSmth(String value)
{
this.myData = value;
}
, than on your first dialog
DialogFragment dlg1 = new AlertDFragment();
dlg1.setSmth(your data here);
before showing the second one;
im new to this and have some problems, thanks for your help.
Situation:
I have a MainActivity and a second Activity called MainAddMedActivity. I get data from the second activity through an EditText and save it in the database. My intention is to display the data from the EditText in a ListView in the MainActivity by taking it from the database. How to do it the right way ?
Med:
#Table(name = "Med")
public class Med extends Model {
// Zähler für eindeutige IDs
private static long counter = 0;
#Column(name = "_id", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)
public long id;
#Column(name = "Description", index = true)
public String description;
public Med() {
super();
}
public Med(String message) {
super();
id = counter++;
description = message;
}
}
MedDAO:
public class MedDAO {
public static List<Med> getAll(String text) {
return new Select()
.from(Med.class)
.where("Description like ?", new String[]{'%' + text + '%'})
.orderBy("Description")
.limit(40)
.execute();
}
public static List<Med> getAll() {
return new Select()
.all()
.from(Med.class)
.execute();
}
public static List<Med> getOneItem(String text) {
return new Select()
.from(Med.class)
.where("Description = ?", text)
.execute();
}
public static void insertMed(String msg){
new Med(msg).save();
}
public static void remove(String text) {
new Delete().from(Med.class).where("Description = ?", text).execute();
}
}
MainActivity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ArrayAdapter<String> listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), MainAddMedActivity.class);
startActivity(intent);
}
});
ListView mainListView = (ListView) findViewById(R.id.listView);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = listAdapter.getItem(position);
//Aus DB entfernen
MedDAO.remove(item);
//Aus Liste im Gui entfernen
listAdapter.remove(item);
Toast.makeText(getBaseContext(), item + "gelöscht", Toast.LENGTH_SHORT).show();
}
});
//TODO: ArrayAdapter bugt
//Adapter für die Liste erzeugen
listAdapter = new ArrayAdapter<String>(this, R.layout.single_row, R.id.listMedNrPart);
mainListView.setAdapter(listAdapter);
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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 void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onResume() {
super.onResume();
// MedDAO.getLatestItem();
/*int max = listAdapter.getCount();
int i = 0;
while (i < max){
Log.d("MainActivity", listAdapter.getItem(i));
i++;
}*/
// listAdapter.add(MedDAO.getLatestItem().toString());
}
}
MainAddMedActivity:
public class MainAddMedActivity extends AppCompatActivity {
private EditText txtSearchMedicament;
private EditText txtNumberMedicament;
private TextView txtAlarmPrompt;
private TimePickerDialog timePickerDialog;
private Switch switchReminder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_add_med);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText description = (EditText) findViewById(R.id.txtSearchMedicament);
String text = description.getText().toString();
**//SAVE IN DATABASE**
MedDAO.insertMed(text);
//TODO: Close Activity
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
this.txtSearchMedicament = (EditText) findViewById(R.id.txtSearchMedicament);
this.txtNumberMedicament = (EditText) findViewById(R.id.txtNumberMedicament);
this.txtAlarmPrompt = (TextView) findViewById(R.id.txtAlarmPrompt);
this.switchReminder = (Switch) findViewById(R.id.switchReminder);
switchReminder.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
cancelSwitch();
}
}
});
A Content Provider could be used. It takes a good amount of code to implement but it binds your database to your view.
Here is an example of a Content Provider I have implemented in the past.
You construct a ContentValue object (basically a set of values to mimic a database row) for your database keys and set your new data there. You then use getContentResolver() to insert the ContentValue into your Content Provider, which in turn updates your database with your new data.
ContentValues values = new ContentValues();
values.put(DatabaseHelper.KEY_VENUE_NAME, store.getName());
values.put(DatabaseHelper.KEY_VENUE_CITY, store.getCity());
values.put(DatabaseHelper.KEY_VENUE_STATE, store.getState());
//insert row
context.getContentResolver().insert(Uri.parse(ContentProvider.base_CONTENT_URI + index), values);
Here's an example of the Content Provider Class (too much code for here) which implements the logic for inserting, deleting, querying, editing, and constructing URI paths to your database.
You can then set up and use a Cursor, which iterates through your data source, to access the data from your Content Provider, more specifically you can extend CursorAdapter to directly bind your views to database queries. Here is what one looks like:
public class StoreCursorAdapter extends SimpleCursorAdapter {
private static final String TAG = "VenueCursorAdapter";
DatabaseHelper databaseHelper;
private Context context;
private int layout;
private int selection; //MapsActivity.getStoreSelection();
public StoreCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
databaseHelper = DatabaseHelper.getInstance(context);
this.context = context;
this.layout = layout;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(layout, parent, false);
return v;
}
#Override
public void bindView(View v, Context context, Cursor c) {
selection = ((MapsActivity) context).getStoreSelection();
int position = c.getPosition();
int nameColumn = c.getColumnIndex(DatabaseHelper.KEY_VENUE_NAME);
String name = c.getString(nameColumn);
TextView nameText = (TextView) v.findViewById(R.id.nameTextView);
TextView ratingText = (TextView) v.findViewById(R.id.ratingTextView);
if(nameText != null && ratingText != null) {
nameText.setText(name);
}
}
}