I have an edittext field in a tab which is given a unique autogenerated value when the activity is created. I want this value passed to a static class as soon as the value is put in the edittext so that on switching tabs, the value can be called from the static class.
My problem is i tried saving the value to the static class using the following code:
invoiceNo.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
//GlobalApp.data().id = invoiceNo.getText().toString();
}
public void beforeTextChanged(CharSequence s, int a, int b, int c){
GlobalApp.data().id = invoiceNo.getText().toString();
}
public void onTextChanged(CharSequence s, int a, int b, int c){
// GlobalApp.data().id = invoiceNo.getText().toString();
}
}
But it kept changing whenever the user returns to the 1st tab (where the value is generated) or it would not be displayed at all. I want it to save the generated value once irrespective of whether user returns to the 1st Tab.
public class clientFragmentTab extends Fragment {
ArrayList<String> saleRecord;
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c.getTime());
EditText currDate, invoiceNo , vehicle,territory ;
//Spinner clientName, territory;
View rootView = null;
int invoice_id = 0;
String invoice_no;
public String[] item = new String[] {"Please search..."};
public String territory1;
CustomAutoCompleteView myAutoComplete;
ProductsDbHelper db;
// adapter for auto-complete
ArrayAdapter<String> myAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.client_layout, container, false);
return rootView;
}
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
myAutoComplete = (CustomAutoCompleteView) rootView.findViewById(R.id.myautocomplete);
// add the listener so it will tries to suggest while the user types
myAutoComplete.addTextChangedListener(new CustomAutoCompleteTextChangedListener(this, getActivity()));
db = new ProductsDbHelper(getActivity());
// set our adapter
myAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_dropdown_item_1line, item);
myAutoComplete.setAdapter(myAdapter);
currDate = (EditText) rootView.findViewById(R.id.editText4);
//clientName = (Spinner) rootView.findViewById(R.id.spinner);
invoiceNo = (EditText) rootView.findViewById(R.id.editText3);
vehicle = (EditText) rootView.findViewById(R.id.editText6);
territory = (EditText) rootView.findViewById(R.id.editText9);invoice_id = UniqueRandomNumbers();
invoice_no = "invoice_" + invoice_id;
currDate.setText(formattedDate);
invoiceNo.setText(invoice_no);
//List<String> list = new ArrayList<String>();
//list.add("Select Client");
//list.add("Item 2");
//list.add("Item 3");
//list.add("Item 4");
//list.add("Item 5");
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_dropdown_item , list);
//adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//clientName.setAdapter(adapter);
// if(invoiceNo.getText().toString() != ""){
// }
invoiceNo.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
//GlobalApp.data().id = invoiceNo.getText().toString();
}
public void beforeTextChanged(CharSequence s, int a, int b, int c){
GlobalApp.data().id = invoiceNo.getText().toString();
}
public void onTextChanged(CharSequence s, int a, int b, int c){
// GlobalApp.data().id = invoiceNo.getText().toString();
}
}
);
}
You seem to be approaching this all wrong, when something feels like you're having to force it it usually signals a problem with the project architecture. The solution should be something like the following:
1. onCreate generate that id and store it in a *member variable*, lets call it mInvoiceId
2. onCreateView or onViewCreated do invoiceNo.setText(mInvoiceId)
3. if it's still required, in onTextChanged do mInvoiceId = s; (the 's' param should be the same result as invoiceNo.getText().toString() I believe)
4. if you're really set on using a static class you can replace any use of mInvoiceId with GlobalApp.data().id but static classes are usually bad.
- You can pass things between fragments correctly using saveInstanceState or intents with extras (not sure what you want to do)
I hope that sets you in the right direction
Related
In an activity I have a spinner where the user can select which date should be displayed in the activity.
But in the previous activity there can be a preselection done. This preselection is passed to the activity by intent.putExtra.
The problem is that when I want to set the preselection with setSelection in the onCreate function it is always overwritten by the onItemSelected function.
How can I do this in the right way?
The code locks like this:
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set layout
setContentView(R.layout.activity_list);
setTitle(getString(R.string.List_Title));
// for alerts
builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
// RecyclerView
adapter = new ListAdapter_rc(this);
lvArticle = (RecyclerView)findViewById(R.id.listView);
lvArticle.setAdapter(adapter);
lvArticle.setLayoutManager(new LinearLayoutManager(this));
new ItemTouchHelper(itemTouchCallback).attachToRecyclerView(lvArticle);
spListSelect = (Spinner)findViewById(R.id.spListSelect);
adapter.dbm = new DBManager(this);
ListAdapter_rc a = adapter;
ArrayList<String> slDummy = new ArrayList<>();
slDummy.addAll(adapter.dbm.listListGetNames());
slDummy.add("Default");
ArrayAdapter<String> adapt = new ArrayAdapter<String>(this, R.layout.spinner_item, slDummy);
spListSelect.setAdapter(adapt);
spListSelect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
adapter.setList(adapter.dbm.listListGet().get(i).id);
// THIS IS CALLED SECOND (i is always 0)
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {}
});
Bundle extras = getIntent().getExtras();
if (extras != null) {
adapter.adminMode = extras.getBoolean("adminMode");
int i = (int)extras.getLong("listSelcted", 0);
adapter.setList((long)i);
spListSelect.setSelection(i,false); // THIS IS CALLED FIRST (i has the desired value)
}
}
I'm trying to save text from the selected item of a ListView in OnItemClick.
I've tried so many different methods to no avail, I think I'm missing something really stupidly obvious here...
SnakesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String choice = SnakesListView.getItemAtPosition(position).toString();
Intent intent = new Intent(SnakeList.this, SnakeProfile.class);
intent.putExtra("SelectedSnakeName", choice);
startActivity(intent);
}
});
The data is being displayed fine, I just can't seem to reference it.
The line causing the exception:
String choice = SnakesListView.getItemAtPosition(position).toString();
Full code for this activity
public class SnakeList extends Activity {
ListView SnakesListView;
Cursor cursor;
Button NewSnakeBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snake_list);
SnakesListView = (ListView) findViewById(R.id.SnakesListView);
NewSnakeBtn = (Button) findViewById(R.id.NewSnake);
SQLiteDatabase db = openOrCreateDatabase("snakeDB", Context.MODE_PRIVATE, null); // ACCESSES DB
cursor = db.rawQuery("SELECT name FROM snakes", null); // SETS cursor TO RESULTS OF QUERY
List<String> SnakeNamesList = new ArrayList<String>();
ArrayAdapter SnakeNamesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, SnakeNamesList);
SnakeNamesList.clear(); // REMOVES ANY NAMES CURRENTLY IN NAME ARRAY TO AVOID DUPLICATES
SnakesListView.setAdapter(SnakeNamesAdapter);
if (cursor.moveToFirst()) {
cursor.moveToFirst(); // MOVES CURSOR TO FIRST POSITION
do SnakeNamesList.add(cursor.getString(0)); // RETURNS STRING FROM FIRST COLUMN (NAME)
while (cursor.moveToNext());
}
NewSnakeBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(SnakeList.this, NewSnake.class));
}
});
SnakesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String choice = SnakesListView.getItemAtPosition(position).toString();
Intent intent = new Intent(SnakeList.this, SnakeProfile.class);
intent.putExtra("SelectedSnakeName", choice);
startActivity(intent);
}
});
}
No use of referencing the ListView; you can get the value from adapter itself.
Change
String choice = SnakesListView.getItemAtPosition(position).toString();
to
String choice = SnakeNamesAdapter.getItem(position).toString();
declare the string arraylist(SnakeNamesList) as global variable and
change
String choice = SnakesListView.getItemAtPosition(position).toString();
to
String choice = SnakeNamesList.get(position);
Here is my first question on StackOverFlow, I usually always find an answer by myself but I am really stuck on a weird problem that I will explain here:
I implemented a ListView in a fragment activity, this listview contains a list of categories related to the current record that I get from the SQLLite database.
All is working fine, I created a SimpleCursorAdapter to retrieve the data from the DB and I display the categories correctly in the ListView.
The problem is related to the pre-fill of the checkboxes (it is a multiselection list), depending on how I try to pre-check the checkboxes, I get 2 cases:
First, the checkboxes are well pre-checked, but I cannot toggle the checkboxes anymore by clicking them. Second the click toggle well the checkboxes, but they are not pre-checked anymore...
Here is the part of the code where I have the problem:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//super.onCreate(savedInstanceState);
View v = inflater.inflate(R.layout.rate_fragment, container,false);
dbCategories = "";
displayCategories = resources.getText(R.string.no_categories).toString();
/** INITIALIZATION */
mViewSwitcher = (ViewSwitcher)v.findViewById(R.id.profileSwitcher);
/** Edition view */
rateGroup = (RadioGroup)v.findViewById(R.id.rate_group);
rateOne = (RadioButton)v.findViewById(R.id.one_button);
rateOne.setTag(1);
rateTwo = (RadioButton)v.findViewById(R.id.two_button);
rateTwo.setTag(2);
rateThree = (RadioButton)v.findViewById(R.id.three_button);
rateThree.setTag(3);
rateFour = (RadioButton)v.findViewById(R.id.four_button);
rateFour.setTag(4);
rateFive = (RadioButton)v.findViewById(R.id.five_button);
rateFive.setTag(5);
descET = (EditText)v.findViewById(R.id.editdescription);
descTextSize = descET.getTextSize();
descET.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
categoriesTV_edit = (TextView)v.findViewById(R.id.edit_categories);
categoriesBT = (Button) v.findViewById(R.id.select_categories);
categoriesBT.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
View categoriesListTitle = getActivity().getLayoutInflater().inflate(R.layout.category_list_title, null);
AlertDialog.Builder alt_bld = new AlertDialog.Builder(v.getContext()).setCustomTitle(categoriesListTitle);
categories = db.getAllCategoriesByRate(currentRate);
categoriesList = new ListView(getActivity());
categoriesList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
categoriesList.setClickable(true);
String[] fromColumns = new String[] {
DatabaseHandler.CATEGORY_NAME
};
int[] toViews = new int[]{
R.id.cat_checked
};
//mAdapter = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_multiple_choice, categories, fromColumns, toViews, 0);
mAdapter = new SimpleCursorAdapter(getActivity(), R.layout.category_item, categories, fromColumns, toViews, 0);
mAdapter.setViewBinder(new ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (columnIndex == 1) {
CheckedTextView categRow = (CheckedTextView) view;
String catName = cursor.getString(1);
mAdapter.setViewText((TextView) view, catName);
int catChecked = cursor.getInt(2);
//boolean checkedCat = catChecked==1;
//categoriesList.setItemChecked(cursor.getPosition(),checkedCat);
categRow.setChecked(catChecked==1);
int catID = cursor.getInt(0);
categRow.setTag(catID);
return true;
}
else {
return false;
}
}
});
categoriesList.setAdapter(mAdapter);
alt_bld.setView(categoriesList);
To have one case or another, all depends on these 2 lines:
//boolean checkedCat = catChecked==1;
//categoriesList.setItemChecked(cursor.getPosition(),checkedCat);
If they are commented, the checkboxes are not pre-checked, but the toggle on the clicks is working. But if I comment these lines out, the toggle is not working anymore but the categories are prechecked.
What I also don't understand is that this line is not working:
categRow.setChecked(catChecked==1);
But this one is working well (I succeed to retrieve the tag):
categRow.setTag(catID);
So I hope someone will succeed to explain to me what I do wrong, I guess there is something I misunderstood here...
NOTE: I get 3 columns from the cursor "categories", first one is the ID of the category, second one is the name, and third one is the status: checked or not (1 or 0).
Thanks in advance for your time.
Finally I ended up creating my own custom adapter, this way I could at least understand more easily what was happening.
I had to create actually several multiselect lists, some populated with data from the database, others from the shared preferences.
For this one displaying data from the DB, I created the following adapter (I commented out the lines about the icons because I did not set them up yet):
public class CategoriesLVAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private List<Category> categoriesList;
// Constructor
public CategoriesLVAdapter(Context c, List<Category> categories_list){
mContext = c;
mInflater = LayoutInflater.from(c);
categoriesList = categories_list;
}
public List<Category> getCategoriesList(){
return categoriesList;
}
#Override
public int getCount() {
return categoriesList.size();
}
#Override
public Object getItem(int position) {
return categoriesList.get(position);
}
#Override
public long getItemId(int position) {
return categoriesList.get(position).getID();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.categories_list_row, null);
//convertView.setLayoutParams(new ListView.LayoutParams(200, 90));
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.categories_list_row_tv);
//holder.icon = (ImageView) convertView.findViewById(R.id.categories_list_row_iv);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//holder.icon.setImageResource(categoriesList.get(position).getDrawableID());
//holder.icon.setAdjustViewBounds(true);
//holder.icon.setScaleType(ImageView.ScaleType.CENTER_CROP);
holder.title.setText(categoriesList.get(position).getName());
return convertView;
}
static class ViewHolder {
TextView title;
//ImageView icon;
}
}
In my activity, I use this adapter when the AlertDialog is called to populate the ListView, then I pre-select the categories using the last ones saved in the shared preferences:
private void categoriesFilter(){
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setTitle(resources.getText(R.string.select_categories).toString());
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.categories_list,(ViewGroup) findViewById(R.id.categories_layout_root));
categoriesLV = (ListView) layout.findViewById(R.id.categories_list);
alt_bld.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String selectedCategoriesString = getSelectedValues(categoriesLV);
//Update the shared preferences
prefs.edit().putString(RateDayApplication.PREF_KEY_CATEGORIES, selectedCategoriesString).commit();
updateFilterDisplay(resources.getText(R.string.cat_title).toString(), selectedCategoriesString, searchedCategoriesTV, "Category");
}
});
alt_bld.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
String selectedCategoriesString = prefs.getString(RateDayApplication.PREF_KEY_CATEGORIES, new String());
categoriesLV.setAdapter(new CategoriesLVAdapter(this, categoriesList));
String[] selectedCategoriesArray = selectedCategoriesString.split(",");
int categoriesLVLength = categoriesLV.getCount();
for(int i = 0; i < categoriesLVLength; i++){
int categoryID = ((Category) categoriesLV.getItemAtPosition(i)).getID();
if(Arrays.asList(selectedCategoriesArray).contains(String.valueOf(categoryID))){
categoriesLV.setItemChecked(i, true);
}
}
alt_bld.setView(layout);
AlertDialog alert = alt_bld.create();
alert.show();
}
Finally here is the function I call from my database handler to get the list of catagories:
// Getting All Categories By ID desc
public List<Category> getCategoriesList() {
String selectQuery = "SELECT " + CATEGORY_ID + ", " + CATEGORY_NAME + " FROM " + CATEGORY_TABLE + " ORDER BY " + CATEGORY_ID + " ASC";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
List<Category> categoriesList = new ArrayList<Category>();//String[] categoriesList = {};
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Category category = new Category(cursor.getInt(0), cursor.getString(1), false);
categoriesList.add(category);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return categoriesList;
}
I think my problem before was coming from the fact that the function "setItemChecked" is a little misleading because it does not mean necessarily that anything is checked.
When you use the function "setItemChecked", the item in the list view becomes selected, with or without a checkbox (my rows only contain text views).
The rows selected in my list appear in a different color, and that's enough in my opinion for a simple multi selection list.
The layouts I used are quite simple, "categories_list" contains a ListView in a LinearLayout and "categories_list_row" contains a TextView in a LinearLayout.
Hope it may guide someone!
OK, I am working on an App that has a page with a listview and a edittext box at top. As you type things into the edittext box it will filter what items are shown in the listview. The problem I am having is with the fast scroll icon that appears on the side of the slider.
When the page first loads NO MATTER what I do the fast scroll slider icon will not appear on the screen. Then I click in the edit text box and type one character and then erase it and now my fast scroll slider icon will appear.
First load no fast scroll icon.
Edittext box and then erase text and fast scroll icon appears.
I have the android:fastScrollEnabled="true" set in my listview. Plus I have set it manually in the code by doing lv1.setFastScrollEnabled(true);
No matter I change I still get the same behavior, unless I remove it complete from the code and xml and then it will stop working on the second page. I have tried cleaning my project and still no good. I am leaning towards it being a bug in android or I am missing something extremely simple.
Here is my code.
public class SearchByFood extends ParentClass
{
private ListView lv1;
private EditText ed;
int textlength = 0;
private ArrayList<String> arr_sort = new ArrayList<String>();
private ArrayList<String> foods = new ArrayList<String>();
private LayoutInflater mInflater;
private ArrayList<Food> foodList;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.search_by_food);
setTextTitle("Search by Food");
lv1 = (ListView) findViewById(R.id.ListView01);
ed = (EditText) findViewById(R.id.EditText01);
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
DataLayerFunctions d = new DataLayerFunctions(getApplicationContext());
foodList = d.selectFoodsWithSubstitutes();
for (Food f : foodList)
{
// this is to build a ArrayList<String> to pass to the setAdapter
Log.d("SearchByFood", "FoodName: " + f.getFood_Name());
foods.add(f.getFood_Name());
}
ArrayAdapter<String> firstAdapter = new ArrayAdapter<String>(SearchByFood.this, R.layout.search_food_listview, foods);
lv1.setAdapter(firstAdapter);
lv1.setFastScrollEnabled(true);
ed.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
textlength = ed.getText().length();
arr_sort.clear();
for (String f : foods)
{
if (textlength <= f.length())
{
if (f.toString().toLowerCase().contains((CharSequence) ed.getText().toString().toLowerCase()))
{
Log.d("STRING", "STRING: " + f.toString() + " contains " + ed.getText());
if (ed.getText().length() > 0)
{
String newString = boldMyString(f, ed.getText().toString());
arr_sort.add(newString);
}
else
{
arr_sort.add(f);
}
}
}
}
// if empty add a no foods found
if (arr_sort.isEmpty())
{
arr_sort.add("No Foods Found");
}
// Load array
// lv1.setAdapter(new
ArrayAdapter<String> adapter = new ArrayAdapter<String>(SearchByFood.this, R.layout.search_food_listview, arr_sort)
{
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row;
if (null == convertView)
{
row = mInflater.inflate(R.layout.search_food_listview, null);
}
else
{
row = convertView;
}
TextView tv = (TextView) row.findViewById(android.R.id.text1);
tv.setText(Html.fromHtml(getItem(position)));
// tv.setText(getItem(position));
return row;
}
};
lv1.setAdapter(adapter);
}
private String boldMyString(String foodName, String guess)
{
int gLength = guess.length();
ArrayList<Integer> results = new ArrayList<Integer>();
for (int i = foodName.toLowerCase().indexOf(guess.toLowerCase()); i >= 0; i = foodName.toLowerCase()
.indexOf(guess.toLowerCase(), i + 1))
{
System.out.println("TEST:" + i);
results.add(i);
}
// Count value is for words that have 2 or more values of guess
// in them.
int count = 0;
for (int i : results)
{
StringBuffer s1 = new StringBuffer(foodName);
s1.insert(i + count, "<b>");
count = count + 3;
s1.insert(i + count + gLength, "</b>");
count = count + 4;
foodName = s1.toString();
System.out.println("FOOD NAME:" + i + ":" + foodName);
}
return foodName;
}
});
// This is what actually does stuff when you click on a listview item.
lv1.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
// Strip out the bold tags
String clicked = (String) lv1.getItemAtPosition(position);
clicked = clicked.replaceAll("<b>", "");
System.out.println("Clicked" + clicked);
clicked = clicked.replaceAll("</b>", "");
// Find the Food ID match and pass the food id to the
// fooddisplay page
for (Food f : foodList)
{
if (null != clicked && clicked.equals(f.getFood_Name()))
{
Intent intent = new Intent(SearchByFood.this, SubstituteDisplay.class);
intent.putExtra("FoodID", f.getFood_ID());
startActivity(intent);
}
}
}
});
}
#Override
public void onBackPressed()
{
final Intent intent = new Intent(this, MasterTemplateActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
return;
}
}
Again, any help as to why my fast scroll icon doesn't show up at first would be much appreciated. It is a small thing but it is really annoying me.
try list.setFastScrollAlwaysVisible(true)
and also try list.smoothScrollToPosition(0); so that icon appears when scroll is called...
something like this..
new Handler().postDelayed(new Runnable() {
#Override
public void run(){
list.smoothScrollToPosition(0);
}
}, 100);
So again I'm posting this because my issue was genuinly different. Fast scrolling also doesn't seem to work in a ConstraintLayout. Both ListView Fast Scrolling and RecyclerView Fast Scrolling don't seem to work.
Been trying to get an answer on what I am doing wrong all over the place. I would like the user to select a button in the calling class, open a called listactivity which displays the contents of a database, let the user click an entry, copy that entry into a new database, send back the rowid from the new database to the calling class and have the calling class assign the title from the new database entry to the original button that was pushed.
Here is the calling class
static final private int CHOOSE_MONDAY = 0;
static final private int CHOOSE_TUESDAY = 0;
private int ButtonPushed = 0;
private NotesDbAdapter mDbHelper;
private MenuDbAdapter menuDbHelper;
private Long mRowId;
String menuTitle;
String menuProtein;
String menuBody;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.plan_menu);
Toast.makeText(this, "Choose a day to pick a meal for!", Toast.LENGTH_LONG).show();
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
menuDbHelper = new MenuDbAdapter(this);
menuDbHelper.open();
}
public void mButtonHandler(View target)
{
switch(target.getId())
{
case R.id.monday:
// Create new intent object and tell it to call the ColorPicker class
Intent question = new Intent(this, PlanMenuList.class);
// Start ColorPicker as a new activity and wait for the result
startActivityForResult(question, CHOOSE_MONDAY);
break;
case R.id.tuesday:
// Create new intent object and tell it to call the ColorPicker class
Intent question1 = new Intent(this, PlanMenuList.class);
// Start ColorPicker as a new activity and wait for the result
startActivityForResult(question1, CHOOSE_TUESDAY);
break;
}
And then this is the called class where I am trying to copy in the user's selection to the new database and then send back the id to the calling class.
public class PlanMenuList extends ListActivity {
private NotesDbAdapter mDbHelper;
private MenuDbAdapter menuDbHelper;
private List<Data>data;
String menuTitle;
String menuProtein;
String menuBody;
private Long mRowId;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes_list);
mDbHelper = new NotesDbAdapter(this);
menuDbHelper = new MenuDbAdapter(this);
mDbHelper.open();
menuDbHelper.open();
fillData();
}
private void fillData() {
Cursor notesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(notesCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{NotesDbAdapter.KEY_TITLE};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, notesCursor, from, to);
setListAdapter(notes);
}
private void populateFields() {
if (mRowId != null) {
Cursor note = mDbHelper.fetchNote(mRowId);
startManagingCursor(note);
menuTitle=(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
menuProtein=(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_PROTEIN)));
menuBody=(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
}
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
mDbHelper.fetchNote(id);
mRowId = id;
//populateFields();
menuDbHelper.createMenu("Monday", menuTitle, menuProtein, menuBody);
Intent answer = new Intent();
answer.putExtra("MenuDbAdapter.KEY_ROWID", mRowId);
setResult(RESULT_OK, answer);
finish();
}
}
I have been messing around with this thing for days and can't seem to get it to do what I want - any help would be appreciated.
Can you post your onActivityResult implementation?
When I've passed data back to an activity as a result, I've used Bundles. For example:
Intent answer = new Intent();
Bundle extras = new Bundle();
extras.putLong("MenuDbAdapter.KEY_ROWID", mRowId);
answer.putExtras(extras);
Then, in the activity result handler, you'd call Intent.getExtras and pull your value from there.
Edit: here are some examples from the android dev guide:
http://developer.android.com/guide/appendix/faq/commontasks.html (search for onActivityResult)
http://developer.android.com/resources/tutorials/notepad/notepad-ex3.html
protected void onListItemClick(ListView l, View v, int position, long id) {
the variable id is not the same as the database row number and thats where the issue is. I'd create a custom adapter and store the _id (row number) as a tag in the view. Retrieve the tag in the OnItemClickListener and do the db queries.
Custom Adapter code:
private class Cursy extends CursorAdapter {
public Cursy(Context context, Cursor c) {
super(context, c);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
viewHolder holder = (viewHolder) view.getTag();
holder.tv.setText(cursor.getString(cursor
.getColumnIndex(NotesDbAdapter.KEY_TITLE)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
viewHolder holder = new viewHolder();
holder._id = ursor.getString(cursor.getColumnIndex(NotesDbAdapter._ID));
View v = getLayoutInflater().inflate(
R.layout.list_layout, null);
holder.tv = (TextView) v
.findViewById(R.id.tv);
v.setTag(holder);
return v;
}
}
OnItemClickListener:
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
viewHolder holder = (viewHolder) view.getTag();
// use holder._id and do the db queries
}
});
Firstly, I think you want to make sure your CHOOSE_MONDAY and CHOOSE_TUESDAY constants are different values, so that you can differentiate between them later.
Secondly, you are sending back the wrong row ID to your original activity. Assuming your createMenu() method is based on SQLiteDatabase.insert(), it should return the row ID after insertion (or -1 if there was a problem). You can use this as the row ID:
mRowId = menuDbHelper.createMenu("Monday", menuTitle, menuProtein, menuBody);