I have 1 ImageView , 1 textview and 1 seekbar in listview items. Seekbar by default visiility is GONE. Now i want to set visibility of seekbar as per database value. If database value is YES then it will display seekbar on long press and if its No then it will do nothing on long press. Currently if i long press on any item it is showing seekbar.
ApplianceAdapter
public class ApplianceAdapter extends CursorAdapter {
public ApplianceAdapter(Context context, Cursor c) {
super(context, c, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.appliancelist, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView txtApplianceName = (TextView) view.findViewById(R.id.txtApplianceName);
final LinearLayout btnApp = (LinearLayout) view.findViewById(R.id.btnApp);
final SeekBar slider = (SeekBar) view.findViewById(R.id.slider);
String appliance = cursor.getString(cursor.getColumnIndexOrThrow("AppName"));
String dimmer = cursor.getString(cursor.getColumnIndexOrThrow("Dimmer"));
txtApplianceName.setText(appliance);
if (dimmer.contains("YES")){
btnApp.setLongClickable(true);
}else if (dimmer.contains("NO")){
btnApp.setLongClickable(false);
}
}
}
Appliance Activity
public class Appliance extends AppCompatActivity {
ListView listView;
ArrayList<HashMap<String,String>> applianceList;
DBOpenHelper db;
String room;
String type;
Cursor appliance;
ApplianceAdapter applianceAdapter;
SeekBar slider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appliance);
Intent intent = getIntent();
String r = intent.getStringExtra("roomname");
room = r.replace("{name=", "").replace("}","");
db = new DBOpenHelper(this);
listView = (ListView) findViewById(R.id.listAppliance);
appliance = db.getAppliance(room);
applianceAdapter = new ApplianceAdapter(this, appliance);
listView.setAdapter(applianceAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
slider = listView.getChildAt(position).findViewById(R.id.slider);
slider.setVisibility(View.VISIBLE);
return false;
}
});
}
}
You can try
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
youradapter.lastclicked=position;
youradapter.notifyDataSetChanged();
return false;
}
});
And in your adapter,
if (dimmer.contains("YES") && cursor.getPosition()==lastclicked){//initially lastclicked = -1
slider.setVisibility(View.VISIBLE);
}else if (dimmer.contains("NO")){
slider.setVisibility(View.GONE);
}
Related
I want to make OnItemClickListener to a dynamic listview. The listview shouldn't have a fixed size. Instead it's the size of the rows in a database. But how do I create the listener concidering I can't use the current method I have since I don't know the size of the listview.
THE PROBLEM IS IN THE INNER CLASS if(position==0) { ... }
public class VisaUtgiftFragment extends Fragment {
private MainActivity ui;
private TextView tvDatabase;
private MyDBHandler dbHandler;
private ListView lvUtgift;
public VisaUtgiftFragment() {
// Required empty public constructor
}
public void setActivity(MainActivity ui){
this.ui = ui;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_visa_utgift, container, false);
tvDatabase = (TextView)view.findViewById(R.id.tvDatabaseTest);
dbHandler = new MyDBHandler(getActivity(), null, null, 1);
tvDatabase.setText(dbHandler.databaseToString());
lvUtgift = (ListView)view.findViewById(R.id.lvUtgift);
// lvUtgift.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, [the rows in the database]));
lvUtgift.setAdapter(new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_1,
dbHandler.getAllItemsInCursor(),
new String[]{"_titel"},
new int[]{android.R.id.text1},
0));
lvUtgift.setOnItemClickListener(new ListViewClicked());
return view;
}
private class ListViewClicked implements android.widget.AdapterView.OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position==0) { //Should be the clicked listview and execute the code
Cursor cursor = (Cursor) lvUtgift.getItemAtPosition(position);
String string = cursor.getString(cursor.getColumnIndexOrThrow("_titel"));
Toast.makeText(getActivity().getApplicationContext(), string, Toast.LENGTH_SHORT).show();
ui.dVisaInkomst();
}
}
}
}
Remove if condition from onClickItem.
private class ListViewClicked implements android.widget.AdapterView.OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor cursor = (Cursor)lvUtgift.getItemAtPosition(position);
if(cursor != null){
String string = cursor.getString(cursor.getColumnIndexOrThrow("_titel"));
Toast.makeText(getActivity().getApplicationContext(), string, Toast.LENGTH_SHORT).show();
ui.dVisaInkomst();
}
}
}
Im starting an activity from onListItemClick Listener as shown
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent n = new Intent(ResultQuestionnaireList.this,ShowResult.class);
n.putExtra("title",""+adapter.getItem(position));
startActivity(n);
}
My problem is that whenever phone makes a sleep The new activity closed and my app return to the old activity ..
Any Help please?
UPDATE :
MY second activity code
public class ShowResult extends AppCompatActivity {
ProgressDialog pDialog;
private String URL_GET_Ques = //Myurl;
private String URL_GET_Ques = //Myurl;
private String URL_GET_RES = //Myurl;
private ArrayList<ResultObject> res;
private ArrayList<AtomQuestionnaire> ques;
private int type;
String title= "";
String question= "";
ArrayAdapter<String> spinnerAdapter;
Spinner spinner;
boolean questionReady=false;
int sortt = 1;
Spinner sortSpin ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_result);
Intent n= getIntent();
if(n.hasExtra("title")){
title = n.getStringExtra("title");
}
questionReady=false;
sortSpin = (Spinner)findViewById(R.id.spinnerType);
sortSpin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
sortt=position;
if(questionReady &&!question.equals("")) {
getExecuter(title, question, type, position);
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
spinner = (Spinner)findViewById(R.id.spinnerQues);
spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, android.R.id.text1);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
if(questionReady){
question= parentView.getSelectedItem().toString();
type = ques.get(position).getType();
Log.d("type",type+"");
getExecuter(title, question, type, sortt);
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
ques = new ArrayList<AtomQuestionnaire>();
new GetQuestions(title).execute();
}
public void getExecuter(String title ,String question,int type,int sort){
new GetResults( title,question,type,sort).execute();
}
}
I have a ListView that is within a Fragment. In the onCreateView section I have set a onItemClickListener for the list, which highlights the selected item in the ListView. I have set two ImageButtons that navigate up and down the list. On selection a new Row is inflated that has its TextView's set to the content of the select item (for the purpose of retaining the highlighted selected state). However I am having difficulty adding that item back to the list. The app will not compile due to the line routines.add(selectedPos-1, str); it wants wants int location, Routine object. I believe the issue is with my construction of my SelectedAdapter class, but I have been unable to determine what to change/pass with regard to the Object.
IE:
public SelectedAdapter(Context context, int textViewResourceId,List objects) {
super(getActivity(), R.layout.listview_routines, routines); }
I would greatly appreciate any input as how to correct this issue; as well as any advice if there is a better way to maintain a selected state. Thanks for your help.
Fragment:
public static class FragmentRoutine extends Fragment {
DatabaseHandler db;
private ListView routineListView;
private List<Routine> routines = new ArrayList<Routine>();
ArrayAdapter<Routine> routineAdapter;
Routine longClickedItemRoutines;
private SelectedAdapter selectedAdapter;
public FragmentRoutine() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.routines,
container, false);
db = new DatabaseHandler(getActivity().getApplicationContext());
routineListView = (ListView) rootView.findViewById(R.id.routineList);
registerForContextMenu(routineListView);
db.closeDB();
if (db.getExerciseCount() != 0)
routines.clear();
routines.addAll(db.getAllRoutines());
populateList();
selectedAdapter = new SelectedAdapter(this.getActivity(), 0, routines);
selectedAdapter.setNotifyOnChange(true);
routineListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickedItemRoutines = routines.get(position);
return false;
}
});
routineListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView arg0, View view,
int position, long id) {
selectedAdapter.setSelectedPosition(position);
}
});
routineListView.post(new Runnable() {
#Override
public void run() {
routineListView.setItemChecked(0, true);
}
});
// move up event handler
ImageButton btnMoveUp = (ImageButton) rootView.findViewById(R.id.btnMoveUp);
btnMoveUp.setOnClickListener(new AdapterView.OnClickListener() {
public void onClick(View arg0) {
moveUp();
}
});
// move down event handler
ImageButton btnMoveDown = (ImageButton) rootView.findViewById(R.id.btnMoveDown);
btnMoveDown.setOnClickListener(new AdapterView.OnClickListener() {
public void onClick(View arg0) {
moveDown();
}
});
setHasOptionsMenu(true);
return rootView;
}
// Move selected item "up" in the ViewList.
private void moveUp(){
Routine currentToDoSave = routines.get(selectedAdapter.getSelectedPosition());
int selectedPos = selectedAdapter.getSelectedPosition();
if (selectedPos > 0 ){
routines.remove(selectedPos);
String str = currentToDoSave.getTagName();
//Problem Line Below
routines.add(selectedPos-1, str);
// set selected position in the adapter
selectedAdapter.setSelectedPosition(selectedPos-1);
}
}
// Move selected item "down" in the ViewList.
private void moveDown(){
Routine currentToDoSave = routines.get(selectedAdapter.getSelectedPosition());
int selectedPos = selectedAdapter.getSelectedPosition();
if (selectedPos < routines.size()-1 ){
routines.remove(selectedPos);
String str = currentToDoSave.getTagName();
routines.add(selectedPos+1, str);
// set selected position in the adapter
selectedAdapter.setSelectedPosition(selectedPos+1);
}
}
public class SelectedAdapter extends ArrayAdapter<Routine>{
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
public SelectedAdapter(Context context, int textViewResourceId,
List objects) {
super(getActivity(), R.layout.listview_routines, routines);
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
// only inflate the view if it's null
if (v == null) {
LayoutInflater vi
= (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.selected_row, null);
}
// get text view
TextView label = (TextView)v.findViewById(R.id.txtExample);
// change the row color based on selected state
if(selectedPos == position){
label.setBackgroundColor(Color.CYAN);
}else{
label.setBackgroundColor(Color.WHITE);
}
label.setText(this.getItem(position).toString());
return(v);
}
}
private void populateList() {
routineAdapter = new SaveListAdapterT();
routineListView.setAdapter(routineAdapter);
}
public class SaveListAdapterT extends ArrayAdapter<Routine> {
public SaveListAdapterT() {
super(getActivity(), R.layout.listview_routines, routines);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getActivity().getLayoutInflater().inflate(R.layout.listview_routines, parent, false);
Routine currentToDoSave = routines.get(position);
TextView name = (TextView) view.findViewById(R.id.name);
name.setText(currentToDoSave.getTagName());
return view;
}
}
}
After researching on this for several days now, I'm posting my question hoping you'll be able to help me.
I'm using an ExpandableListView with CursorTreeAdapter to display data from database I have. The data for the group is showing up with no problem. When I expand MORE when one group to show the children and I scroll up and down, the children data changes. e.g. parents A, B, C has one child each with data A1, B1 and C1. When I expand parent A and C and I scroll up and down, A1 data changes (in most cases to B1 data). Only if I collapse C will A1 data show again for parent A.
The child layout
Can you advise as to why it is happenning and what can be done?
Here is my CursorTreeAdapter code from the newGroupView, bindGroupView, newChildView, bindChildView:
public class MyCursorTreeAdapter extends CursorTreeAdapter {
String name = "";
String phone = "";
String cityStreet = "";
String userNote2 = "";
DBConnector values;
long id = 0;
DBConnector cmpDb;
LayoutInflater mInflater;
Context context;
int oldGroupPosition;
public MyCursorTreeAdapter(Context context, Cursor cursor) {
super(cursor, context);
this.context = context;
values = new DBConnector(context);
this.values = values;
cmpDb = new DBConnector(context);
}
#Override
public View newGroupView(Context context, Cursor cursor, boolean isExpanded, ViewGroup parent) {
final View view = mInflater.inflate(R.layout.group_list_view, parent, false);
return view;
}
#Override
public void bindGroupView(View view, Context context, Cursor cursor, boolean isExpanded) {
TextView textsubText1 = (TextView) view.findViewById(R.id.subText1);
TextView textsubText2 = (TextView) view.findViewById(R.id.subText2);
textsubText1.setText(cursor.getString(cursor.getColumnIndex(values.Name)));
textsubText2.setText(cursor.getString(cursor.getColumnIndex(values.Name)));
userNote2 = cursor.getString(cursor.getColumnIndex(values.Note2));
}
#Override
public View newChildView(Context context, Cursor cursor, boolean isLastChild, ViewGroup parent) {
final View view = mInflater.inflate(R.layout.child_view, parent, false);
return view;
}
#Override
public void bindChildView(final View view, final Context context, final Cursor cursor, boolean isLastChild) {
values.open();
TextView nameTv = (TextView) view.findViewById(R.id.tvName);
TextView phoneTv = (TextView) view.findViewById(R.id.tvPhone);
TextView addressTv = (TextView) view.findViewById(R.id.tvAddress);
ImageButton btData1 = (ImageButton) view.findViewById(R.id.btData1);
ImageButton btData2 = (ImageButton) view.findViewById(R.id.btData2);
ImageButton btSaveData = (ImageButton) view.findViewById(R.id.btSaveData);
extractDataFromUserNote2();
nameTv.setText(""+ name);
phoneTv.setText(""+ phone);
addressTv.setText(""+ cityStreet);
android.view.View.OnClickListener doWithBtData1 = new Button.OnClickListener() {
#Override
public void onClick(View v) {
// action on btData1
}
};
android.view.View.OnClickListener doWithBtData2 = new Button.OnClickListener() {
#Override
public void onClick(View v) {
// action on btData2
}
};
android.view.View.OnClickListener doWithBtSaveData = new Button.OnClickListener() {
#Override
public void onClick(View v) {
// action on btSaveData
}
};
btData1.setOnClickListener(doWithBtData1);
btData2.setOnClickListener(doWithBtData2);
btSaveData.setOnClickListener(doWithBtSaveData);
values.close();
}
#Override
protected Cursor getChildrenCursor(Cursor groupCursor) {
return getCursor();
}
#Override
public int getChildrenCount (int groupPosition) {
return 1;
}
#Override
public void onGroupCollapsed (int groupPosition) {
}
#Override
public void onGroupExpanded (int groupPosition) {
}
protected Cursor setChildrenCursor(Cursor groupCursor) {
return groupCursor;
}
#Override
public void setGroupCursor (Cursor cursor) {
}
Thanks.
Ok, after many days of research I was able to find a way around this problem. I added an OnScroll call back function that collapses the expanded group once the user is scrolling in the list.
I wish I could find a more elegant way, but it is working.
Here is the code:
On the main parameter list:
int previousItem = -1;
The call back function:
elv.setOnScrollListener(new OnScrollListener() {
// This call back function close the group on scroll. It is used to override the but of view change.
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (previousItem != -1 && scrollState == 1) {
elv.collapseGroup(previousItem );
previousItem = -1;
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
The call back function to manage the Expand/Collapse of the group:
elv.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
if(groupPosition != previousItem ) {
elv.collapseGroup(previousItem );
}
previousItem = groupPosition;
}
});
I hope this will help you.
The problem is as follows: When I click on the row, dialog opens where I enter new row value and click ok to save changes. The row is updated, but I need to exit view and go back again to see changes. How can I refresh view automatically when the sava button is clicked?
Here is my code for Dialog:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
private SQLiteDatabase db;
public EditListItemDialog(Context context) {
super(context);
dba = new MyDB(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
dba.open();
}
private List<String> fragment_monday;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
adapter.getItem(position); //Will return the clicked item
}
public EditListItemDialog(Context context, DiaryAdapter adapter, int position) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
dba = new MyDB(context);
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
dismiss();
try {
saveItToDB();
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 2);
dba.close();
((TextView) editText).setText("");
}
}
And here is the code where I want to refresh view instead of doing it manually:
public class Monday extends ListActivity {
private SQLiteDatabase db;
private static final int MyMenu = 0;
MyDB dba;
DiaryAdapter myAdapter;
private class MyDiary{
public MyDiary(String t, String c){
title=t;
content=c;
}
public String title;
public String content;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
dba = new MyDB(this);
dba.open();
setContentView(R.layout.fragment_monday);
super.onCreate(savedInstanceState);
myAdapter = new DiaryAdapter(this);
this.setListAdapter(myAdapter);
}
public class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(Monday.this, null, position).show();
return true;
}
});
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
/** Called when the user clicks the Edit button */
public void visitDiary(View view) {
Intent intent = new Intent(this, Diary.class);
startActivity(intent);
}
/** Called when the user clicks the back button */
public void visitSchedule(View view) {
Intent intent = new Intent(this, DisplayScheduleScreen.class);
startActivity(intent);
}
}
I hope it's clear enough what I am looking for. Where my list is, I want the list to be refreshed automatically after updating row so the new content of the row shows up immediately instead of navigating to other view and going back. I will be appreciated for your help.
At some point, after you call EditListItemDialog and it finishes, you need to run NotifyDataSetChanged() on your listview adapter. onResume() is a good place to do it,