ListView Items aren't displaying on Main Activity - java

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);*

Related

database id's are interchanged android sqlite

Good Day everyone. I have this code and i face problem in deleting. For example, my list of names are Junko, Gemina and Fukar. If i view each, they show same details. Now, if I delete any of them, ex. I delete Fukar, it will be deleted successfully but when I click on Gemina, the detail that appears is of Junko. If i click Junko, it says "Unfortunately the app stopped working". If I add new Name, ex. Nimrod, It will add successfully, but when i view Nimrod, the detail of Gemina will appear. And if i add another name, Vourin, the data of Gemina will appear its like their ids are interchanged and I think the error is in the delete part. I appreciate any comment. Thanks.
Below is my DBHelper.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.HashMap;
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "contactdb.sqlite";
public static final String CONTACTS_TABLE_NAME = "mycontacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_STUNAME = "name";
public static final String CONTACTS_COLUMN_STUPHONE = "phone";
public static final String CONTACTS_COLUMN_STUSTREET = "street";
public static final String CONTACTS_COLUMN_STUEMAIL = "email";
public static final String CONTACTS_COLUMN_STUCITY = "place";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 3);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(
"create table mycontacts " +
"(id integer primary key autoincrement, name text,phone text,email text, street text,place text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS mycontacts");
onCreate(db);
}
public boolean addStudentContact(String contactname,String contactphone,String contactstreet,String contactemail, String contactplace){
/*,*/
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contantValues = new ContentValues();
contantValues.put("name",contactname);
contantValues.put("phone", contactphone);
contantValues.put("street",contactstreet);
contantValues.put("email",contactemail);
contantValues.put("place",contactplace);
db.insert("mycontacts", null, contantValues);
db.close();
return true;
}
public boolean updateStudentContact(Integer contactid,String contactname,String contactphone,String contactstreet,String contactemail, String contactplace)
{
/*,String contactname,*/
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contantValues = new ContentValues();
contantValues.put("name",contactname);
contantValues.put("phone", contactphone);
contantValues.put("street",contactstreet);
contantValues.put("email",contactemail);
contantValues.put("place",contactplace);
db.update("mycontacts", contantValues, "id = ?", new String[]{Integer.toString(contactid)});
db.close();
return true;
}
public Integer deleteContact(Integer id){
SQLiteDatabase db=this.getWritableDatabase();
return db.delete("mycontacts","id = ?",new String[]{Integer.toString(id)});
}
public Cursor getData(int contactid){
SQLiteDatabase db=this.getWritableDatabase();
Cursor res=db.rawQuery("Select * from mycontacts where id = " + contactid + "", null);
return res;
}
public int numberOfRows(){
SQLiteDatabase db=this.getWritableDatabase();
int numRows=(int) DatabaseUtils.queryNumEntries(db,CONTACTS_TABLE_NAME);
return numRows;
}
public ArrayList<Person> getAllStudentContacts(){
ArrayList<Person> arraylist= new ArrayList<>();
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.rawQuery("Select * from mycontacts",null);
if (cursor.moveToFirst()) {
do {
Person person = new Person();
person.name = cursor.getString(cursor.getColumnIndex(CONTACTS_COLUMN_STUNAME));
person.ID = cursor.getInt(cursor.getColumnIndex(CONTACTS_COLUMN_ID));
arraylist.add(person);
} while (cursor.moveToNext());
}
return arraylist;
}
}
DisplayContact.java
package com.test.ppandey.contactapp;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class DisplayContact extends AppCompatActivity {
int from_Where_I_Am_Coming = 0;
private DBHelper mydb;
TextView name;
TextView phone;
TextView email;
TextView street;
TextView place;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_contact);
name = (TextView) findViewById(R.id.editTextName);
phone = (TextView) findViewById(R.id.editTextPhone);
email = (TextView) findViewById(R.id.editTextStreet);
street = (TextView) findViewById(R.id.editTextEmail);
place = (TextView) findViewById(R.id.editTextCity);
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
{
int Value = extras.getInt("id");
if (Value > 0) {
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
String stuname = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STUNAME));
String stuphone = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STUPHONE));
String stuemail = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STUEMAIL));
String stustreet = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STUSTREET));
String stuplace = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STUCITY));
if (!rs.isClosed()) {
rs.close();
}
Button b = (Button) findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
name.setText((CharSequence) stuname);
name.setFocusable(false);
name.setClickable(false);
phone.setText((CharSequence) stuphone);
phone.setFocusable(false);
phone.setClickable(false);
email.setText((CharSequence) stuemail);
email.setFocusable(false);
email.setClickable(false);
street.setText((CharSequence) stustreet);
street.setFocusable(false);
street.setClickable(false);
place.setText((CharSequence) stuplace);
place.setFocusable(false);
place.setClickable(false);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
Bundle extras = getIntent().getExtras();
if (extras != null) {
int Value = extras.getInt("id");
if (Value > 0) {
getMenuInflater().inflate(R.menu.menu_display_contact, menu);
} else {
getMenuInflater().inflate(R.menu.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.
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.Edit_Contact:
Button b = (Button) findViewById(R.id.button1);
b.setVisibility(View.VISIBLE);
name.setEnabled(true);
name.setFocusableInTouchMode(true);
name.setClickable(true);
phone.setEnabled(true);
phone.setFocusableInTouchMode(true);
phone.setClickable(true);
email.setEnabled(true);
email.setFocusableInTouchMode(true);
email.setClickable(true);
street.setEnabled(true);
street.setFocusableInTouchMode(true);
street.setClickable(true);
place.setEnabled(true);
place.setFocusableInTouchMode(true);
place.setClickable(true);
return true;
case R.id.Delete_Contact:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure ?");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void saveData(View view) {
/*, */
/* mydb.addContact(name.getText().toString(),email.getText().toString(), street.getText().toString(), place.getText().toString(), phone.getText().toString());
finish();*/
Bundle extras = getIntent().getExtras();
if (extras != null) {
int Value = extras.getInt("id");
if (Value > 0) {
if (mydb.updateStudentContact(id_To_Update, name.getText().toString(), phone.getText().toString(), street.getText().toString(),email.getText().toString(), place.getText().toString())) {
Toast.makeText(getApplicationContext(), "Successfully Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Record not updated", Toast.LENGTH_SHORT).show();
}
} else {
if (mydb.addStudentContact(name.getText().toString(), phone.getText().toString(),street.getText().toString(), email.getText().toString(), place.getText().toString())) {
Toast.makeText(getApplicationContext(), "Successfully Added", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Record not added", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
}
}
MainActivity.java
package com.test.ppandey.contactapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE="MESSAGE";
private ListView objListView;
DBHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db=new DBHelper(this);
ArrayList<Person> arrayList=db.getAllStudentContacts();
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,arrayList);
objListView=(ListView)findViewById(R.id.listView1);
objListView.setAdapter(arrayAdapter);
objListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
long id_to_search = id;
Bundle dataBundle = new Bundle();
dataBundle.putLong("id", id_to_search);
Intent intent = new Intent(getApplicationContext(), DisplayContact.class);
intent.putExtras(dataBundle);
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.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);*/
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.item1:Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new Intent(getApplicationContext(),DisplayContact.class);
intent.putExtras(dataBundle);
startActivityForResult(intent, 0);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
db=new DBHelper(this);
ArrayList<Person> arrayList=db.getAllStudentContacts();
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,arrayList);
objListView=(ListView)findViewById(R.id.listView1);
objListView.setAdapter(arrayAdapter);
}
}
activity_display_contact.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scrollView1"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="350dp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.test.ppandey.contactapp.DisplayContact">
<EditText
android:id="#+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="5dp"
android:layout_marginLeft="82dp"
android:ems="10"
android:inputType="text" >
</EditText>
<EditText
android:id="#+id/editTextEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editTextStreet"
android:layout_below="#+id/editTextStreet"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="textEmailAddress" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editTextName"
android:layout_alignParentLeft="true"
android:text="#string/name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editTextCity"
android:layout_alignParentBottom="true"
android:layout_marginBottom="28dp"
android:onClick="saveData"
android:text="#string/save" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editTextEmail"
android:layout_alignLeft="#+id/textView1"
android:text="#string/email"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editTextPhone"
android:layout_alignLeft="#+id/textView1"
android:text="#string/phone"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/editTextEmail"
android:layout_alignLeft="#+id/textView5"
android:text="#string/street"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/editTextCity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/editTextName"
android:layout_below="#+id/editTextEmail"
android:layout_marginTop="30dp"
android:ems="10"
android:inputType="text" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/editTextCity"
android:layout_alignBottom="#+id/editTextCity"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/editTextEmail"
android:text="#string/country"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/editTextStreet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editTextName"
android:layout_below="#+id/editTextPhone"
android:ems="10"
android:inputType="text" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editTextPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editTextStreet"
android:layout_below="#+id/editTextName"
android:ems="10"
android:inputType="phone|text" />
</RelativeLayout>
</ScrollView>
Person.java
package com.test.ppandey.contactapp;
/**
* Created by Ariel on 08/03/2016.
*/
public class Person {
public String name;
public long ID;
private Person person; {
name = new String(name);
}
private Person id; {
ID = new long(id);
}
}
I added Person.java and edited MainActivity.java and DBHelper.java
This is your problem:
int id_to_search = position + 1;
You are assuming that the IDs and the positions are in sync. This is only true as long as you do not remove any entries. Instead of using the position to reference an entry, you have to use the ID, as that's immutable.
When you pull the entries from your database, you need to pull the name and the ID, and keep that data in your adapter, so you can reference an entry by its ID.
Some code below (just a skeleton):
1) Create a model for your data
public class Person {
// consider making private and adding accessors
public String name;
public long id;
}
2) when you pull your data, pull the name and the ID (you may expand the Person class and this function to pull additional data):
public List<Person> getAllStudentContacts(){
List<Person> arraylist= new ArrayList<>();
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.rawQuery("Select * from mycontacts",null);
if (cursor.moveToFirst()) {
do {
Person person = new Person();
person.name = cursor.getString(cursor.getColumnIndex(CONTACTS_COLUMN_STUNAME));
person.id = cursor.getInt(cursor.getColumIndex(CONTACTS_COLUMN_ID));
arraylist.add(prson);
} while (cursor.moveToNext());
}
return arraylist;
}
Then in your adapter you use the ID in the Person object to reference it, instead of the position.
Are you refreshing your "List of Names" from your android App afer every insert/delete?
Maybe by calling getAllStudentContacts() from your code after every insert/delete to refill your List of names of your android app?
Good Luck

How to inflate views programmatically in vertical order

I just picked up Android developing. I decided to make a ToDo-list(simple and has a somewhat visual body) but I'm facing problems with inflating Layout in order.
Basically I have an Activity that collects information that is supposed to be shown in Main Activity. I get one of them showing up, but can't figure out how to add more than one of them. They'd be showing up in vertical order as the title says.
Main:
package com.example.victor.todo;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewManager;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
String NEW_TASK, NEW_TASK_DETAILS;
int pos = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_add_task){
Intent i = new Intent(this,AddTaskActivity.class);
startActivityForResult(i, 1);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == 1){
if(resultCode == RESULT_OK){
String task = data.getStringExtra("task");
String taskDetails = data.getStringExtra("details");
String taskInfo = data.getStringExtra(AddTaskActivity.EXTRA_NAME);
Log.i("TAG", "task: " + task);
Log.i("TAG", "task info: " + taskDetails);
AddTask(task, taskDetails);
} else {
//DO SOMETHING IF NO INFO IS RETURNED
}
}
}
public void AddTask(String task, String details){
TextView tw = (TextView)findViewById(R.id.addMainHint);
((ViewManager) tw.getParent()).removeView(tw);
LinearLayout linearLayoutMain = (LinearLayout) findViewById(R.id.mainLinearLayout);
View v = getLayoutInflater().inflate(R.layout.task_listing, null);
linearLayoutMain.addView(v);
TextView taskName = (TextView) v.findViewById(R.id.single_task_info);
taskName.setText(task);
CheckBox taskCheckBox = (CheckBox) v.findViewById(R.id.single_task_checkbox);
taskCheckBox.setChecked(false);
/*
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.single_task_layout);
relativeLayout.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
*/
/*
RelativeLayout layout = (RelativeLayout) findViewById(R.id.single_task_layout);
TextView ll = new TextView();
*/
}
public void TaskClicked(){
}
}
task_listing.xml(a relative layout that acts as the container of the info):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="70dp"
android:id="#+id/single_task_layout"
>
<TextView
android:layout_width="300dp"
android:layout_height="30dp"
android:id="#+id/single_task_info"
android:layout_marginTop="20dp"
android:textColor="#color/primary_material_dark"
android:textSize="20sp"
android:layout_alignParentRight="true"
android:layout_marginLeft="40dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:clickable="true" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/single_task_checkbox"
android:layout_gravity="left"
android:layout_toLeftOf="#id/single_task_info"
android:layout_marginTop="15dp"
android:layout_marginLeft="15dp"
android:enabled="true"
android:clickable="true"
android:onClick="TaskClicked"
android:visibility="visible" />
</RelativeLayout>
I guess I'm using the wrong tools but I don't even know what to search for! I don't have problems with Java itself but the design is giving me serious headache. I've been trying to figure this out for hours(it's 7.48 in the morning)!
Again, it works if I add just one of the layouts so the other javas and xmls aren't probably that important.
Thanks!
Use a listview is correct. Try doing this (A little bit more elaborate than what you have but worth it.
Create a Task object that implements Pacelable. This object can be sent back in the result of AddTaskActivity
public class Task implements Parcelable {
private String myTask;
private String myDetails;
public static final Parcelable.Creator<Task> CREATOR
= new Parcelable.Creator<Task>() {
public Task createFromParcel(Parcel in) {
return new Task(in);
}
public Task[] newArray(int size) {
return new Task[size];
}
};
public Task() {}
public Task(Parcel in){
myTask = in.readString();
myDetails = in.readString();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(myTask);
dest.writeString(myDetails);
}
}
And this is your class slightly modified
public class MainActivity extends ActionBarActivity {
private Adapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myAdapter = new Adapter();
ListView listView = (ListView)findViewById(android.R.id.list);
listView.setAdapter(myAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_add_task){
Intent i = new Intent(this,AddTaskActivity.class);
startActivityForResult(i, 1);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == 1){
if(resultCode == RESULT_OK){
myAdapter.addTask(data.getParcelableExtra(AddTaskActivity.[key constant]));
} else {
//DO SOMETHING IF NO INFO IS RETURNED
}
}
}
public void TaskClicked(){
}
private class Adapter extends BaseAdapter {
private List<Task> myTasks;
public Adapter() {
myTasks = new ArrayList<Task>();
}
public void addTask(Task task) {
myTasks.add(task);
notifyDataSetChanged();
}
#Override
public int getCount() {
return myTasks.size();
}
#Override
public Object getItem(int position) {
return myTasks.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView tw = (TextView)findViewById(R.id.addMainHint);
((ViewManager) tw.getParent()).removeView(tw);
convertView = getViewNotNull(convertView, parent);
Task task = (Task)getItem(position);
TextView taskName = (TextView) convertView.findViewById(R.id.single_task_info);
taskName.setText(task.getTask());
}
private View getViewNotNull(View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = View.inflate(parent.getContext(), R.layout.task_listing)
//here you should create a viewholder and set it on the view using setTag()
}
return convertView;
}
}
}
I quickly threw this together so hopefully it has what you need to get started
you'll still need to implement the item click listener on the listview as well as the check status for the checkboxes
Use ListView to get it done easily.

dialog fragment: response when entered value

I need help with knowing how to get dialogfragment act when entered a value then pressed okay button or cancel button.
Below are classes ActivityA.java, BasicDialogFragment.java, fragment_basic_dialog.xml and activity_a.xml.
That's all the code you need for this question. Thanks in advance.
ActivityA
package internal.android.com.helloworld;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ActivityA extends ActionBarActivity implements BasicDialogFragment.OnNameEnteredListener {
private Button dialogKnapp = null;
private TextView textA = null;
private TextView textA2 = null;
private EditText editA2 = null;
private Button buttonAB = null;
private Button buttonAC = null;
private Button buttonAD = null;
private Button buttonCancel = null;
private Button buttonOK = null;
private EditText dialog_fornavn = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
dialogKnapp = (Button) findViewById(R.id.dialog_knapp);
buttonCancel = (Button) findViewById(R.id.buttonCancel);
buttonOK = (Button) findViewById(R.id.buttonOK);
dialog_fornavn = (EditText) findViewById(R.id.dialog_fornavn);
textA = (TextView) findViewById(R.id.textA);
textA2 = (TextView) findViewById(R.id.textA2);
editA2 = (EditText) findViewById(R.id.editA2);
buttonAB = (Button) findViewById(R.id.buttonAB);
buttonAC = (Button) findViewById(R.id.buttonAC);
buttonAD = (Button) findViewById(R.id.buttonAD);
Intent intent = getIntent();
String navn = intent.getStringExtra("navnet");
textA2.setText(navn);
buttonAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAB();
}
});
buttonAC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAC();
}
});
buttonAD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAD();
}
});
dialogKnapp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startDialog();
}
});
}
private void startAB() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void startAC() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityC.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void startAD() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityD.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void startDialog() {
BasicDialogFragment bdf = new BasicDialogFragment();
bdf.show(getFragmentManager(), "basic");
}
public void OnFragmentInteractionListener(String nameEntered){
visTekst();
}
private void visTekst() {
if(buttonOK.isPressed()){
textA2.setText(dialog_fornavn.getText());
Toast melding = Toast.makeText(getApplicationContext(),
dialog_fornavn.getText(), Toast.LENGTH_SHORT);
melding.show();
} else if(buttonCancel.isPressed()){
startAB();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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.
Toast toast = Toast.makeText(getApplicationContext(), "Activity A",
Toast.LENGTH_SHORT);
switch (item.getItemId()) {
case R.id.menu_item_1:
toast.setText("Activity A");
toast.show();
return true;
case R.id.menu_item_2:
toast.setText("Activity B");
toast.show();
startAB();
return true;
case R.id.menu_item_3:
toast.setText("Activity C");
toast.show();
startAC();
return true;
case R.id.menu_item_4:
toast.setText("Activity D");
toast.show();
startAD();
return true;
case R.id.action_settings:
toast.setText("Settings");
toast.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
BasicDialogFragment.java
import android.app.Activity;
import android.app.DialogFragment;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link BasicDialogFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link BasicDialogFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class BasicDialogFragment extends DialogFragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnNameEnteredListener {
public void OnFragmentInteractionListener(String nameEntered);
}
private OnNameEnteredListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment BasicDialogFragment.
*/
// TODO: Rename and change types and number of parameters
public static BasicDialogFragment newInstance(String param1, String param2) {
BasicDialogFragment fragment = new BasicDialogFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public BasicDialogFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_basic_dialog, container, false);
this.getDialog().setTitle("First Name");
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.OnFragmentInteractionListener("uri");
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnNameEnteredListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
fragment_basic_dialog.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" tools:context="no.hit.kvisli.heiverden.BasicDialogFragment"
android:layout_width="match_parent" android:layout_height="match_parent"
android:padding="10dp" android:orientation="vertical" >
<EditText
android:id="#+id/dialog_fornavn"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:textSize="24dp" android:textColor="#android:color/holo_red_dark"
android:hint="Skriv fornavn her" android:inputType="textPersonName" />
<LinearLayout
android:layout_width="match_parent" android:layout_height="wrap_content"
android:padding="10dp" android:orientation="horizontal" >
<Button
android:id="#+id/buttonCancel" android:text="Cancel"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
<Button
android:id="#+id/buttonOK" android:text="OK"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
activity_a.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<LinearLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/farge_A"
tools:context=".ActivityA">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity A"
android:id="#+id/textA"
style="#style/Overskrift"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textA2"
style="#style/Overskrift"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editA2"
style="#style/EditTekst"
android:hint="Skriv noe her"
android:layout_marginLeft="120dp"
android:layout_marginTop="50dp"/>
<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="horizontal"
android:layout_marginTop="150dp"
android:layout_marginLeft="50dp"
tools:context=".ActivityA">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dialog"
android:id="#+id/dialog_knapp"
android:background="#color/dialog_knapp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to B"
android:id="#+id/buttonAB"
android:background="#color/farge_B"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to C"
android:id="#+id/buttonAC"
android:background="#color/farge_C"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to D"
android:id="#+id/buttonAD"
android:background="#color/farge_D"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
If I am reading it correctly and your BasicDialogFragment code is like this
then all you need to do is add
public void OnNameEntered(String nameEntered){
//Do Something Here
}
to your ActivityA.java
EDIT
modify the following functions as follows:
private void visTekst(String nameEntered) {
if(buttonOK.isPressed()){
textA2.setText(nameEntered);
Toast melding = Toast.makeText(getApplicationContext(),
dialog_fornavn.getText(), Toast.LENGTH_SHORT);
melding.show();
} else if(buttonCancel.isPressed()){
startAB();
}
}
and call it as
public void OnFragmentInteractionListener(String nameEntered){
visTekst(nameEntered);
}
You need to setup your listeners as it is mentioned in the code that you have used
in your BasicDialogFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_basic_dialog, container, false);
this.getDialog().setTitle("First Name");
buttonCancel = (Button) findViewById(R.id.buttonCancel);
buttonOK = (Button) findViewById(R.id.buttonOK);
buttonCancel.setOnClickListner(new View.OnClickListener(View v){
onButtonPressed(/*Your custom URI*/Uri uri);
});
buttonOK .setOnClickListner(new View.OnClickListener(View v){
onButtonPressed(/*Your custom URI*/Uri uri);
});
return v;
}
For this issue, there are two ways, one is direct cast to hosted Activity to get activity instance. Another is using one interface that defined in DialogFragment but implemented by hosted Activity.
For detail please follow my previous post Call activity from DialogFragment.
//Here is the answer. Took a while but got it to the end, thanks for your help.
//ActivityA
import android.app.FragmentManager;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ActivityA extends ActionBarActivity implements BasicDialogFragment.Communicator {
private Button dialogKnapp = null;
private TextView textA = null;
private TextView textA2 = null;
private EditText editA2 = null;
private Button buttonAB = null;
private Button buttonAC = null;
private Button buttonAD = null;
private EditText dialog_fornavn = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
dialogKnapp = (Button) findViewById(R.id.dialog_knapp);
dialog_fornavn = (EditText) findViewById(R.id.dialog_fornavn);
textA = (TextView) findViewById(R.id.textA);
textA2 = (TextView) findViewById(R.id.textA2);
editA2 = (EditText) findViewById(R.id.editA2);
buttonAB = (Button) findViewById(R.id.buttonAB);
buttonAC = (Button) findViewById(R.id.buttonAC);
buttonAD = (Button) findViewById(R.id.buttonAD);
Intent intent = getIntent();
String navn = intent.getStringExtra("navnet");
textA2.setText(navn);
buttonAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAB();
}
});
buttonAC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAC();
}
});
buttonAD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAD();
}
});
dialogKnapp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startDialog();
}
});
}
private void startAB() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void startAC() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityC.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void startAD() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityD.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
public void startDialog(){
FragmentManager manager = getFragmentManager();
BasicDialogFragment basicDialogFragment = new BasicDialogFragment();
basicDialogFragment.show(manager,"BasicDialogFragment");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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.
Toast toast = Toast.makeText(getApplicationContext(), "Activity A",
Toast.LENGTH_SHORT);
switch (item.getItemId()) {
case R.id.menu_item_1:
toast.setText("Activity A");
toast.show();
return true;
case R.id.menu_item_2:
toast.setText("Activity B");
toast.show();
startAB();
return true;
case R.id.menu_item_3:
toast.setText("Activity C");
toast.show();
startAC();
return true;
case R.id.menu_item_4:
toast.setText("Activity D");
toast.show();
startAD();
return true;
case R.id.action_settings:
toast.setText("Settings");
toast.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onDialogMessage(Editable message) {
textA2.setText(message);
}
}
//BasicDialogFragment
`import android.app.Activity;
import android.app.DialogFragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class BasicDialogFragment extends DialogFragment implements View.OnClickListener{
private Button buttonCancel = null;
private Button buttonOK = null;
private EditText dialog_fornavn = null;
Communicator communicator;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
communicator= (Communicator) activity;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_basic_dialog, null);
buttonCancel = (Button) v.findViewById(R.id.buttonCancel);
buttonOK = (Button) v.findViewById(R.id.buttonOK);
dialog_fornavn = (EditText) v.findViewById(R.id.dialog_fornavn);
buttonCancel.setOnClickListener(this);
buttonOK.setOnClickListener(this);
setCancelable(true);
return v;
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.buttonOK){
communicator.onDialogMessage(dialog_fornavn.getText());
dismiss();
}
else{
dismiss();
}
}
interface Communicator{
public void onDialogMessage(Editable message);
}
}`
//Thats it, nothing chaged in xml files. Not sure if its good coding but worked for me.

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
}
}

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

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));

Categories

Resources