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
}
}
Related
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);*
I have created an android app that features an add button, a subtract button, and a counter variable.
However, as soon as the app opens on my device (Samsung Galaxy S3), I receive an error message stating that the app has stopped working.
Below is my MainActivity.java file.
package com.example.first;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
int counter;
Button add, sub;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
add = (Button) findViewById(R.id.btnAdd);
sub = (Button) findViewById(R.id.btnSub);
display = (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter += 1;
display.setText("The total is " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter -= 1;
display.setText("The total is " + counter);
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
The fragment_main.xml file is below:
<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: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.first.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/tvDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvDisplay"
android:layout_centerHorizontal="true"
android:layout_marginTop="54dp"
android:text="#string/add_button" />
<Button
android:id="#+id/btnSub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/btnAdd"
android:layout_below="#+id/btnAdd"
android:layout_marginTop="40dp"
android:text="#string/sub_button" />
Are there any ideas as to why the app stops working immediately after it starts running?
Thank you.
I imagine that you're getting a NullPointerException around Line 31. The reason you're getting a NullPointerException is because you're trying to find Views in your ActionBarActivity that are being inflated into your PlaceholderFragment. Change your code as follows:
// import statements omitted
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()).commit();
}
}
// onCreateOptionsMenu() and onOptionsItemSelected()
// method remain the same.
public static class PlaceholderFragment extends Fragment {
int counter = 0;
Button add, sub;
TextView display;
public PlaceholderFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
add = (Button) rootView.findViewById(R.id.btnAdd);
sub = (Button) rootView.findViewById(R.id.btnSub);
display = (TextView) rootView.findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter += 1;
display.setText("The total is " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter -= 1;
display.setText("The total is " + counter);
}
});
return rootView;
}
}
}
Remove counter = 0; and Just Do this:
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
tv1.setText("The total is : " + String.valueOf(counter));
}
});
sub.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
tv1.setText("The total is : " + String.valueOf(counter));
}
});
Hope this helps..
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"
/>
I have a list menu that links to another list menu and into an activity called counter. But the counter keeps throwing an exception and not show me the actual counter activity
here's the code below
package com.example.taekwondobuddy.util;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Tools extends ListActivity{
String classes[] = {"Counter","Accelermeter","Timer"} ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Tools.this, android.R.layout.simple_list_item_1, classes));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String cheese = classes[position];
try{
Class ourclass = Class.forName("com.example.taekwondobuddy.util" + cheese);
Intent ourIntent = new Intent(Tools.this, ourclass);
startActivity(ourIntent);
} catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
the tool class
package com.example.taekwondobuddy.util;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Tools extends ListActivity{
String classes[] = {"Counter","Accelermeter","Timer"} ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Tools.this, android.R.layout.simple_list_item_1, classes));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String cheese = classes[position];
try{
Class ourclass = Class.forName("com.example.taekwondobuddy.util" + cheese);
Intent ourIntent = new Intent(Tools.this, ourclass);
startActivity(ourIntent);
} catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
the counter class
package com.example.taekwondobuddy.util;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Counter extends Activity {
int counter;
Button add;
Button sub;
TextView display;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.counter);
counter = 0;
add = (Button) findViewById(R.id.button1);
sub = (Button) findViewById(R.id.button2);
display = (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Counter: " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
display.setText("Counter: " + counter);
}
});
}
}
and the counter.xml if that helps anyone
<?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" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Counter: 0"
android:textSize="45dp"
android:layout_gravity="center"
android:id="#+id/tvDisplay"
></TextView>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="150dp"
android:text="Add" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:text="Subtract" />
</RelativeLayout>
I can't see what can be wrong any ideas?
Class ourclass = Class.forName("com.example.taekwondobuddy.util" + cheese); in this line append "." before cheese
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));