CheckBox in child of exapndablelistview (android) - android

Problem is with checkbox. When user click on child, app should show toast message on which child user clicked. It works fine if I click on textview of child, but when i click on checkbox, nothing heppend. Also when I click on child item, I want that my checkbox change state. Do you see something that I can't see. Here is my code for main activity
private ExpandableAdapter adapter;
private ExpandableListView expandableList;
private List<Pitanja> pitanjas = new ArrayList<Pitanja>();
private ArrayList<Pitanja> listaPitanja = new ArrayList<Pitanja>();
private List<Odgovor> odgovors = new ArrayList<Odgovor>();
public static HashMap<Integer, Integer> pitanjaa;
private Intent intent;
private ProgressDialog pDialog;
private TextView output;
private List<Ispit> ispitList;
private String pozicija;
private Button posalji;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ispit);
output = (TextView) findViewById(R.id.ispit_datum);
output.setMovementMethod(new ScrollingMovementMethod());
pitanjaa = new HashMap<Integer, Integer>();
posalji = (Button) findViewById(R.id.posaljiIspitButton);
posalji.setOnClickListener(this);
generateData();
initEx();
intent = getIntent();
RequestPackage p = new RequestPackage();
p.setUri("http://arka.foi.hr/WebDiP/2012_projekti/WebDiP2012_085/AIR/ispit.php");
p.setMethod("POST");
p.setParam("id_kolegij", intent.getStringExtra("id_predmeta"));
Log.i("Saljem podatke ", intent.getStringExtra("id_predmeta"));
MyTask task = new MyTask();
task.execute(p);
}
private void updateDisplay(){
Collections.shuffle(ispitList);
output.setText(String.valueOf(ispitList.get(0).getId()));
MyRequest task = new MyRequest();//this works fine
RequestPackage r = new RequestPackage();//works
r.setMethod("POST");//works
r.setUri("http://arka.foi.hr/WebDiP/2012_projekti/WebDiP2012_085/AIR/pitanja.php");//works
r.setParam("id_kolegij", output.getText().toString());//works
task.execute(r);
}
private void initEx(){
adapter = new ExpandableAdapter(IspitActivity.this, listaPitanja);
expandableList = (ExpandableListView) findViewById(R.id.expandableIspitListView);
expandableList.setAdapter(adapter);
for (int i=0;i<adapter.getGroupCount();i++){
expandableList.collapseGroup(i);
}
expandableList.setOnChildClickListener(new OnChildClickListener(){
#Override
public boolean onChildClick(ExpandableListView arg0, View arg1,
int arg2, int arg3, long arg4) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Klikno si na " + adapter.getChild(arg2, arg3).getText() + " " + adapter.getChild(arg2, arg3).getTocan_netocan(), Toast.LENGTH_SHORT).show();
if (Integer.parseInt(adapter.getChild(arg2, arg3).getTocan_netocan()) == 0)
pitanjaa.put(arg2, arg3);
Log.i("pitanja koja si odgovorio su", pitanjaa.toString());
adapter.getChild(arg2, arg3).setSelected(true);
return true;
}
});
}
private void generateData(){
Pitanja p;
for (int i=0;i<pitanjas.size();i++){
ArrayList<Odgovor> od = new ArrayList<Odgovor>();
for (int z=0;z<odgovors.size();z++){
if (odgovors.get(z).getId_pitanja().contains(String.valueOf(pitanjas.get(i).getId()))){
od.add(odgovors.get(z));
}
}
pozicija = pitanjas.get(i).getText();
p = new Pitanja(i, pozicija, od);
listaPitanja.add(p);
}
}
private class MyTask extends AsyncTask<RequestPackage, String, List<Ispit>>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(IspitActivity.this);
pDialog.setMessage("Dobavljam podatke...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected List<Ispit> doInBackground(RequestPackage... params) {
String content = HttpManager.getData(params[0]);
ispitList = JSONParser.parseIspit(content.substring(1, content.length()-1));
Log.i("Parsirano izgleda sljedeci", content.substring(1, content.length()-1));
return ispitList;
}
#Override
protected void onPostExecute(List<Ispit> result) {
super.onPostExecute(result);
pDialog.dismiss();
updateDisplay();
}
}
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), PregledActivity.class);
startActivity(intent);
}
}
Here is my expandablelistview adapter
public class ExpandableAdapter extends BaseExpandableListAdapter{
LayoutInflater inflater;
private List<Pitanja> groups;
public ExpandableAdapter(Context context,List<Pitanja> groups) {
super();
this.groups=groups;
inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(Odgovor child,Pitanja group) {
if(!groups.contains(group)) {
groups.add(group);
}
int index=groups.indexOf(group);
ArrayList<Odgovor> ch=groups.get(index).getOdgovors();
ch.add(child);
groups.get(index).setOdgovors(ch);
}
public Odgovor getChild(int groupPosition, int childPosition) {
ArrayList<Odgovor> ch=groups.get(groupPosition).getOdgovors();
return ch.get(childPosition);
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<Odgovor> ch=groups.get(groupPosition).getOdgovors();
return ch.size();
}
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
Odgovor child= (Odgovor) getChild(groupPosition,childPosition);
TextView childName=null;
CheckBox cb = null;
if(convertView==null) {
convertView=inflater.inflate(R.layout.child_item, null);
}
childName=(TextView) convertView.findViewById(R.id.textview_child_item);
childName.setText(child.getText());
cb = (CheckBox) convertView.findViewById(R.id.checkbox_child_item);
if (child.isSelected())
cb.setChecked(true);
return convertView;
}
public Pitanja getGroup(int groupPosition) {
return groups.get(groupPosition);
}
public int getGroupCount() {
return groups.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(final int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
TextView groupName = null;
Pitanja group=(Pitanja) getGroup(groupPosition);
if(convertView==null) {
convertView=inflater.inflate(R.layout.parent_item, null);
}
groupName=(TextView) convertView.findViewById(R.id.parent_item);
groupName.setText(group.getText());
return convertView;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public boolean hasStableIds() {
return true;
}
}
my child view
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/checkbox_child_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false" />
<TextView
android:id="#+id/textview_child_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
If I changle focusable of my checkbox, it doesn't work too. Someone have idea

The CheckBox will consume the click event before passing it on to the ExpandableListView click event. You'll need to manually attached a click listener to the CheckBox in the getChildView() method if you want to see those click events.

Related

Highlight Header View of expandable list view if Its at least one Child View is highlighted on Android Studio

I want Header View on expandable List View is automatically changed background color right after initial program if there is at least one of Child View be highlighted
I get this program from http://tutorialscache.com/expandable-listview-android-tutorials/ as an example
Here is the ExpandableCustomAdapter Class
public class ExpandableCustomAdapter extends BaseExpandableListAdapter{
//Initializing variables
private List<String> headerData;
private HashMap<String, ArrayList<ChildDataModel>> childData;
private Context mContext;
private LayoutInflater layoutInflater;
// constructor
public ExpandableCustomAdapter(Context mContext, List<String> headerData,
HashMap<String, ArrayList<ChildDataModel>> childData) {
this.mContext = mContext;
this.headerData = headerData;
this.childData = childData;
this.layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getGroupCount() {
return this.headerData.size();
}
#Override
public int getChildrenCount(int headPosition) {
return this.childData.get(this.headerData.get(headPosition)).size();
}
#Override
public Object getGroup(int headPosition) {
return this.headerData.get(headPosition);
}
#Override
public Object getChild(int headPosition, int childPosition) {
return this.childData.get(this.headerData.get(headPosition))
.get(childPosition);
}
#Override
public long getGroupId(int headPosition) {
return headPosition;
}
#Override
public long getChildId(int headPosition, int childPosition) {
return this.childData.get(this.headerData.get(headPosition))
.get(childPosition).getId();
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int headPosition, boolean is_expanded, View view, ViewGroup headGroup) {
// Heading of each group
String heading = (String) getGroup(headPosition);
if (view==null){
view = layoutInflater.inflate(R.layout.list_header,null);
}
TextView headerTv = view.findViewById(R.id.headerTv);
headerTv.setText(heading+"");
headerTv.setBackgroundColor( Color.BLUE );
return view;
}
#Override
public View getChildView(int headPosition, int childPosition, boolean islastChild, View view, ViewGroup viewGroup) {
ChildDataModel child = (ChildDataModel) getChild(headPosition, childPosition);
if (view == null) {
view = layoutInflater.inflate(R.layout.child_item, null);
}
TextView childTv = (TextView) view.findViewById(R.id.childTv);
ImageView childImg = (ImageView) view.findViewById(R.id.childImg);
childTv.setText(child.getTitle());
if(child.getTitle().equalsIgnoreCase( "China" ))
{
childTv.setBackgroundColor( Color.RED );
}
childImg.setImageResource(child.getImage());
return view;
}
#Override
public boolean isChildSelectable(int headPosition, int childPosition) {
return true;
}
}
Here is ChildDataModel Class
public class ChildDataModel {
long id;
int image;
String title;
public ChildDataModel(int id, String country, int image) {
this.setId(id);
this.setTitle(country);
this.setImage(image);
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
Log.d("response ","ID: "+getId()+" Title: "+getTitle());
return super.toString();
}
}
Here is MainActivity Class
public class MainActivity extends AppCompatActivity {
ExpandableCustomAdapter expandableCustomAdapter;
ExpandableListView expandableListView;
List<String> headerData;
HashMap<String,ArrayList<ChildDataModel>> childData;
ChildDataModel childDataModel;
Context mContext;
ArrayList<ChildDataModel> asianCountries,africanCountries,nAmericanCountries,sAmericanCountries;
private int lastExpandedPosition = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
//initializing arraylists
headerData = new ArrayList<>();
childData = new HashMap<String,ArrayList<ChildDataModel>>();
asianCountries = new ArrayList<>();
africanCountries = new ArrayList<>();
nAmericanCountries = new ArrayList<>();
sAmericanCountries = new ArrayList<>();
// link listview from activity_main.xml
expandableListView = findViewById(R.id.expandAbleListView);
//populating data of world continents and their countries.
headerData.add("ASIA");
//adding countries to Asian continent
childDataModel = new ChildDataModel(1,"Afghanistan",R.drawable.afghanistan);
asianCountries.add(childDataModel);
childDataModel = new ChildDataModel(2,"China",R.drawable.china);
asianCountries.add(childDataModel);
childDataModel = new ChildDataModel(3,"India",R.drawable.india);
asianCountries.add(childDataModel);
childDataModel = new ChildDataModel(4,"Pakistan",R.drawable.pakistan);
asianCountries.add(childDataModel);
childData.put(headerData.get(0),asianCountries);
headerData.add("AFRICA");
//adding countries to African continent
childDataModel = new ChildDataModel(1,"South Africa",R.drawable.southafrica);
africanCountries.add(childDataModel);
childDataModel = new ChildDataModel(2,"Zimbabwe",R.drawable.zimbabwe);
childData.put(headerData.get(1),africanCountries);
headerData.add("NORTH AMERICA");
//adding countries to NORTH AMERICA continent
childDataModel = new ChildDataModel(1,"Canada",R.drawable.canada);
nAmericanCountries.add(childDataModel);
childData.put(headerData.get(2),nAmericanCountries);
headerData.add("SOUTH AMERICA");
//adding countries to SOUTH AMERICA continent
childDataModel = new ChildDataModel(1,"Argentina",R.drawable.argentena);
sAmericanCountries.add(childDataModel);
childData.put(headerData.get(3),sAmericanCountries);
//set adapter to list view
expandableCustomAdapter = new ExpandableCustomAdapter(mContext,headerData,childData);
expandableListView.setAdapter(expandableCustomAdapter);
//child click listener
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView expandableListView, View view, int headPosition, int childPosition, long id) {
Toast.makeText(mContext,
headerData.get(headPosition)
+ " has country "
+ childData.get(
headerData.get(headPosition)).get(
childPosition).getTitle(), Toast.LENGTH_SHORT)
.show();
return false;
}
});
//group expanded
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int headPosition) {
if (lastExpandedPosition != -1
&& headPosition != lastExpandedPosition) {
expandableListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = headPosition;
Toast.makeText(mContext,
headerData.get(headPosition) + " continent expanded",
Toast.LENGTH_SHORT).show();
}
});
//group collapsed
expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int headPosition) {
Toast.makeText(mContext,
headerData.get(headPosition) + " continent collapsed",
Toast.LENGTH_SHORT).show();
}
});
//Group Indicator
expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
parent.smoothScrollToPosition(groupPosition);
if (parent.isGroupExpanded(groupPosition)) {
ImageView imageView = v.findViewById(R.id.expandable_icon);
imageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_right));
} else {
ImageView imageView = v.findViewById(R.id.expandable_icon);
imageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_down));
}
return false ;
}
});
}
}
I expect to handle it without event like setOnChildClickListener, setOnGroupExpandListener,setOnGroupCollapseListener, etc. Thanks for help
change getGroupView to:
#Override
public View getGroupView(int headPosition, boolean is_expanded, View view, ViewGroup headGroup) {
// Heading of each group
String heading = (String) getGroup(headPosition);
if (view==null){
view = layoutInflater.inflate(R.layout.list_header,null);
}
TextView headerTv = view.findViewById(R.id.headerTv);
headerTv.setText(heading+"");
boolean hasSelected = false;
ArrayList<ChildDataModel> childs =
childData.get(headerData.getItemAtIndex(headPosition));
for(int i=0;i<childs.size();i++){
if(childs.get(i).isSelected){
hasSelected = true;
}}
if(hasSelected)
headerTv.setBackgroundColor( Color.BLUE );
else
headerTv.setBackgroundColor( Color.RED);
return view;
}
you most highlight the header view when getGroupView executed if childs highl sign selected chileds and if selected eny then highlight header
Thank you #hunixa siuri It does work well. However Code must be edited a little as below
#Override
public View getGroupView(int headPosition, boolean is_expanded, View view, ViewGroup headGroup) {
// Heading of each group
String heading = (String) getGroup(headPosition);
if (view==null){
view = layoutInflater.inflate(R.layout.list_header,null);
}
TextView headerTv = view.findViewById(R.id.headerTv);
headerTv.setText(heading+"");
boolean hasSelected = false;
ArrayList<ChildDataModel> childs = childData.get(headerData.get(headPosition));
for(int i=0;i<childs.size();i++){
if(childs.get(i).getTitle().equalsIgnoreCase( "China" )){
hasSelected = true;
}}
if(hasSelected)
view.setBackgroundColor( Color.BLUE );
else
view.setBackgroundColor( Color.RED);
return view;
}

android listview, edittext same ID

I got a listView in a fragment. This listView use an BaseExpandableListAdapter. I got a list of question and for each of them, I have a list of answer. I add a Edittext after each last answer == last child (to add a new answer).
My problem is that each edittext has the same ID, so when I have more than one question, I can't write inside the edittext because two edittext have the same Id.
I don't know how to manage it :'(.
-> Fragment code :
public class HomeFragment extends Fragment implements AbsListView.OnItemClickListener {
private OnFragmentInteractionListener mListener;
/**
* The fragment's ListView/GridView.
*/
private AbsListView mListView;
/**
* The Adapter which will be used to populate the ListView/GridView with
* Views.
*/
private AdapterHomeFragment adapter;
private LinkedList<Question> listQuestion;
private ExpandableListView listView;
public static HomeFragment newInstance() {
HomeFragment fragment = new HomeFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
listQuestion = QuestionManager.getQuestionManager().getQuestionWithAnswerNotFromMe();
View rootView = inflater.inflate(R.layout.home_fragment, container, false);
listView = (ExpandableListView) rootView.findViewById(R.id.listView);
adapter = new AdapterHomeFragment(getActivity(), listQuestion);
listView.setAdapter(adapter);
listView.setGroupIndicator(null);
return rootView;
}
/*
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
*/
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
}
}
/**
* The default content for this Fragment has a TextView that is shown when
* the list is empty. If you would like to change the text, call this method
* to supply the text it should use.
*/
public void setEmptyText(CharSequence emptyText) {
View emptyView = mListView.getEmptyView();
if (emptyView instanceof TextView) {
((TextView) emptyView).setText(emptyText);
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(String id);
}
public void refreshData()
{
listQuestion = QuestionManager.getQuestionManager().getQuestionWithAnswerNotFromMe();
adapter = new AdapterHomeFragment(getActivity(), listQuestion);
listView.setAdapter(adapter);
listView.setGroupIndicator(null);
}
-> Adapter code :
public class AdapterHomeFragment extends BaseExpandableListAdapter {
private LinkedList<Question> groups;
public LayoutInflater inflater;
public Activity activity;
public AdapterHomeFragment(Activity act, LinkedList<Question> groups) {
activity = act;
this.groups = groups;
inflater = act.getLayoutInflater();
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return groups.get(groupPosition).getListAnswer().get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
if (!isLastChild) {
Answer answer = (Answer) getChild(groupPosition, childPosition);
TextView text = null;
convertView = inflater.inflate(R.layout.rowanswer_home, null);
text = (TextView) convertView.findViewById(R.id.rowanswer_home_answer);
text.setText(answer.getAnswer());
text = (TextView) convertView.findViewById(R.id.rowanswer_home_author);
text.setText("Anonymous"+answer.getUserId().toString());
text = (TextView) convertView.findViewById(R.id.rowanswer_home_time);
text.setText(answer.getDifferenceTime()+" ago");
}
else
{
TextView text = null;
convertView = inflater.inflate(R.layout.footer_answer, null);
final Question question = groups.get(groupPosition);
final EditText editText = (EditText)convertView.findViewById(R.id.footer_answer_edit_text);
final Button button = (Button) convertView.findViewById(R.id.footer_answer_button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String text_answer = editText.getText().toString();
QuestionManager.getQuestionManager().addAnswer(text_answer, question.getId());
groups = QuestionManager.getQuestionManager().getQuestionWithAnswerNotFromMe();
notifyDataSetChanged();
}
});
button.setEnabled(false);
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// you can call or do what you want with your EditText here
String text = editText.getText().toString();
if (verifyFormatString(text)) {
button.setEnabled(true);
} else
button.setEnabled(false);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
Log.d("test5780", String.valueOf(editText.getId()));
}
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return groups.get(groupPosition).getListAnswer().size() + 1;
}
#Override
public Object getGroup(int groupPosition) {
return groups.get(groupPosition);
}
#Override
public int getGroupCount() {
return groups.size();
}
#Override
public void onGroupCollapsed(int groupPosition) {
super.onGroupCollapsed(groupPosition);
}
#Override
public void onGroupExpanded(int groupPosition) {
super.onGroupExpanded(groupPosition);
}
#Override
public long getGroupId(int groupPosition) {
return 0;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
int nbAnswer;
if (convertView == null) {
convertView = inflater.inflate(R.layout.rowquestion_home, null);
}
Question question = (Question) getGroup(groupPosition);
((CheckedTextView) convertView.findViewById(R.id.rowquestion_home_question)).setText(question.getQuestion());
((CheckedTextView) convertView.findViewById(R.id.rowquestion_home_question)).setChecked(isExpanded);
((TextView) convertView.findViewById(R.id.rowquestion_home_author)).setText("Anonymous" + question.getUserId().toString());
((TextView) convertView.findViewById(R.id.rowquestion_home_time)).setText(question.getDifferenceTime()+ " ago");
nbAnswer = question.getListAnswer().size();
if (nbAnswer == 1)
((TextView) convertView.findViewById(R.id.rowquestion_home_nbAnswer)).setText(String.valueOf(question.getListAnswer().size()) + " answer");
else
((TextView) convertView.findViewById(R.id.rowquestion_home_nbAnswer)).setText(String.valueOf(question.getListAnswer().size()) + " answers");
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public boolean verifyFormatString (String question)
{
boolean valid = false;
int i = 0;
while (!valid && i < question.length())
{
if (question.charAt(i) != ' ')
valid = true;
i += 1;
}
return valid;
}
-> Xml of the footer
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="40dp"
android:clickable="true"
android:orientation="vertical"
android:paddingLeft="40dp"
android:background="#color/layout_button"
tools:context=".MainActivity" >
<View
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/footer_answer_block"
/>
<EditText
android:id="#+id/footer_answer_edit_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawablePadding="5dp"
android:gravity="center_vertical"
android:hint="Add answer"
android:textSize="14sp"
android:textStyle="italic"
android:layout_toLeftOf="#+id/footer_answer_button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</EditText>
<Button
android:id="#+id/footer_answer_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lines="1"
android:textSize="12sp"
android:text="add"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/footer_answer_block">
</Button>
If you have any idea how to resolve it, it will help me a lot !
Thank you.
When I click on the edittext the keyboard open but instant lose the focus on the edittext and it's impossible to write inside
You can use setTag() method of view. So whenever your getChildView() executes just set editText.setTag(position). Once user submit the answer you just need to find the tag that in which edit test user has typed by edittext.getTag(). It will return you the position which you tagged at the time of getChildView() execution. By that way you can get to know different answers once you have more than 1 question.
getChildView() Code
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
if (!isLastChild) {
Answer answer = (Answer) getChild(groupPosition, childPosition);
TextView text = null;
convertView = inflater.inflate(R.layout.rowanswer_home, null);
text = (TextView) convertView.findViewById(R.id.rowanswer_home_answer);
text.setText(answer.getAnswer());
text = (TextView) convertView.findViewById(R.id.rowanswer_home_author);
text.setText("Anonymous"+answer.getUserId().toString());
text = (TextView) convertView.findViewById(R.id.rowanswer_home_time);
text.setText(answer.getDifferenceTime()+" ago");
}
else
{
TextView text = null;
convertView = inflater.inflate(R.layout.footer_answer, null);
final Question question = groups.get(groupPosition);
final EditText editText = (EditText)convertView.findViewById(R.id.footer_answer_edit_text);
editText.setTag(childPosition);
final Button button = (Button) convertView.findViewById(R.id.footer_answer_button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String text_answer = editText.getText().toString();
QuestionManager.getQuestionManager().addAnswer(text_answer, question.getId());
groups = QuestionManager.getQuestionManager().getQuestionWithAnswerNotFromMe();
notifyDataSetChanged();
}
});
button.setEnabled(false);
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// you can call or do what you want with your EditText here
String text = editText.getText().toString();
int answeredPosition = (Integer)editText.getTag();
Log.d("Answered Position",""+answeredPosition);// This is the position of question in listview for which user has typed the answer.
if (verifyFormatString(text)) {
button.setEnabled(true);
} else
button.setEnabled(false);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
Log.d("test5780", String.valueOf(editText.getId()));
}
return convertView;
}
Let me know if it work or you need more descriptive answer.

Get child view from ExpandableListView in FragmentActivity without childClick Event

I have several classes. First class extends from FragmentActivity, second class is adapter extends from BaseExpandableListAdapter. And Model Class.
First class:
public class CloseInformationTaskActivityList extends FragmentActivity implements ExpandableListView.OnChildClickListener {
private DAOFactory dao;
private ExpandListAdapter expAdapter;
private ExpandableListView expandList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
//task with all information passed in intent by reference
PRTarea task = (PRTarea) b.getSerializable("Task");
dao = new DAOFactory(this.getApplicationContext());
List<PRParametros> parametrosList = dao.getParametrosDAO().getParamsByTaskId(task.getId());
if (parametrosList.size() > 0) {
setContentView(R.layout.activity_task_parameters_list);
expandList = (ExpandableListView) findViewById(R.id.paramsExpandableListView);
ArrayList<Group> expListItems = setParamsGroups(parametrosList);
expAdapter = new ExpandListAdapter(CloseInformationTaskActivityList.this, expListItems, this);
expandList.setOnChildClickListener(this);
expandList.setAdapter(expAdapter);
} else {
setContentView(R.layout.activity_no_param_error);
}
// Set up the action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home/Up button should not be enabled, since there is no hierarchical
// parent.
assert actionBar != null;
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setTitle(R.string.task_information_title);
actionBar.setIcon(R.drawable.ic_arrow_back_white_24dp);
}
private ArrayList<Group> setParamsGroups(List<PRParametros> parametrosList) {
ArrayList<Group> paramGroupList = new ArrayList<>();
ArrayList<Child> ch_list = null;
Group grupo;
String holdIdGroup = "0";
//secure check
if (parametrosList != null && parametrosList.size() > 0) {
for (int i = 0; i < parametrosList.size(); i++) {
PRParametros parametro = parametrosList.get(i);
String idGrupo = parametro.getIdGrupo();
if (!idGrupo.equals(holdIdGroup)) {
holdIdGroup = idGrupo;
grupo = new Group();
ch_list = new ArrayList<>();
grupo.setName(dao.getGruposParametrosDAO().getGrupoById(idGrupo).getDescripcion());
grupo.setItems(ch_list);
paramGroupList.add(grupo);
}
Child child = new Child();
child.setName(parametro.getNombre());
if(parametro.getIdTipo().equals("12")){
if(parametro.getValor() != null){
paramValue = dao.getListaParametrosDAO().getValueParamById(Integer.valueOf(parametro.getValor()));
}
}
child.setValue(paramValue);
child.setType(Integer.valueOf(parametro.getIdTipo()));
child.setParamId(Integer.valueOf(parametro.getId()));
if (ch_list != null) {
ch_list.add(child);
}
}
}
return paramGroupList;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.btn_save_param:
saveParameters();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void saveParameters() {
Toast.makeText(getApplicationContext(),"Save parameters click", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.save_parameters, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Child child = (Child) parent.getExpandableListAdapter().getChild(groupPosition,childPosition);
int itemType = child.getType();
switch (itemType){
case 12:
onCreateDialogSingleChoice(child, v);
break;
case 9:
openDateDialog(child, v);
break;
}
return false;
}
/**
* Open popup with single choice, refresh model data of child
* and assign selected value to textView
*
* #param child model with data
* #param view to asign selected value
*/
public void onCreateDialogSingleChoice(final Child child, final View view) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
List<PRListaParametros> listaParametros = dao.getListaParametrosDAO().getListParamsById(child.getParamId());
List<String> values = new ArrayList<>();
for(int i = 0; i < listaParametros.size(); i++){
values.add(listaParametros.get(i).getDescripcion());
}
final String[] items = values.toArray(new String[listaParametros.size()]);
final TextView label = (TextView) ((RelativeLayout) view).getChildAt(1);
builder.setTitle(R.string.task_information_param_popup_title);
builder.setSingleChoiceItems(items, 75, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
label.setText(items[which]);
child.setValue(items[which]);
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.task_information_param_popup_negative_button,new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
label.setText("");
}
});
builder.show();
}
}
Second class:
/**
* Adapter for expandable list with parameters
*/
public class ExpandListAdapter extends BaseExpandableListAdapter {
private Context mContext;
private ArrayList<Group> groups;
private LayoutInflater mInflater;
public ExpandListAdapter(Context mContext, ArrayList<Group> groups) {
this.mContext = mContext;
this.groups = groups;
mInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<Child> chList = groups.get(groupPosition).getItems();
return chList.get(childPosition);
}
#Override
public boolean areAllItemsEnabled() {
return super.areAllItemsEnabled();
}
#Override
public View getChildView(int groupPosition, final int childPosition,
final boolean isLastChild, View convertView, ViewGroup parent) {
final Child child = (Child) getChild(groupPosition, childPosition);
final ViewHolder holder;
int itemType = child.getType();
holder = new ViewHolder();
if (itemType >= 1 && itemType <= 7) {
convertView = mInflater.inflate(R.layout.layout_edit_text_close_information, null);
holder.txtLabel = (TextView) convertView.findViewById(R.id.txt_task_detail_info_param);
holder.editText = (EditText) convertView.findViewById(R.id.txt_task_detail_info_param_input);
holder.editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
//refresh data in model
child.setValue(holder.editText.getText().toString());
}
});
}else if(itemType == 8){
convertView = mInflater.inflate(R.layout.layout_boolean_close_information, null);
holder.txtLabel = (TextView) convertView.findViewById(R.id.txt_task_detail_info_param_boolean_title);
holder.booleanSwitch = (Switch) convertView.findViewById(R.id.param_boolean_switch);
holder.booleanSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String switchValue = "false";
if(holder.booleanSwitch.isChecked()){
switchValue = "true";
}
child.setValue(switchValue);
//mParamListener.onParameterViewClick(v, child);
}
});
}else {
convertView = mInflater.inflate(R.layout.layout_text_view_close_information, null);
holder.txtLabel = (TextView) convertView.findViewById(R.id.txt_task_detail_info_param_text_view);
holder.txtClickWithValue = (TextView) convertView.findViewById(R.id.txt_task_detail_info_param_click_text_view);
}
convertView.setTag(holder);
if (itemType >= 1 && itemType <= 7) {
holder.txtLabel.setText(child.getName());
holder.editText.setText(child.getValue());
switch (itemType){
case 1:
holder.editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_NUMBER);
holder.editText.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
break;
case 2:
holder.editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_NUMBER);
holder.editText.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
break;
case 6:
holder.editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_NUMBER);
holder.editText.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
if(!holder.editText.getText().toString().isEmpty()){
if(!isValidIp(holder.editText.getText().toString())){
holder.editText.setError("IPv 4 no valido");
}
}
break;
case 7:
holder.editText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS);
if(!holder.editText.getText().toString().equals("")){
if(!isValidIp(holder.editText.getText().toString())){
holder.editText.setError("IPv 6 no valido");
}
}
holder.editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if(!isValidIp(holder.editText.getText().toString())){
holder.editText.setError("IPv 6 no valido");
}
}
});
break;
}
}else if(itemType == 8) {
boolean value = Boolean.valueOf(child.getValue());
holder.txtLabel.setText(child.getName());
if(value){
holder.booleanSwitch.setTextOn(mContext.getResources().getString(R.string.task_information_param_boolean_switch_on));
holder.booleanSwitch.setChecked(true);
}else{
holder.booleanSwitch.setTextOff(mContext.getResources().getString(R.string.task_information_param_boolean_switch_off));
holder.booleanSwitch.setChecked(false);
}
}else {
holder.txtLabel.setText(child.getName());
holder.txtClickWithValue.setText(child.getValue());
}
return convertView;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
super.registerDataSetObserver(observer);
//call notifyDataSetChanged() for refresh data model in view
}
public static class ViewHolder {
public TextView txtLabel;
public EditText editText;
public TextView txtClickWithValue;
public Switch booleanSwitch;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<Child> chList = groups.get(groupPosition).getItems();
return chList.size();
}
#Override
public Object getGroup(int groupPosition) {
return groups.get(groupPosition);
}
#Override
public int getGroupCount() {
return groups.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
Group group = (Group) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater inf = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.activity_task_parameters_group, null);
}
TextView groupTitle = (TextView) convertView.findViewById(R.id.param_group_name);
groupTitle.setText(group.getName());
TextView groupCount = (TextView) convertView.findViewById(R.id.param_group_count);
int countParam = getChildrenCount(groupPosition);
if(countParam > 1){
groupCount.setText(getChildrenCount(groupPosition) + " " +
mContext.getResources().getString(R.string.task_information_param_group_count_title));
}else{
groupCount.setText(getChildrenCount(groupPosition) + " " +
mContext.getResources().getString(R.string.task_information_param_group_count_title_single));
}
if (isExpanded) {
convertView.setBackgroundResource(R.color.group_param_expanded);
} else {
convertView.setBackgroundResource(0);
}
return convertView;
}
#Override
public int getChildType(int groupPosition, int childPosition) {
return super.getChildType(groupPosition, childPosition);
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
/**
* #param ip the ip
* #return check if the ip is valid ipv4 or ipv6
*/
private static boolean isValidIp(final String ip) {
return InetAddressUtils.isIPv4Address(ip) || InetAddressUtils.isIPv6Address(ip);
}
}
Model Class
/**
* Model of each parameters
*/
public class Child {
private String name;
private String value;
private int type;
private int paramId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getParamId() {
return paramId;
}
public void setParamId(int paramId) {
this.paramId = paramId;
}
}
XML View of each child by type, possible type is EditText, TextView, Switch, popup list with single choice.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp">
<TextView
android:id="#+id/txt_task_detail_info_param"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:minWidth="150dp"
android:focusable="false"
android:clickable="false"
android:padding="20dp"
android:textSize="14sp"
android:layout_toLeftOf="#+id/txt_task_detail_info_param_input"
android:layout_alignParentLeft="true" />
<EditText
android:id="#+id/txt_task_detail_info_param_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="150dp"
android:maxWidth="200dp"
android:ellipsize="end"
android:maxLines="1"
android:textSize="14sp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
Layout have action bar with save button:
|------------------Save button--|
| <ExpandableList> | |
| group1 | |
| child1: textView EditText | |
| child2: textView Switch | |
| group2 | |
| child1: textView TextView | |
|-------------------------------|
I am trying to get values of child view for save it in database, before i need check each field by type for valid data.
Currently i am checking the values in adapter and works well. Possibly not the right way...
But how to get value of each view by type only clicking save button in FragmentActivity in action bar??
I am trying onChildClick but click event by editText not working. Thanks!
SOLVED
Now I have resolved, but I think is not the right way for do it.
In model class Child i created new field with View.
private View view;
and assigned complete View by type (editText,TextView, etc) in adapter getChildView for example:
child.setView(holder.editText);
and finally use in FragmentActivity
private void checkParameters() {
boolean validated = true;
int groupCount = expandList.getExpandableListAdapter().getGroupCount();
for (int i = 0; i < groupCount; i++) {
int childCount = expandList.getExpandableListAdapter().getChildrenCount(i);
for (int j = 0; j < childCount; j++) {
Child child = (Child) expandList.getExpandableListAdapter().getChild(i, j);
//secure check
if (child.getView() != null) {
int itemType = child.getType();
//only editText
if (itemType >= 1 && itemType <= 7) {
EditText ed = (EditText) child.getView();
//do something
}
}
}
}
}
Anyone know how to do this more efficiently???

Update Activity list in Android after deleting element

I've a problem, obviously!
I need to refresh the content called by a TabHost after having deleted an element (It's a favorite page and I gave the user the possibility to eliminate the favorite he desired), How can I do that?
Here is the code (The row is in an expandable list view) of the Favourite page.
package it.sii.android.jobaroundu;
public class Preferiti extends ExpandableListActivity{
//Initialize variables
private static final String STR_CHECKED = " has Checked!";
private static final String STR_UNCHECKED = " has unChecked!";
private int ParentClickStatus=-1;
private int ChildClickStatus=-1;
//aggiustare creando la classe annunci_parent e annunci_child
private ArrayList<Parent> pref=new ArrayList<Parent>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyDBHelper dbHelper = new MyDBHelper(this,"JobAroundU_DB", null, 1);
SQLiteDatabase db=dbHelper.getWritableDatabase();
Resources res = this.getResources();
Drawable devider = res.getDrawable(R.drawable.line);
// Set ExpandableListView values
getExpandableListView().setGroupIndicator(null);
getExpandableListView().setDivider(devider);
getExpandableListView().setChildDivider(devider);
getExpandableListView().setDividerHeight(1);
registerForContextMenu(getExpandableListView());
//RECUPERO RICERCHE RECENTI
String sqlSavedPreferences="SELECT * FROM MyPreferences";
Cursor cursor = db.rawQuery(sqlSavedPreferences, null);
//creo padre e aggiungo ad esso le info
while (cursor.moveToNext()){
Parent p= new Parent();
p.setPosizione(cursor.getString(1));
p.setAzienza(cursor.getString(2));
p.setId(cursor.getString(4));
Log.i("Parent ID", p.getId());
Child cp = new Child();
cp.setDescrizione(cursor.getString(3));
p.setChildren(new ArrayList<Child>());
p.getChildren().add(cp);
pref.add(p);
}
db.close();
cursor.close();
//se parents e' vuoto --> messaggio errore --> non esistono preferiti salvati
if (pref.isEmpty()) {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));
ImageView image = (ImageView) layout.findViewById(R.id.immagine);
image.setImageDrawable(getResources().getDrawable(R.drawable.icon_25761));
TextView text = (TextView) layout.findViewById(R.id.ToastTV);
text.setText("Non ci sono preferiti da visualizzare!!!");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
String n = getIntent().getStringExtra(getPackageName()+".Username");
Intent i = new Intent(this, PersonalPage.class);
i.putExtra(getPackageName()+".Username", n);
startActivity(i);
}
if (this.getExpandableListAdapter() == null) {
//Create ExpandableListAdapter Object
final MyExpandableListAdapter mAdapter = new MyExpandableListAdapter();
// Set Adapter to ExpandableList Adapter
this.setListAdapter(mAdapter);
}
else
{
// Refresh ExpandableListView data
((MyExpandableListAdapter)getExpandableListAdapter()).notifyDataSetChanged();
}
}
private class MyExpandableListAdapter extends BaseExpandableListAdapter{
private LayoutInflater inflater;
//protected SQLiteOpenHelper dbHelper2 =new MyDBHelper(PaginaRisultati.this,"JobAroundU_DB", null, 1);
public MyExpandableListAdapter(){
// Create Layout Inflator
inflater = LayoutInflater.from(Preferiti.this);
}
// This Function used to inflate parent rows view
#Override
public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parentView){
final Parent parent = pref.get(groupPosition);
// Inflate grouprow.xml file for parent rows
convertView = inflater.inflate(R.layout.grouprow_pref, parentView, false);
// Get grouprow.xml file elements and set values
((TextView) convertView.findViewById(R.id.text1)).setText(parent.getPosizione());
((TextView) convertView.findViewById(R.id.TVAzienda)).setText(parent.getAzienda());
ImageView image=(ImageView)convertView.findViewById(R.id.image_tag);
image.setImageResource(R.drawable.yellow_star);
ImageButton bin = (ImageButton)convertView.findViewById(R.id.imageButton_bin);
bin.setFocusable(false);
bin.setOnClickListener(new OnClickListener(){
#Override
public void onClick(final View v) {
AlertDialog.Builder alt_bld = new AlertDialog.Builder(Preferiti.this);
alt_bld.setMessage("Sei sicuro di voler eliminare l'utente dai preferiti?")
.setCancelable(false)
.setPositiveButton("Si", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
MyDBHelper dbHelper2 = new MyDBHelper(Preferiti.this,"JobAroundU_DB", null, 1);
SQLiteDatabase db2=dbHelper2.getWritableDatabase();
String sqlDelete = "DELETE FROM MyPreferences WHERE idDBJobs="+parent.getId()+";";
db2.execSQL(sqlDelete);
db2.close();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("CANCELLARE QUESTO PREFERITO?");
// Icon for AlertDialog
alert.setIcon(R.drawable.trash_empty);
alert.show();
//elimino il preferito dal db
Log.i("DELETING", "I'm deleting "+parent.getId()+" Position: "+parent.getPosizione());
}
});
return convertView;
}
// This Function used to inflate child rows view
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parentView){
final Parent parent = pref.get(groupPosition);
final Child child = parent.getChildren().get(childPosition);
// Inflate childrow.xml file for child rows
convertView = inflater.inflate(R.layout.childrow_pref, parentView, false);
// Get childrow.xml file elements and set values
/***DESCRIZIONE***/
((TextView) convertView.findViewById(R.id.TVDescrizione)).setText(child.getDescrizione());
ImageView image=(ImageView)convertView.findViewById(R.id.image_tag);
image.setImageResource(R.drawable.icon_16301);
return convertView;
}
#Override
public Object getChild(int groupPosition, int childPosition)
{
//Log.i("Childs", groupPosition+"= getChild =="+childPosition);
return pref.get(groupPosition).getChildren().get(childPosition);
}
//Call when child row clicked
#Override
public long getChildId(int groupPosition, int childPosition)
{
/****** When Child row clicked then this function call *******/
if( ChildClickStatus!=childPosition)
{
ChildClickStatus = childPosition;
}
return childPosition;
}
#Override
public int getChildrenCount(int groupPosition)
{
int size=0;
if(pref.get(groupPosition).getChildren()!=null)
size = pref.get(groupPosition).getChildren().size();
return size;
}
#Override
public Object getGroup(int groupPosition)
{
Log.i("Parent", groupPosition+"= getGroup ");
return pref.get(groupPosition);
}
#Override
public int getGroupCount()
{
return pref.size();
}
//Call when parent row clicked
#Override
public long getGroupId(int groupPosition)
{
ParentClickStatus=groupPosition;
if(ParentClickStatus==0)
ParentClickStatus=-1;
return groupPosition;
}
#Override
public void notifyDataSetChanged()
{
// Refresh List rows
super.notifyDataSetChanged();
}
#Override
public boolean isEmpty()
{
return ((pref == null) || pref.isEmpty());
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
return true;
}
/******************* Checkbox Checked Change Listener ********************/
private final class CheckUpdateListener implements OnCheckedChangeListener
{
private final Parent parent;
private CheckUpdateListener(Parent parent)
{
this.parent = parent;
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
Log.i("onCheckedChanged", "isChecked: "+isChecked);
parent.setChecked(isChecked);
((MyExpandableListAdapter)getExpandableListAdapter()).notifyDataSetChanged();
final Boolean checked = parent.isChecked();
}
}
/***********************************************************************/
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
}
}
and here the code of the TabHost.
package it.sii.android.jobaroundu;
public class Preferiti extends ExpandableListActivity{
//Initialize variables
private static final String STR_CHECKED = " has Checked!";
private static final String STR_UNCHECKED = " has unChecked!";
private int ParentClickStatus=-1;
private int ChildClickStatus=-1;
//aggiustare creando la classe annunci_parent e annunci_child
private ArrayList<Parent> pref=new ArrayList<Parent>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyDBHelper dbHelper = new MyDBHelper(this,"JobAroundU_DB", null, 1);
SQLiteDatabase db=dbHelper.getWritableDatabase();
Resources res = this.getResources();
Drawable devider = res.getDrawable(R.drawable.line);
// Set ExpandableListView values
getExpandableListView().setGroupIndicator(null);
getExpandableListView().setDivider(devider);
getExpandableListView().setChildDivider(devider);
getExpandableListView().setDividerHeight(1);
registerForContextMenu(getExpandableListView());
//RECUPERO RICERCHE RECENTI
String sqlSavedPreferences="SELECT * FROM MyPreferences";
Cursor cursor = db.rawQuery(sqlSavedPreferences, null);
//creo padre e aggiungo ad esso le info
while (cursor.moveToNext()){
Parent p= new Parent();
p.setPosizione(cursor.getString(1));
p.setAzienza(cursor.getString(2));
p.setId(cursor.getString(4));
Log.i("Parent ID", p.getId());
Child cp = new Child();
cp.setDescrizione(cursor.getString(3));
p.setChildren(new ArrayList<Child>());
p.getChildren().add(cp);
pref.add(p);
}
db.close();
cursor.close();
//se parents e' vuoto --> messaggio errore --> non esistono preferiti salvati
if (pref.isEmpty()) {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));
ImageView image = (ImageView) layout.findViewById(R.id.immagine);
image.setImageDrawable(getResources().getDrawable(R.drawable.icon_25761));
TextView text = (TextView) layout.findViewById(R.id.ToastTV);
text.setText("Non ci sono preferiti da visualizzare!!!");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
String n = getIntent().getStringExtra(getPackageName()+".Username");
Intent i = new Intent(this, PersonalPage.class);
i.putExtra(getPackageName()+".Username", n);
startActivity(i);
}
if (this.getExpandableListAdapter() == null) {
//Create ExpandableListAdapter Object
final MyExpandableListAdapter mAdapter = new MyExpandableListAdapter();
// Set Adapter to ExpandableList Adapter
this.setListAdapter(mAdapter);
}
else
{
// Refresh ExpandableListView data
((MyExpandableListAdapter)getExpandableListAdapter()).notifyDataSetChanged();
}
}
private class MyExpandableListAdapter extends BaseExpandableListAdapter{
private LayoutInflater inflater;
//protected SQLiteOpenHelper dbHelper2 =new MyDBHelper(PaginaRisultati.this,"JobAroundU_DB", null, 1);
public MyExpandableListAdapter(){
// Create Layout Inflator
inflater = LayoutInflater.from(Preferiti.this);
}
// This Function used to inflate parent rows view
#Override
public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parentView){
final Parent parent = pref.get(groupPosition);
// Inflate grouprow.xml file for parent rows
convertView = inflater.inflate(R.layout.grouprow_pref, parentView, false);
// Get grouprow.xml file elements and set values
((TextView) convertView.findViewById(R.id.text1)).setText(parent.getPosizione());
((TextView) convertView.findViewById(R.id.TVAzienda)).setText(parent.getAzienda());
ImageView image=(ImageView)convertView.findViewById(R.id.image_tag);
image.setImageResource(R.drawable.yellow_star);
ImageButton bin = (ImageButton)convertView.findViewById(R.id.imageButton_bin);
bin.setFocusable(false);
bin.setOnClickListener(new OnClickListener(){
#Override
public void onClick(final View v) {
AlertDialog.Builder alt_bld = new AlertDialog.Builder(Preferiti.this);
alt_bld.setMessage("Sei sicuro di voler eliminare l'utente dai preferiti?")
.setCancelable(false)
.setPositiveButton("Si", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
MyDBHelper dbHelper2 = new MyDBHelper(Preferiti.this,"JobAroundU_DB", null, 1);
SQLiteDatabase db2=dbHelper2.getWritableDatabase();
String sqlDelete = "DELETE FROM MyPreferences WHERE idDBJobs="+parent.getId()+";";
db2.execSQL(sqlDelete);
db2.close();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("CANCELLARE QUESTO PREFERITO?");
// Icon for AlertDialog
alert.setIcon(R.drawable.trash_empty);
alert.show();
//elimino il preferito dal db
Log.i("DELETING", "I'm deleting "+parent.getId()+" Position: "+parent.getPosizione());
}
});
return convertView;
}
// This Function used to inflate child rows view
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parentView){
final Parent parent = pref.get(groupPosition);
final Child child = parent.getChildren().get(childPosition);
// Inflate childrow.xml file for child rows
convertView = inflater.inflate(R.layout.childrow_pref, parentView, false);
// Get childrow.xml file elements and set values
/***DESCRIZIONE***/
((TextView) convertView.findViewById(R.id.TVDescrizione)).setText(child.getDescrizione());
ImageView image=(ImageView)convertView.findViewById(R.id.image_tag);
image.setImageResource(R.drawable.icon_16301);
return convertView;
}
#Override
public Object getChild(int groupPosition, int childPosition)
{
//Log.i("Childs", groupPosition+"= getChild =="+childPosition);
return pref.get(groupPosition).getChildren().get(childPosition);
}
//Call when child row clicked
#Override
public long getChildId(int groupPosition, int childPosition)
{
/****** When Child row clicked then this function call *******/
if( ChildClickStatus!=childPosition)
{
ChildClickStatus = childPosition;
}
return childPosition;
}
#Override
public int getChildrenCount(int groupPosition)
{
int size=0;
if(pref.get(groupPosition).getChildren()!=null)
size = pref.get(groupPosition).getChildren().size();
return size;
}
#Override
public Object getGroup(int groupPosition)
{
Log.i("Parent", groupPosition+"= getGroup ");
return pref.get(groupPosition);
}
#Override
public int getGroupCount()
{
return pref.size();
}
//Call when parent row clicked
#Override
public long getGroupId(int groupPosition)
{
ParentClickStatus=groupPosition;
if(ParentClickStatus==0)
ParentClickStatus=-1;
return groupPosition;
}
#Override
public void notifyDataSetChanged()
{
// Refresh List rows
super.notifyDataSetChanged();
}
#Override
public boolean isEmpty()
{
return ((pref == null) || pref.isEmpty());
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
return true;
}
/******************* Checkbox Checked Change Listener ********************/
private final class CheckUpdateListener implements OnCheckedChangeListener
{
private final Parent parent;
private CheckUpdateListener(Parent parent)
{
this.parent = parent;
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
Log.i("onCheckedChanged", "isChecked: "+isChecked);
parent.setChecked(isChecked);
((MyExpandableListAdapter)getExpandableListAdapter()).notifyDataSetChanged();
final Boolean checked = parent.isChecked();
}
}
/***********************************************************************/
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
}
}
The solution is calling notifyDataSetChanged() after the delete operation:
pref.clear();
MyDBHelper dbHelper = new MyDBHelper(this,"JobAroundU_DB", null, 1);
SQLiteDatabase db=dbHelper.getWritableDatabase();
String sqlSavedPreferences="SELECT * FROM MyPreferences";
Cursor cursor = db.rawQuery(sqlSavedPreferences, null);
while (cursor.moveToNext()){
Parent p= new Parent();
p.setPosizione(cursor.getString(1));
p.setAzienza(cursor.getString(2));
p.setId(cursor.getString(4));
Log.i("Parent ID", p.getId());
Child cp = new Child();
cp.setDescrizione(cursor.getString(3));
p.setChildren(new ArrayList<Child>());
p.getChildren().add(cp);
pref.add(p);
}
db.close();
cursor.close();
// Refresh ExpandableListView data
((MyExpandableListAdapter)getExpandableListAdapter()).notifyDataSetChanged();
Add the above code to your delete method and it should work.

How should I correct the code to get rid of these "value not used" warnings?

These are the error messages I am getting please advise.
The value of the field LocationListActivity.adapter is not used
The value of the field LocationListActivity.lv1 is not used
The value of the field LocationListActivity.titleString is not used
public class LocationListActivity extends ExpandableListActivity {
private ArrayAdapter<String> adapter = null;
private String name;
private ArrayList<List<LocationData>> locations; //Array list of all locations
private ArrayList<LocationData> locationList; // locations for each group
private ListView lv1;
private ArrayList<String> locationSection = new ArrayList<String>();
private ArrayList<String> sectionLocations = new ArrayList<String>();
private ArrayList<ArrayList<String>> allLocations = new ArrayList<ArrayList<String>>();
private String titleString;
private ExpandableListAdapter mAdapter;
private Button search;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location_list_activity);
search = (Button)findViewById(R.id.search_button);
search.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(LocationListActivity.this, LocationListSearchActivity.class));
}
});
//PARSE locations.xml
try {
this.locations = new ArrayList<List<LocationData>>();
this.locationList = new ArrayList<LocationData>();
XmlResourceParser xrp = this.getResources().getXml(R.xml.locations);
LocationData currentLocation = null;
while(xrp.getEventType() != XmlResourceParser.END_DOCUMENT) {
currentLocation = new LocationData();
if(xrp.getEventType() == XmlResourceParser.START_TAG) {
if(xrp.getName().equals("section")) {
locationSection.add(xrp.getAttributeValue(null, "title"));
}
else if(xrp.getName().equals("location")) {
currentLocation.setBuilding((xrp.getAttributeValue(null, "building")));
name = xrp.getAttributeValue(null, "name");
sectionLocations.add(name);
currentLocation.setName(name);
currentLocation.setDetailName((xrp.getAttributeValue(null, "detailName")));
currentLocation.setLat(Double.parseDouble(xrp.getAttributeValue(null, "lat")));
currentLocation.setLng(Double.parseDouble(xrp.getAttributeValue(null, "lng")));
currentLocation.setPhone(xrp.getAttributeValue(null, "phone"));
locationList.add(currentLocation);
}
}
else if(xrp.getEventType() == XmlResourceParser.END_TAG) {
if(xrp.getName().equals("section")) {
allLocations.add(new ArrayList<String>(sectionLocations));
sectionLocations.clear();
locations.add(new ArrayList<LocationData>(locationList));
locationList.clear();
}
}
xrp.next();
}
xrp.close();}
catch (XmlPullParserException xppe) {}
catch (IOException e) {}
// Set up our adapter
mAdapter = new MyExpandableListAdapter();
setListAdapter(mAdapter);
}
public class MyExpandableListAdapter extends BaseExpandableListAdapter {
public Object getChild(int groupPosition, int childPosition) {
return allLocations.get(groupPosition).get(childPosition);
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public int getChildrenCount(int groupPosition) {
return allLocations.get(groupPosition).size();
}
public TextView getGenericView() {
// Layout parameters for the ExpandableListView
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, 80);
TextView textView = new TextView(LocationListActivity.this);
textView.setLayoutParams(lp);
// Center the text vertically
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
// Set the text starting position
textView.setBackgroundResource(R.drawable.button_click);
textView.setTypeface(null, android.graphics.Typeface.BOLD);
textView.setTextColor(0xFF000000);
textView.setPadding(55, 0, 0, 0);
return textView;
}
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
TextView textView = getGenericView();
textView.setText(getChild(groupPosition, childPosition).toString());
textView.setTypeface(null, android.graphics.Typeface.NORMAL);
return textView;
}
public Object getGroup(int groupPosition) {
return locationSection.get(groupPosition);
}
public int getGroupCount() {
return locationSection.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
TextView textView = getGenericView();
textView.setText(getGroup(groupPosition).toString());
return textView;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public boolean hasStableIds() {
return true;
}
}
public boolean onChildClick (ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Intent i = new Intent( LocationListActivity.this, LocationInfoActivity.class );
i.putExtra("name", locations.get(groupPosition).get(childPosition).getName());
i.putExtra("building", locations.get(groupPosition).get(childPosition).getBuilding());
i.putExtra("detailName", locations.get(groupPosition).get(childPosition).getDetailName());
i.putExtra("lat", locations.get(groupPosition).get(childPosition).getLat());
i.putExtra("lng", locations.get(groupPosition).get(childPosition).getLng());
i.putExtra("phone", locations.get(groupPosition).get(childPosition).getPhone());
startActivity(i);
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = this.getMenuInflater();
inflater.inflate(R.menu.menu_home, menu);
return true;
}
//Called when user selects a menu item;
#Override
public boolean onOptionsItemSelected( MenuItem item ){
switch(item.getItemId()) {
case R.id.menu_search:
startActivity(new Intent(this, LocationListSearchActivity.class));
finish();
break;
case R.id.menu_about:
startActivity(new Intent(this, AboutActivity.class));
finish();
break;
}
return true;
}
}
You can use
#SuppressWarnings("unused")
Note: Similar thing happened to me. I had variables that all was used but warning still appeared. So in this case this approach is very good.
But if you have variables which you already not using nowhere, i recommend to remove them or comment them.
You could remove or comment out those variables. If you don't want to do that you can also change the warnings within Eclipse.
There have been times where I had variables that I KNOW were used and I couldn't figure out why it kept saying they were not. For some reason, certain errors in other part of the program might be making that happen. Alternately, if you are not going to use what it has highlighted, then I would just delete it.

Categories

Resources