only that checkbox are selected those are are in front of us - java

i have a button to select all check boxes but i have a issue only that check boxes are selected whose are in front of us on scrolling down other check boxes are not selected
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import com.example.callblockerapp.R;
import com.utills.DbHelper;
public class AddFromContacts extends Activity implements OnItemClickListener {
List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
ContactsAdapter ma;
ListView lv;
private Button select, btnCancelFromContacts, btnAllFromContacts;
DbHelper db = new DbHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_from_contacts);
getAllContacts(this.getContentResolver());
lv = (ListView) findViewById(R.id.ContactlistView);
ma = new ContactsAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
// adding
select = (Button) findViewById(R.id.getSelected);
btnCancelFromContacts = (Button) (findViewById(R.id.btnCancelFromContacts));
btnCancelFromContacts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
select.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// StringBuilder checkedcontacts = new StringBuilder();
String name, phoneNumber;
for (int i = 0; i < name1.size(); i++)
{
if (ma.mCheckStates.get(i) == true) {
// checkedcontacts.append(name1.get(i).toString());
// checkedcontacts.append("\n");
name = name1.get(i).toString();
phoneNumber = phno1.get(i).toString();
phoneNumber = phoneNumber.replace("-", "");
Log.e("", "Checked Name :- " + name
+ "\nChecked Phone Number :- " + phoneNumber);
db.addBlockedNumber(phoneNumber, name);
finish();
} else {
}
}
// Toast.makeText(AddFromContacts.this, checkedcontacts,
// Toast.LENGTH_LONG).show();
}
});
btnAllFromContacts = (Button) findViewById(R.id.btnAllFromContacts);
btnAllFromContacts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < lv.getChildCount(); i++) {
ViewGroup item = (ViewGroup) lv.getChildAt(i);
CheckBox checkbox = (CheckBox) item
.findViewById(R.id.checkBox);
// if (!checkbox.isChecked()) {
checkbox.setChecked(true);
btnAllFromContacts.setText("Uncheck All");
// } else if (checkbox.isChecked()) {
// checkbox.setChecked(false);
// btnAllFromContacts.setText("Select All");
// }
}
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllContacts(ContentResolver cr) {
Cursor phones = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
while (phones.moveToNext()) {
String name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class ContactsAdapter extends BaseAdapter implements
CompoundButton.OnCheckedChangeListener {
private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView name, txtNumber;
CheckBox cb;
ContactsAdapter() {
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater) AddFromContacts.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null)
vi = mInflater.inflate(R.layout.add_from_contacts_row, null);
txtNumber = (TextView) vi.findViewById(R.id.txtNumber);
name = (TextView) vi.findViewById(R.id.name);
cb = (CheckBox) vi.findViewById(R.id.checkBox);
txtNumber.setText("Name :" + name1.get(position));
name.setText("Phone No :" + phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
xml file add_from_contacts.xml
<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="match_parent"
tools:context=".MainActivity" >
<ListView
android:id="#+id/ContactlistView"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#ffbdbdbd"
android:orientation="horizontal"
android:paddingTop="2.5dip" >
<Button
android:id="#+id/btnAllFromContacts"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:gravity="center"
android:text="Select All"
android:textSize="14.0dip" />
<Button
android:id="#+id/getSelected"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:gravity="center"
android:text="Add Contact"
android:textAppearance="?android:textAppearanceMedium"
android:textSize="14.0dip" />
<Button
android:id="#+id/btnCancelFromContacts"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:gravity="center"
android:text="Cancel"
android:textSize="14.0dip" />
</LinearLayout>
</RelativeLayout>
another xml file add_from_contacts_row.xml
<?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="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/txtNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/txtNumber" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true" />
</RelativeLayout>

May I suggest an easy way to do that? Suppose I have a global variable for class AddFromContacts as,
public static boolean checked=false;
now, inside the button click (Button to select/deselect all), leave the loop you wrote as it is. Include the following.
if(checked)
checked=false;
else
checked=true;
Then inside Adapter getView(),
cb.setChecked(AddFromContacts.checked);
Eg: worked for me
public class MainActivity extends Activity {
ListView lv;
Button b1;
boolean checked=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView) findViewById(R.id.listView1);
b1=(Button) findViewById(R.id.button1);
Myadapter adapter=new Myadapter();
lv.setAdapter(adapter);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(checked)
checked=false;
else
checked=true;
for (int i = 0; i < lv.getChildCount(); i++) {
ViewGroup item = (ViewGroup) lv.getChildAt(i);
CheckBox checkbox = (CheckBox) item
.findViewById(R.id.checkBox1);
checkbox.setChecked(checked);
}
}
});
}
class Myadapter extends BaseAdapter{
CheckBox cb;
LayoutInflater mInflater;
public Myadapter() {
mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 15;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = mInflater.inflate(R.layout.item, null);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
cb.setTag(position);
cb.setChecked(checked);
return vi;
}
}
}
Also, I can see a method public void setChecked(int position, boolean isChecked). If you meant to call this, change the code to setChecked(position,mCheckStates.get(position, false));

Related

Expandable Listview OnClickListeners

I am creating an app in android studios that requires the user to select a child item from an expandable listview on one activity and for it to be displayed on another activity. I'm new to java and android studios and still dont understand how to do this really. If anyone has any sample code or can help that would be great, thanks!
You should use the setOnChildClickListener method from the ExpandableListView class to create a ClickListener for the list elements and then use a Intent to open the new activity. The call to set the listener should be set after you've set the adapter for the ListView.
Here there's a tutorial for using a ExpandableListView and it shows how to set a ClickListener for the elements.
And here there's the Android developer's documentation which shows how to create and open a new Activity from a button's click.
**You should use the setOnChildClickListener method from the ExpandableListView class to create a ClickListener for the list elements and then use a Intent to open the new activity. The call to set the listener should be set after you've set the adapter for the ListView and create the xml file for child and parent.child will be Expandable TextView **
**layout file**
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.elite_android.explistview1.MainActivity">
<RelativeLayout
android:id="#+id/main_number_picker_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="17dp">
<NumberPicker
android:id="#+id/main_number_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Next" />
<TextView
android:id="#+id/main_txt_patient_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="#id/main_number_picker"
android:text="Select number of patient"
android:textColor="#color/colorAccent"
android:layout_marginLeft="80dp"/>
</RelativeLayout>
<ExpandableListView
android:id="#+id/exp_Listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/main_number_picker_layout">
</ExpandableListView>
</RelativeLayout>
**Main Activity.java file**
package com.example.elite_android.explistview1;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.view.View.OnFocusChangeListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.NumberPicker;
public class MainActivity extends AppCompatActivity {
ExpandableListView expandableListView;
private MyAdapter mAdapter;
ExpandableListView expand;
NumberPicker numberPicker;
private List<String> headerItems;
private ArrayList childDetails;
private HashMap<String, List<String>> childList;
private Context ctx;
EditText editText1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the EditText
editText1 = (EditText) findViewById(R.id.child_item);
// //set the onFocusChange listener
// // editText1.setOnFocusChangeListener(editText1.getOnFocusChangeListener());
//
//// //get reference to EditText
//// editText2 = (EditText) findViewById(R.id.sequence);
//// // set the on focusChange listner
//// editText2.setOnFocusChangeListener(editText2.getOnFocusChangeListener());
//
// //Generate list View from ArrayList;
//
//
// EditText editText = (EditText) findViewById(R.id.child_item);
// editText.requestFocus();
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
//
//
//// editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
// // #Override
// // public void onFocusChange(View v, boolean hasFocus) {
// // //editText.setOnFocusChangeListener();
// // return;
// // }
// //});
//
String[] numbers = new String[10];
for (int count = 0; count < 10; count++)
numbers[count] = String.valueOf(count);
numberPicker = (NumberPicker) findViewById(R.id.main_number_picker);
numberPicker.setMaxValue(numbers.length);
numberPicker.setMinValue(1);
numberPicker.setDisplayedValues(numbers);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
generateListItems(newVal);
loadRecycleView();
}
});
}
private void generateListItems(int childCount) {
if (headerItems != null)
headerItems.clear();
else
headerItems = new ArrayList<>();
if (childList != null)
childList.clear();
else
childList = new HashMap();
if (childDetails == null) {
childDetails = new ArrayList();
childDetails.add("Name");
childDetails.add("Age");
childDetails.add("Gender");
}
// Put header items
for (int count = 0; count < childCount; count++) {
headerItems.add(" Parent " + count);
childList.put(headerItems.get(count), childDetails);
}
}
private void loadRecycleView() {
if (expandableListView == null) {
expandableListView = (ExpandableListView) findViewById(R.id.exp_Listview);
mAdapter = new MyAdapter(this, headerItems, childList);
expandableListView.setAdapter(mAdapter);
} else {
expandableListView.invalidate();
mAdapter.setHeaderData(headerItems);
mAdapter.setListData(childList);
mAdapter.notifyDataSetChanged();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
}
**Adapter class.java**
package com.example.elite_android.explistview1;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.view.View.OnFocusChangeListener;
/**
* Created by ELITE-ANDROID on 28-02-2017.
*/
// this is provides all needs methods implementing an Expandable List VIew
public class MyAdapter extends BaseExpandableListAdapter {
// We need some Variables here so therer are some Variables here
private List<String> header_titles; // This is for Representing the HeadLine(Array list)
private HashMap<String, List<String>> child_titles; // defin the HashMap for the child item how to Represent the Parent Handing so Hash Map, need some Variables
private Context ctx;
private NumberPicker numberPicker;
EditText editText;
View view;
private static LayoutInflater inflater = null;
//for initalized for all Variables we need some Constructor
public MyAdapter(Context context, List<String> header_titles, HashMap<String, List<String>> child_titles) {
super();
this.ctx = context;
this.child_titles = child_titles;
this.header_titles = header_titles;
}
public void refreshHeader_titles(List<String> events) {
this.header_titles.clear();
this.header_titles.addAll(header_titles);
notifyDataSetChanged();
}
;
#Override
// From this Override method How to Return how many elements are the Group count like parent
public int getGroupCount() {
return header_titles.size();
}
#Override
//here the number of child items are in each heading. There are three Heading - PAtien Name ,Age, Gender
public int getChildrenCount(int groupPosition) {
// Log.d("xxx", )
return child_titles.get(header_titles.get(groupPosition)).size(); //how to Return the size of HashMap
}
#Override
public Object getGroup(int groupPosition) {
return header_titles.get(groupPosition);
}
#Override
// here how to retuen child items on the particular headings and Positions.
public Object getChild(int groupPosition, int childPosition) {
return child_titles.get(header_titles.get(groupPosition)).get(childPosition);
}
#Override
//return the groupo position
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
// Here return the Group View
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
// ListViewHolder viewHolder;
// if (view == null) {
// viewHolder = new ListViewHolder();
// LayoutInflater inflater = context.getLayoutInflater();
// view = inflater.inflate(R.layout.listitems, null, true);
// viewHolder.itmName = (TextView) view.findViewById(R.id.Item_name);
// viewHolder.itmPrice = (EditText) view.findViewById(R.id.Item_price);
// view.setTag(viewHolder);
// } else {
// viewHolder = (ListViewHolder) view.getTag();
//// loadSavedValues();
// }
// Here how to get the Heading Title here Decalered String Variables, now how to get title of heading from getGroup methods so simple call Backed Methods.
String title = (String) this.getGroup(groupPosition);
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.prent, null);
}
TextView textView = (TextView) convertView.findViewById(R.id.heading_item);
textView.setText(title); // for Heading bold style ,title
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
String title = (String) this.getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child, null);
}
String cellData = child_titles.get(header_titles.get(groupPosition)).get(childPosition);
EditText childItem = (EditText) convertView.findViewById(R.id.child_item);
childItem.setHint(cellData);
childItem.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// Log.d("xxxx", "Has focus " + hasFocus);
if (!hasFocus) {
// int itemIndex = View.getId();
// String enteredName = ((EditText)v).getText().toString();
// selttems.put(itemIndex, enteredName);
} else {
}
return;
}
});
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void setListData(HashMap<String, List<String>> lData) {
child_titles = lData;
}
public void setHeaderData(List<String> hData) {
header_titles = hData;
}
}
**child.Xml file**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#ffff">
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/child_item"
android:textSize="25dp"
android:textStyle="bold"
android:gravity="center_vertical"
android:layout_marginLeft="10dp"/>
<!--<EditText-->
<!--android:id="#+id/sequence"-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_alignParentLeft="true"-->
<!--android:layout_alignParentTop="true"-->
<!--android:paddingLeft="35sp"-->
<!--android:layout_marginRight="10dp"-->
<!--android:textAppearance="?android:attr/textAppearanceMedium" />-->
</LinearLayout>
<!--This Layout File Represent the Child Items.
This Field Represent the Child Item IN the List VIew -->
**parent.Xml**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="vertical">
<TextView
android:id="#+id/heading_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:gravity="center_vertical"
android:textColor="#color/colorAccent"
android:textSize="25dp" />
</LinearLayout>
<!--This Layout file for Heading -Lines.-->

Popup window not showing up with spinner item selection?

On Clicking the spinner item need to show the popup window but its not showing up, only i can see the toast notification.
Log: system.err
java.lang.IllegalStateException: System services not available to Activities before onCreate()
My Code Below
MainActivity.java
package com.example.newapplication;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Spinner;
import com.example.newapplication.service;
public class MainActivity extends Activity {
Button btnClosePopup;
//Button OpenPopup;
ArrayList array;
service ser = new service(array);
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner1);
/*OpenPopup = (Button) findViewById(R.id.button1);
OpenPopup.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
initiatepopupwindow();
}
});
*/
array = ser.getArrayList();
Log.d("TAG","" +array);
//for(int i=0;i<array.length();i++){
//}
ArrayAdapter<String> dataadapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, array);
dataadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataadapter);
addListenerOnSpinnerItemSelected();
}
private PopupWindow pwindo;
private void addListenerOnSpinnerItemSelected() {
// TODO Auto-generated method stub
spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void initiatepopupwindow() {
// TODO Auto-generated method stub
try{
Log.d("TAG", "" +"Inside popupwindow");
LayoutInflater inflater = (LayoutInflater) MainActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.screen_popup,
(ViewGroup) findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 300, 370, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup);
btnClosePopup.setOnClickListener(cancel_button_click_listener);
}
catch (Exception e) {
e.printStackTrace();
}
}
private OnClickListener cancel_button_click_listener = new OnClickListener() {
public void onClick(View v) {
pwindo.dismiss();
}
};
}
Listener for spinner event.
CustomOnItemSelectedListener.java
package com.example.newapplication;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import com.example.newapplication.MainActivity;
public class CustomOnItemSelectedListener implements OnItemSelectedListener{
MainActivity main = new MainActivity();
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
// TODO Auto-generated method stub
main.initiatepopupwindow();
Toast.makeText(parent.getContext(), parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
screenpopup.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/popup_element"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#444444"
android:orientation="vertical"
android:padding="10sp" >
<TextView
android:id="#+id/txtView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5sp"
android:text="Hello!" />
<Button
android:id="#+id/btn_close_popup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Close" />
</LinearLayout>
activity_main layout
<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="match_parent"
android:background="#drawable/lightbackground"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="23dp"
android:layout_marginTop="32dp"
android:text="Welcome to MyApp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="21dp" />
</RelativeLayout>
remove your CustomOnItemSelectedListener.java class
and then use this code
public class MainActivity extends Activity {
Button btnClosePopup;
// Button OpenPopup;
ArrayList array;
service ser = new service(array);
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner1);
/*
* OpenPopup = (Button) findViewById(R.id.button1);
* OpenPopup.setOnClickListener(new OnClickListener(){
*
* #Override public void onClick(View v) { // TODO Auto-generated method
* stub initiatepopupwindow(); }
*
* });
*/
array = ser.getArrayList();
Log.d("TAG", "" + array);
// for(int i=0;i<array.length();i++){
// }
ArrayAdapter<String> dataadapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, array);
dataadapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataadapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
initiatepopupwindow();
Toast.makeText(getApplicationContext(), array.get(arg2) + "",
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
private PopupWindow pwindo;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void initiatepopupwindow() {
// TODO Auto-generated method stub
try {
Log.d("TAG", "" + "Inside popupwindow");
LayoutInflater inflater = (LayoutInflater) MainActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.screenpopup,
(ViewGroup) findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 300, 370, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup);
btnClosePopup.setOnClickListener(cancel_button_click_listener);
} catch (Exception e) {
e.printStackTrace();
}
}
private OnClickListener cancel_button_click_listener = new OnClickListener() {
public void onClick(View v) {
pwindo.dismiss();
}
};
}
In place of layout pass spinner object of your view:
replace
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
with
pwindo.showAtLocation(spinner, Gravity.CENTER, 0, 0);
And to open popup window just below your spinner use below code
pwindo.showAsDropDown(spinner, 0, 0);
Update your CustomOnItemSelectedListener class as:
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
Context mCtx;
public CustomOnItemSelectedListener(Context ctx) {
this.mCtx = ctx;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
// TODO Auto-generated method stub
((MainActivity) mCtx).initiatepopupwindow();
Toast.makeText(parent.getContext(),
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG)
.show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}

ListView Items aren't displaying on Main Activity

I'm a beginner in android development. I'm trying to send data from an ArrayList of Type Workout Item to the MainActivity using an Adapter, but I don't understand base adapters very well. Here is my code:
WorkoutActivity.java:
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;
public class WorkoutActivity extends Activity {
WorkoutItemAdapter workoutItemAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_workout);
}
public class WorkoutItemAdapter extends BaseAdapter{
int rowCount = 1;
List<WorkoutItem> workoutsList = getDataForListView();
public WorkoutItem getWorkout(int position)
{
return workoutsList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) WorkoutActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.workout_item, parent, false);
}
TextView workoutNum = (TextView) convertView.findViewById(R.id.workout_col);
TextView workoutTime = (TextView) convertView.findViewById(R.id.time_col);
WorkoutItem workout = workoutsList.get(position);
workoutNum.setText(workout.workoutNum);
workoutTime.setText(workout.time);
return convertView;
}
#Override
public int getCount() {
return workoutsList.size();
// TODO Auto-generated method stub
}
#Override
public WorkoutItem getItem(int position) {
// TODO Auto-generated method stub
return workoutsList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public void addRow() {
rowCount++;
notifyDataSetChanged();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.workout, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
public List<WorkoutItem> getDataForListView()
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String workoutTime = prefs.getString("Workout Time", "");
List<WorkoutItem> workoutsList = new ArrayList<WorkoutItem>();
for(int i = 0; i < (workoutsList.size() + 1); i++)
{
WorkoutItem workout = new WorkoutItem();
workout.workoutNum = "Workout " + (i+1);
workout.time = workoutTime;
workoutsList.add(workout);
}
return workoutsList;
}
public void startAndStopTimer(View view)
{
long totalTime = 0;
Button startAndStop = (Button) findViewById(R.id.button1);
Chronometer c = (Chronometer) findViewById(R.id.chronometer1);
if(startAndStop.getText().equals("Start"))
{
c.setBase(SystemClock.elapsedRealtime() + totalTime);
c.start();
startAndStop.setText("Pause");
}
else
{
totalTime = c.getBase() - SystemClock.elapsedRealtime();
c.stop();
startAndStop.setText("Start");
}
}
public void save(View view)
{
// create broadcast receiver saying ...saved.
// Add ArrayList value to arrayList
Chronometer timer = (Chronometer) findViewById(R.id.chronometer1);
SharedPreferences timerSettings = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = timerSettings.edit();
editor.putString("Workout Time", timer.getText().toString());
editor.commit();
// go back to main activity.
Intent intent = new Intent(WorkoutActivity.this, OverviewActivity.class);
startActivity(intent);
finish();
}
public void cancel(View view)
{
// go back to main activity
Intent intent = new Intent(WorkoutActivity.this, OverviewActivity.class);
startActivity(intent);
finish();
}
}
OverviewActivity.java:
import edu.uark.csce.razorrunner.WorkoutActivity.WorkoutItemAdapter;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
public class OverviewActivity extends Activity{
WorkoutItemAdapter workoutAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_overview);
LoadPreferences();
LoadListView();
}
private void LoadListView() {
// TODO Auto-generated method stub
ListView workoutList = (ListView) findViewById(R.id.workout_list);
workoutList.setAdapter(workoutAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.overview, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void LoadPreferences()
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String Name = sharedPreferences.getString("Name", "");
TextView textView = (TextView) findViewById(R.id.textView2);
textView.setText(Name);
}
public void openWorkoutActivity(View view)
{
Intent intent = new Intent(OverviewActivity.this, WorkoutActivity.class);
startActivity(intent);
finish();
}
public void openProfileActivity(View view)
{
Intent intent = new Intent(OverviewActivity.this, ProfileActivity.class);
startActivity(intent);
finish();
}
public void openHistoryActivity(View view)
{
Intent intent = new Intent(OverviewActivity.this, HistoryActivity.class);
startActivity(intent);
finish();
}
}
activity_overview.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="edu.uark.csce.razorrunner.OverviewActivity" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/profileButton"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:onClick="openProfileActivity"
android:text="Profile" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
<ListView
android:id="#+id/workout_list"
android:layout_width="wrap_content"
android:layout_height="195dp"
android:layout_weight="0.19" >
</ListView>
<Button
android:id="#+id/startNewWorkout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:onClick="openWorkoutActivity"
android:text="Start New Workout!"
android:typeface="sans" />
</LinearLayout>
activity_workout.xml:
<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="match_parent"
android:gravity="center"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="edu.uark.csce.razorrunner.WorkoutActivity" >
<Button
android:id="#+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button2"
android:layout_alignBottom="#+id/button2"
android:layout_alignRight="#+id/button1"
android:text="Cancel"
android:onClick="cancel" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/Button01"
android:text="Save"
android:onClick="save" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Button01"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_marginRight="22dp"
android:text="Start"
android:onClick="startAndStopTimer" />
<TextView
android:id="#+id/time_col"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_alignParentTop="true"
android:text="New Workout"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/time_col"
android:layout_marginTop="18dp"
android:text="Calories Burned"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/textView2"
android:layout_marginTop="14dp"
android:text="Duration"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/TextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView2"
android:layout_alignBottom="#+id/textView2"
android:layout_alignRight="#+id/button1"
android:layout_toRightOf="#+id/button2"
android:ems="10"
android:text="0"
android:textAppearance="?android:attr/textAppearanceLarge">
<requestFocus />
</TextView>
<Chronometer
android:id="#+id/chronometer1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/TextView01"
android:layout_alignLeft="#+id/TextView1"
android:layout_alignRight="#+id/TextView1"
android:text="Chronometer" />
</RelativeLayout>
I'd like to show the workout number and duration for each list item every time I click Save, but currently all I get is a blank ListView every time I click Save. Any help and/or additional sources on this topic would be useful.
I hope two mistakes you made.
public List<WorkoutItem> getDataForListView()
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String workoutTime = prefs.getString("Workout Time", "");
List<WorkoutItem> workoutsList = new ArrayList<WorkoutItem>();
for(int i = 0; i < (workoutsList.size() + 1); i++)
{
WorkoutItem workout = new WorkoutItem();
workout.workoutNum = "Workout " + (i+1);
workout.time = workoutTime;
workoutsList.add(workout);
}
return workoutsList;
}
I guess you are trying to add data to list view. Since you are creating new List using
List<WorkoutItem> workoutsList = new ArrayList<WorkoutItem>();
workoutsList.size() will return zero. your loop iterates till list size+1. (only one time )
then you need to pass the List from WorkoutActivity to OverviewActivity.
change WorkoutActivity insert following code
public class WorkoutActivity extends Activity {
WorkoutItemAdapter workoutItemAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_workout);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.workout, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
public List<WorkoutItem> getDataForListView() {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
String workoutTime = prefs.getString("Workout Time", "");
List<WorkoutItem> workoutsList = new ArrayList<WorkoutItem>();
for (int i = 0; i < (10+ 1); i++) {
WorkoutItem workout = new WorkoutItem();
workout.workoutNum = "Workout " + (i + 1);
workout.time = workoutTime;
workoutsList.add(workout);
}
return workoutsList;
}
public void startAndStopTimer(View view) {
long totalTime = 0;
Button startAndStop = (Button) findViewById(R.id.button1);
Chronometer c = (Chronometer) findViewById(R.id.chronometer1);
if (startAndStop.getText().equals("Start")) {
c.setBase(SystemClock.elapsedRealtime() + totalTime);
c.start();
startAndStop.setText("Pause");
} else {
totalTime = c.getBase() - SystemClock.elapsedRealtime();
c.stop();
startAndStop.setText("Start");
}
}
public void save(View view) {
// create broadcast receiver saying ...saved.
// Add ArrayList value to arrayList
Chronometer timer = (Chronometer) findViewById(R.id.chronometer1);
SharedPreferences timerSettings = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = timerSettings.edit();
editor.putString("Workout Time", timer.getText().toString());
editor.commit();
// go back to main activity.
Intent intent = new Intent(WorkoutActivity.this, OverviewActivity.class);
intent.putStringArrayListExtra("stock_list", getDataForListView());
startActivity(intent);
finish();
}
public void cancel(View view) {
// go back to main activity
Intent intent = new Intent(WorkoutActivity.this, OverviewActivity.class);
intent.putStringArrayListExtra("stock_list", getDataForListView());
startActivity(intent);
finish();
}
}
and OverviewActivity to this
public class OverviewActivity extends Activity{
List<WorkoutItem> workList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_overview);
Intent i = getIntent();
workList = i.getStringArrayListExtra("stock_list");
LoadPreferences();
LoadListView();
}
private void LoadListView() {
// TODO Auto-generated method stub
ListView workoutList = (ListView) findViewById(R.id.workout_list);
WorkoutItemAdapter workoutAdapter= new WorkoutItemAdapter(workList);
workoutList.setAdapter(workoutAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.overview, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void LoadPreferences()
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String Name = sharedPreferences.getString("Name", "");
TextView textView = (TextView) findViewById(R.id.textView2);
textView.setText(Name);
}
public void openWorkoutActivity(View view)
{
Intent intent = new Intent(OverviewActivity.this, WorkoutActivity.class);
startActivity(intent);
finish();
}
public void openProfileActivity(View view)
{
Intent intent = new Intent(OverviewActivity.this, ProfileActivity.class);
startActivity(intent);
finish();
}
public void openHistoryActivity(View view)
{
Intent intent = new Intent(OverviewActivity.this, HistoryActivity.class);
startActivity(intent);
finish();
}
public class WorkoutItemAdapter extends BaseAdapter{
int rowCount = 1;
List<WorkoutItem> workoutsList ;
public WorkoutItemAdapter( List<WorkoutItem> list) {
workoutsList=list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) WorkoutActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.workout_item, parent, false);
}
TextView workoutNum = (TextView) convertView.findViewById(R.id.workout_col);
TextView workoutTime = (TextView) convertView.findViewById(R.id.time_col);
WorkoutItem workout = workoutsList.get(position);
workoutNum.setText(workout.workoutNum);
workoutTime.setText(workout.time);
return convertView;
}
#Override
public int getCount() {
return workoutsList.size();
// TODO Auto-generated method stub
}
#Override
public WorkoutItem getItem(int position) {
// TODO Auto-generated method stub
return workoutsList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public void addRow() {
rowCount++;
notifyDataSetChanged();
}
}
}
try these code. I have not yet tried, hope will works fine.
So I assume OverviewActivity.java is your main Activity which in return opens WorkoutActivity ?
you haven't initialise workoutAdapter...only declared....
hence workoutAdapter is null....which means the size of adapter is 0 ...which means no rows for list view...
before setting the adapter to listview ..you must have to initialize workoutAdapter
i.e.
workoutAdapter=new WorkoutItemAdapter(getDataForListView());
create the adaper contructor and pass the list array
public class WorkoutItemAdapter extends BaseAdapter{
int rowCount = 1; //don't know about that
List<WorkoutItem> workoutsList;
public WorkoutItemAdapter(List<WorkoutItem> tmp)
{
this.workoutsList=tmp; //setting the list array to datamember of this adapter
}
In WorkOutItemAdapter List<WorkoutItem> workoutsList = getDataForListView();
// check the size of the list is zero or null
In WorkOutItemActivity you do like this
WorkoutItemAdapter workoutItemAdapter = new WorkoutItemAdapter();
ListView workoutList = (ListView) findViewById(R.id.workout_list);
workoutList.setAdapter(workoutAdapter);*

Uri argument and LoaderCallbacks

I have four class :
MainActivity.java - MyAdapter.java - MyDataBase.java - MyListActivity.java
now, what is Uri in the MyListActiviy ? How can I fill it ?
when I Click "showlist_btn" button in MainActivity, a list without content is displayed ! why ?
MainActivity:
package com.example.ex22;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText edittext ;
Button add_btn ;
Button showlist_btn ;
MyDataBase mydatabase ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydatabase = new MyDataBase(MainActivity.this);
edittext = (EditText)findViewById(R.id.edittext);
showlist_btn = (Button)findViewById(R.id.showlist_btn);
add_btn = (Button)findViewById(R.id.add_btn);
add_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String str = edittext.getText().toString();
mydatabase.addName(str);
edittext.setText("");
}
});
showlist_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, MyListActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
MyAdapter:
package com.example.ex22;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class MyAdapter extends BaseAdapter {
List<String> mylist ;
LayoutInflater inflater ;
public MyAdapter(Context context){
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mylist.size();
}
void getList(List<String> list){
mylist = list ;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder viewholder ;
if(convertView == null){
convertView = inflater.inflate(R.layout.row_for_list, null);
viewholder = new ViewHolder();
viewholder.text = (TextView)convertView.findViewById(R.id.textview_forrow);
convertView.setTag(viewholder);
}else {
viewholder = (ViewHolder)convertView.getTag();
}
viewholder.text.setText(mylist.get(position));
return convertView;
}
static class ViewHolder{
TextView text ;
}
}
MyDataBase:
package com.example.ex22;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyDataBase extends SQLiteOpenHelper {
private final static String DB_NAME = "mydb" ;
private final static String TABLE_NAME = "mytable" ;
//private static final String NAME = "name" ;
private final static String NAME_COLOUM = "_name" ;
private static final String CREATE_TABLE = "CREATE TABLE "+ TABLE_NAME + "("
+ NAME_COLOUM + " TEXT" + ")";
public MyDataBase(Context context){
super(context,DB_NAME,null,1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
public void addName(String str){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NAME_COLOUM, str);
db.insert(TABLE_NAME, null, values);
db.close();
}
public List<String> getAllNames(){
List<String> list = new ArrayList<String>() ;
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM "+ TABLE_NAME, null);
if(c.moveToFirst()){
do{String str = c.getString(0);
list.add(str);
}while(c.moveToNext());
}
return list ;
}
public String getCulomName(){
return this.NAME_COLOUM;
}
}
MyListActivity:
package com.example.ex22;
import android.app.ListActivity;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.SimpleCursorAdapter;
public class MyListActivity extends ListActivity
implements LoaderCallbacks<Cursor>{
SimpleCursorAdapter simplecursorradapter ;
MyDataBase mydb ;
CursorLoader cursorloader ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//setContentView(R.layout.show_list);
mydb = new MyDataBase(this);
String[] from = new String[] { mydb.getCulomName() };
int[] to = new int[]{
R.id.forlist
};
simplecursorradapter = new SimpleCursorAdapter(this, android.R.layout.simple_expandable_list_item_2, null,
from , to ,0);
setListAdapter(simplecursorradapter);
LoaderManager loadermanager = getLoaderManager();
loadermanager.initLoader(0, null, this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// TODO Auto-generated method stub
String[] projection = {mydb.getCulomName()};
final String SCHEME = "content";
// The provider's authority
final String AUTHORITY = "com.example.ex22";
final Uri src = Uri.parse(SCHEME + "://" + AUTHORITY);
Uri uri = Uri.withAppendedPath(src, "mytable");
cursorloader = new CursorLoader(this, uri, projection, null, null, null);
return cursorloader;
}
#Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
// TODO Auto-generated method stub
simplecursorradapter.swapCursor(arg1);
}
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
// TODO Auto-generated method stub
simplecursorradapter.swapCursor(null);
}
}
activity_main :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<EditText
android:id="#+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Write Your Name..."
/>
<Button
android:id="#+id/add_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Add Name"
/>
<Button
android:id="#+id/showlist_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Show Name List"
/>
</LinearLayout>
forlist:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/forlist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
row_for_list:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textview_forrow"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textSize="40sp"
/>
</LinearLayout>
show_list:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>

Populating a ListView with Objects from Parse.com Android

I'm trying to fill a ListView with objects from my database at Parse.com, but I'm am having trouble because the ListView does not accept objects directly. I've tried making an array of strings by looping through my objects and casting them as strings but that failed. I have also tried to call a .toString on the objects but no luck either.
My plan is to loop through all of the parse objects and then add them to the ListView. That ListView will then be used to allow the user to search through all of the objects from Parse.com. The objects from Parse.com should replace the listview_array[] data....ex replace "BudWeiser", "Dubra" etc....
The loop I did create to retrieve the Objects names, prices, size did work, but I could not place it into the listView since I believe it was an object.
Here's my code
package com.alpha.dealtap;
import java.lang.reflect.Array;
import java.util.List;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
public class Search_Page extends Activity {
private ListView lv;
private EditText et;
public String listview_array[] = { "BudWeiser", "Dubra", "Corona",
"Jack Daniels", "Smirnoff", "Keystone Light", "Natural Ice" };
private ArrayList<String> array_sort = new ArrayList<String>();
public ArrayList<Object> _arrayList = new ArrayList<Object>();
int textlength = 0;
ParseObject dealsObject;
int n = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_page);
Parse.initialize(this, "vUz23Z6zdIL1jbxbVWeLpsSdu1ClTu3YiG30zTWY",
"4BTyoq1QQKows8qVJV7lvU3ZokSRrLFyOCPzffwJ");
// Using this Parsequery...I can grab/locate the objects from the Parse
// list...Here I grabbed the objects that have Burnettes and the price
// of it
// Eventually I may need to set a limit on how many results I will get
// from the for loop....So far I think it is limited to 100 by default
ParseQuery query = new ParseQuery("Deals");
// query.whereEqualTo("Brand", "Burnettes");
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
Log.d("Brand", "Retrieved " + objects.size() + " Brands");
for (ParseObject dealsObject : objects) {
// use dealsObject.get('columnName') to access the
// properties of the Deals object
Object brands = dealsObject.get("Brand").toString();
_arrayList.add(brands);
listview_array = _arrayList;
//Having trouble putting strings into an array list....Have to cast as ArrayList and then it causes error!
Log.d("Size", (String) dealsObject.get("Size"));
Log.d("Price", (String) dealsObject.get("Price"));
Log.d("Brand", (String) dealsObject.get("Brand"));
n++;
}
} else {
Log.d("Brand", "Error: " + e.getMessage());
}
}
});
Button store = (Button) findViewById(R.id.b1);
Button deal = (Button) findViewById(R.id.b2);
lv = (ListView) findViewById(R.id.ListView01);
et = (EditText) findViewById(R.id.search_box);
lv.setAdapter(new ArrayAdapter<Object>(this,
android.R.layout.simple_list_item_1, listview_array));
et.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// Abstract Method of TextWatcher Interface.
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// Abstract Method of TextWatcher Interface.
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
textlength = et.getText().length();
array_sort.clear();
for (int i = 0; i < listview_array.length; i++) {
if (textlength <= listview_array[i].length()) {
if (et.getText()
.toString()
.equalsIgnoreCase(
(String) listview_array[i].subSequence(
0, textlength))) {
array_sort.add(listview_array[i]);
}
}
}
lv.setAdapter(new ArrayAdapter<String>(Search_Page.this,
android.R.layout.simple_list_item_1, array_sort));
}
});
store.setOnClickListener(new View.OnClickListener() {
// When you use OnClickListener...you need the onClick method inside
// of it
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent("com.alpha.dealtap.STOREPAGE"));
}
});
deal.setOnClickListener(new View.OnClickListener() {
// When you use OnClickListener...you need the onClick method inside
// of it
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent("com.alpha.dealtap.DEALPAGE"));
}
});
}
protected void onListItemClick(ListView l, View v, int position, long id) {
// Cheese equals the position for which item that is clicked...so it
// depends on which item that is clicked
String cheese = "TAPDEAL";
try {
Class ourClass = Class.forName("com.alpha.dealtap." + cheese);
Intent ourIntent = new Intent(Search_Page.this, ourClass);
startActivity(ourIntent);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
}
you can use BaseAdapter class for custom listview. here is the code for that.
List<ParseObject> parse = new ArrayList<ParseObject>();
public class CustomChannelListAdapter extends BaseAdapter {
private Context context;
public CustomChannelListAdapter(Context context) {
super();
this.context = context;
}
#Override
public int getCount() {
if (parse != null) {
return parse.size();
}
return 0;
}
#Override
public Channel getItem(int position) {
// TODO Auto-generated method stub
return parse.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
TextView tittle = null;
TextView desc = null;
TextView nowPlaying = null;
if (view == null) {
LayoutInflater inflater = ((Activity) context)
.getLayoutInflater();
view = inflater.inflate(R.layout.video_listrow, parent, false);
} else {
view = convertView;
}
tittle = (TextView) view.findViewById(R.id.title);
desc = (TextView) view.findViewById(R.id.Descp);
nowPlaying = (TextView) view.findViewById(R.id.NowplayingId);
if (parse!= null) {
if (parse.get(position).getName() != null) {
tittle.setText(parse.get(position).getName()
.toString());
} else {
tittle.setText("----------------------");
}
if (parse.get(position).getDesc() != null) {
desc.setText(parse.get(position).getDesc()
.toString());
} else {
desc.setText("------------------------");
}
}
return view;
}
}
video_listrow.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="400dp"
android:layout_height="75dp"
android:background="#drawable/videolist_selector"
android:orientation="horizontal"
android:paddingLeft="5dp"
android:paddingRight="5dp" >
<!-- Title Of Song -->
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:textColor="#color/orange"
android:textSize="18dip"
android:textStyle="bold"
android:typeface="sans"
android:ellipsize="marquee"
android:freezesText="true"
android:marqueeRepeatLimit="marquee_forever"
android:paddingLeft="5dip"
android:scrollHorizontally="true"
android:singleLine="true"
android:text="Tittle Not Found " />
<!-- Artist Name -->
<TextView
android:id="#+id/Descp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_marginTop="1dip"
android:layout_toRightOf="#+id/thumbnail"
android:paddingTop="5dp"
android:textColor="#color/white"
android:textSize="12dip"
android:textStyle="bold"
android:typeface="sans"
android:ellipsize="marquee"
android:freezesText="true"
android:marqueeRepeatLimit="marquee_forever"
android:paddingLeft="5dip"
android:scrollHorizontally="true"
android:singleLine="true"
android:text="Description Not Found"
/>
<!-- Rightend Duration -->
<!--
<TextView
android:id="#+id/duration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#id/title"
android:gravity="right"
android:text="5:45"
android:layout_marginRight="5dip"
android:textSize="10dip"
android:textColor="#10bcc9"
android:textStyle="bold"/>
-->
<!-- Rightend Arrow -->
<!--
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/arrow"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
-->
<TextView
android:id="#+id/NowplayingId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="5dp"
android:layout_marginRight="4dp"
android:text="Now playing..."
android:textColor="#color/red"
android:textSize="12dp" />
</RelativeLayout>
In your activity code
ListView videoList = (ListView) findviewByid(_);
CustomChannelListAdapter channelAdapter = new CustomChannelListAdapter(PlasmaView.this);
videoList.setAdapter(channelAdapter);

Categories

Resources