Multiple Intents passing listView info from one activity to another - android

I'm trying to pass information from my second activity to my first activity. In my second Activity contains a list view of images of provinces in Canada. Each item in the list contains 3 properties (Province Name, Capital of the Province, Image id for the actual flag of the province). When the user selects an item from the listView it should direct them to the first Activity and pass the intent information from the second Activity to the first Activity. The information that will be passed are the name of the province and the capital of the province. I feel like I'm doing it correctly and my app currently has no issue in terms of bugs or crashes but I can't seem to figure out why the information is not being passed from activity 2 to activity 1. It just passes nothing. Thanks to those all in advance that help me out!
Main Activity.Java
TextView provinceTxt, capitalTxt;
String provinceString, capitalString;
ArrayList<Province> provinces;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
provinceTxt = findViewById(R.id.txtProvince);
capitalTxt = findViewById(R.id.txtCapital);
display();
}
public void selectProvince(View view) {
showAlertDialog();
}
public void showAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Would You Like to Open the Second Activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainActivity.this, Second_Activity.class);
startActivity(intent);
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
public void display(){
Intent intent = getIntent();
provinceString = intent.getStringExtra("name");
provinceTxt.setText(provinceString);
capitalString = intent.getStringExtra("capital");
capitalTxt.setText(capitalString);
}
}
Second Activity.Java
List<Province> provinces;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second_);
provinces = ProvincesData.getList();
listView = findViewById(R.id.listView);
CustomAdapter adapter = new CustomAdapter(Second_Activity.this, R.layout.list_view_row, provinces);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Province province = (Province) listView.getItemAtPosition(position);
Intent intent = new Intent();
intent.putExtra("name", province.getName());
intent.putExtra("capital", province.getCapital());
finish();
}
});
}
}
Province.Java
public class Province {
String name;
String capital;
public Province(String name, String capital, int armID) {
this.name = name;
this.capital = capital;
this.armID = armID;
}
int armID;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCapital() {
return capital;
}
public void setCapital(String capital) {
this.capital = capital;
}
public int getArmID() {
return armID;
}
public void setArmID(int armID) {
this.armID = armID;
}
}
ProvincesData.Java
public static List<Province> getList() {
List<Province> provinces = new ArrayList<Province>();
Province province1 = new Province("Alberta","Edmonton", R.drawable.alberta);
provinces.add(province1);
Province province2 = new Province("British Columbia","Victoria", R.drawable.british_columbia);
provinces.add(province2);
Province province3 = new Province("Manitoba","Winnipeg", R.drawable.manitoba);
provinces.add(province3);
Province province4 = new Province("New Brunswick","Fredericton", R.drawable.new_brunswick);
provinces.add(province4);
Province province5 = new Province("Newfoundland and Labrador","St. John's", R.drawable.newfoundland_and_labrador);
provinces.add(province5);
Province province6 = new Province("Nova Scotia","Halifax", R.drawable.nova_scotia);
provinces.add(province6);
Province province7 = new Province("Ontario","Toronto", R.drawable.ontario);
provinces.add(province7);
Province province8 = new Province("Quebec","Quebec City", R.drawable.quebec);
provinces.add(province8);
Province province9 = new Province("Saskatchewan","Regina", R.drawable.saskatchewan);
provinces.add(province9);
Province province10 = new Province("Prince Edward ","Charlottetown", R.drawable.prince_edward_island);
provinces.add(province10);
return provinces;
}
}
CustomAdapter.Java
public class CustomAdapter extends ArrayAdapter {
static class ViewHolder{
TextView provinceTv;
TextView cityTv;
ImageView armID;
}
List<Province> provinces;
public CustomAdapter(#NonNull Context context, int resource, #NonNull List objects) {
super(context, resource, objects);
provinces = objects;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder holder;
View view = convertView;
if(view == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_view_row , null);
holder = new ViewHolder();
holder.provinceTv = view.findViewById(R.id.txtProvinceRow);
holder.cityTv = view.findViewById(R.id.txtCapitalRow);
holder.armID = view.findViewById(R.id.imageView);
view.setTag(holder);
}
holder = (ViewHolder)view.getTag();
holder.provinceTv.setText(provinces.get(position).getName());
holder.cityTv.setText(provinces.get(position).getCapital());
holder.armID.setBackgroundResource(provinces.get(position).getArmID());
return view;
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="#+id/txtTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:text="Selected Province Info"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginHorizontal="25dp"
android:orientation="horizontal">
<TextView
android:id="#+id/txtProvinceTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Province Name"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<TextView
android:id="#+id/txtProvince"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="text"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginHorizontal="25dp"
android:orientation="horizontal">
<TextView
android:id="#+id/txtCapitalTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Capital City"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textStyle="bold"/>
<TextView
android:id="#+id/txtCapital"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="text"
android:textAppearance="#style/TextAppearance.AppCompat.Large" />
</LinearLayout>
<Button
android:id="#+id/btnSelect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginHorizontal="30dp"
android:text="Select Province"
android:onClick="selectProvince"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textStyle="bold"/>
</LinearLayout>
Activity_second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Second_Activity">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
list_view_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginHorizontal="10dp"
android:layout_weight="1"
tools:srcCompat="#tools:sample/avatars" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp"
android:layout_weight="2"
android:layout_marginHorizontal="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/txtProvinceRow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textStyle="bold"
android:text="" />
<TextView
android:id="#+id/txtCapitalRow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:text="" />
</LinearLayout>
</LinearLayout>

You forget to start the intent
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Province province = (Province) listView.getItemAtPosition(position);
Intent intent = new Intent(this.Second_Activity.class, MainActivity);
intent.putExtra("name", province.getName());
intent.putExtra("capital", province.getCapital());
startActivity(intent);
finish();
}
});
receive the intent
public void display(){
Bundle extras = intent.getExtras();
if(extras != null){
String provinceString = extras.getString("name");
provinceTxt.setText(provinceString);
String capitalString = extras.getString("capital");
capitalTxt.setText(capitalString);
}
}
for more details refer this

you can use Activity.startActivityForResult(Intent intent, int requestCode)to start Second Activity and use Activity.onActivityResult(int requestCode, int resultCode, Intent data) to receive data that from Second Activityin MainActivity

Related

ListView doesn't show ImageButton with BaseAdapter

I want to display a name from my database with a delete button on the right. I have created a custom adapter with BaseAdapter. The ListView show me the right name but no ImageButton. Hope ypu can help me.
Here my Code:
Layout for each ListItem:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/PlayerTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/PlayerDeleteImageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:background="#android:color/white"
android:padding="20dp"
app:srcCompat="#drawable/ic_baseline_delete_24"
android:tint="#color/colorPrimaryDark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Layout for my PlayerActivity:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Baum.PlayerActivity">
<EditText
android:id="#+id/PayerEditText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:hint="#string/AddPlayerHint"
app:layout_constraintEnd_toStartOf="#+id/PlayerFloatingActionButton"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ListView
android:id="#+id/PlayerListView"
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/bottom_navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/PayerEditText" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:itemBackground="#android:color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/menu_navigation" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/PlayerFloatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:clickable="true"
android:onClick="onClickFloatingActionButton"
android:tint="#color/colorPrimary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_baseline_add_24"
tools:ignore="VectorDrawableCompat" />
</androidx.constraintlayout.widget.ConstraintLayout>
My Activity:
public class PlayerActivity extends Activity {
private ArrayList<String> players = new ArrayList<>();
DBHelper db = new DBHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
//Initalize custom Players
loadPlayersInArrayList();
// Show all Players in the ListView
ListView listView = (ListView) findViewById(R.id.PlayerListView);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, players);
listView.setAdapter(arrayAdapter);
//All BottomNav stuff
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setSelectedItemId(R.id.player_menu);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.player_menu:
return true;
case R.id.home_menu:
startActivity(new Intent(getApplicationContext(), HomeActivity.class));
overridePendingTransition(0, 0);
return true;
case R.id.deck_menu:
startActivity(new Intent(getApplicationContext(), DecksActivity.class));
overridePendingTransition(0, 0);
return true;
}
return false;
}
});
}
public void onClickFloatingActionButton(View v){
EditText newPlayerName = findViewById(R.id.PayerEditText);
ArrayList<Player> dbPlayers = db.getAllPlayer();
boolean newPlayer = true;
for(Player p : dbPlayers){
if(newPlayerName.getText().toString().equals(p.getName())){
newPlayer = false;
new AlertDialog.Builder(this)
.setTitle("Information")
.setMessage("Dieser Name ist bereits vergeben")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
break;
}
}
if (newPlayer){
db.addPlayer(newPlayerName.getText().toString());
loadPlayersInArrayList();
}
}
public void loadPlayersInArrayList(){
if (players != null){
players.clear();
}
ArrayList<Player> dbPlayers = db.getAllPlayer();
for(Player p : dbPlayers){
players.add(p.getName());
}
}
}
Here is my Adapter:
public class PlayerAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> items;
public PlayerAdapter(Context context, ArrayList<String> items){
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null){
convertView = LayoutInflater.from(context).inflate(R.layout.player_list_item, parent, false);
}
String currentItem = (String) getItem(position);
TextView deckName = (TextView) convertView.findViewById(R.id.PlayerTextView);
ImageButton playerDeleteButton = (ImageButton) convertView.findViewById(R.id.PlayerDeleteImageButton);
deckName.setText(currentItem);
return convertView;
}
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
Here a screenshot of my ListView in the app:
ListView in the app
Here a screenshot from the Layout for each Item:
Screenshot Layout
I guess android.R.layout.simple_list_item_1 expect only a simple text view in the layout file. (I might be wrong as well).
Still using Base Adapter and android.R.layout.simple_list_item_1 are expected to be in a simple spinner item. For any custom layout for list item use ArrayAdapter<type>. Code as follows-
PlayerAdapter.java
public class PlayerAdapter extends ArrayAdapter<String> {
List<String> playerNameList;
public PlayerAdapter(#NonNull Context context, #NonNull List<String> playerNameList) {
//#param context, layout of list item, textview id of list item and List<String>
super(context, R.layout.player_list_item, R.id.PlayerTextView,playerNameList);
this.playerNameList = playerNameList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView playerTextView = view.findViewById(R.id.PlayerTextView);
ImageView playerDeleteImageButton = view.findViewById(R.id.PlayerDeleteImageButton);
playerTextView.setText(playerNameList.get(position));
playerDeleteImageButton.setOnClickListener(v -> {
// apply on image click code here
});
return view;
}
}
I modified to list item as well to be a simple LinearLayout -
ListItem Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_margin="5dp"
android:padding="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/PlayerTextView"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:textSize="20sp"
android:textStyle="bold"/>
<ImageView
android:id="#+id/PlayerDeleteImageButton"
android:src="#mipmap/ic_launcher_round"
android:layout_width="30dp"
android:layout_height="30dp"/>
</LinearLayout>
Setting PlayerAdpater
List<String> playerNameList = new ArrayList<>();
PlayerAdapter playerAdapter = new PlayerAdapter(this,playerNameList);
playerNameList.setAdapter(playerAdapter);
Hope this will help.
Happy Coding !

setOnItemClickListener() not working on ListView (select always first row)

I have created a custom ListView by extending LinearLayout for every row (Contact) and i need to select the item, but the method "setOnItemClickListener()" not working. I have just put a onItemSelectedListener under and now the method "setOnItemClickListener" select always the first item though i select other row
MainActivity:
public class MainActivity extends AppCompatActivity {
private ListView lvPhone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvPhone = (ListView)findViewById(R.id.listPhone);
final List<PhoneBook> listPhoneBook = new ArrayList<PhoneBook>();
listPhoneBook.add(new PhoneBook(BitmapFactory.decodeResource(getResources(),R.drawable.image),"Contact_1","123456789","av1#gmail.com","1"));
listPhoneBook.add(new PhoneBook(BitmapFactory.decodeResource(getResources(),R.drawable.image),"Contact_2","123456789","av2#gmail.com","2"));
listPhoneBook.add(new PhoneBook(BitmapFactory.decodeResource(getResources(),R.drawable.image),"Contact_3","123456789","av3#gmail.com","3"));
final PhoneBookAdapter adapter = new PhoneBookAdapter(this, listPhoneBook);
lvPhone.setAdapter(adapter);
lvPhone.setItemsCanFocus(false);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Dialog d = new Dialog(MainActivity.this);
d.setTitle("Login");
d.setCancelable(true);
d.setContentView(R.layout.account);
d.show();
Button button_close = (Button) d.findViewById(R.id.DCancel);
button_close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
d.dismiss();
}
});
Button button_login = (Button) d.findViewById(R.id.DLogin);
button_login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String mName = new String("Ciao");
String mPhone;
String mEmail;
String mID;
TextView TextName = (TextView) d.findViewById(R.id.DName);
TextView TextPhone = (TextView)d.findViewById(R.id.DPhone);
TextView TextEmail = (TextView)d.findViewById(R.id.DEmail);
TextView TextID = (TextView)d.findViewById(R.id.DID);
mName=TextName.getText().toString();
mPhone=TextPhone.getText().toString();
mEmail=TextEmail.getText().toString();
mID=TextID.getText().toString();
listPhoneBook.add(new PhoneBook(BitmapFactory.decodeResource(getResources(),R.drawable.image),mName,mPhone,mEmail,mID));
lvPhone.setAdapter(adapter);
d.dismiss();
}
});
}
});
lvPhone.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView TextName = (TextView) view.findViewById(R.id.tvName);
TextView TextPhone = (TextView)view.findViewById(R.id.tvPhone);
TextView TextEmail = (TextView)view.findViewById(R.id.tvEmail);
TextView TextID = (TextView)view.findViewById(R.id.tvID);
String tvName = new String(TextName.getText().toString());
String tvPhone = new String(TextPhone.getText().toString());
String tvEmail = new String(TextEmail.getText().toString());
String tvID = new String(TextID.getText().toString());
Toast.makeText(MainActivity.this, tvName, Toast.LENGTH_SHORT).show();
}
});
lvPhone.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
PhoneBookAdapter:
public class PhoneBookAdapter extends BaseAdapter{
private Context mContext;
private List<PhoneBook> mListPhoneBook;
public PhoneBookAdapter (Context context, List<PhoneBook> list) {
mContext = context;
mListPhoneBook = list;
}
#Override
public int getCount() {
return mListPhoneBook.size();
}
#Override
public Object getItem(int position) {
return mListPhoneBook.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
PhoneBook entry = mListPhoneBook.get(position);
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.phonebook_row,null);
}
ImageView ivAvatar = (ImageView)convertView.findViewById(R.id.imgAvatar);
ivAvatar.setImageBitmap(entry.getmAvatar());
TextView tvName = (TextView)convertView.findViewById(R.id.tvName);
tvName.setText(entry.getmName());
TextView tvPhone = (TextView)convertView.findViewById(R.id.tvPhone);
tvPhone.setText(entry.getmPhone());
TextView tvEmail = (TextView)convertView.findViewById(R.id.tvEmail);
tvEmail.setText(entry.getmEmail());
TextView tvID = (TextView)convertView.findViewById(R.id.tvID);
tvID.setText(entry.getmID());
return convertView;
}
}
`
PhoneBook_row:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true">
<ImageView
android:id="#+id/imgAvatar"
android:layout_width="70dp"
android:layout_height="70dp"
android:scaleType="fitCenter"
android:src="#drawable/image"
android:clickable="true"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:clickable="true">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvName"
android:textStyle="bold"
android:clickable="true"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvPhone"
android:textStyle="bold"
android:clickable="true"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvEmail"
android:textStyle="bold"
android:clickable="true"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvID"
android:textStyle="bold"
android:clickable="true"/>
</LinearLayout>
</LinearLayout>
Replace your PhoneBook_row.xml with the one I am putting up here, I have tried this and it worked for me. I have changed all your android:clickable="true" to android:clickable="false". The reason for doing this is, all of your child views consume click and the result is your parent view i.e ListView not getting the click event. Hope this helps.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="false">
<ImageView
android:id="#+id/imgAvatar"
android:layout_width="70dp"
android:layout_height="70dp"
android:scaleType="fitCenter"
android:src="#drawable/image"
android:clickable="false"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:clickable="false">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvName"
android:textStyle="bold"
android:clickable="false"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvPhone"
android:textStyle="bold"
android:clickable="false"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvEmail"
android:textStyle="bold"
android:clickable="false"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvID"
android:textStyle="bold"
android:clickable="false"/>
</LinearLayout>
</LinearLayout>
Looks like you are missing the override.
Add an #Override before the function as shown below.
lvPhone.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
Also adding android:clickable = true in the layout file wouldn't be necessary.
You have changed your question , anyway i believe you can now get the item selected listener working. To get the item which is selected you can use the position as below
lvPhone.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
PhoneBook phoneBook = listPhoneBook.get(position);
Toast.makeText(MainActivity.this, phoneBook.getName() , Toast.LENGTH_SHORT).show();
//where getName is a function to get the name in the phonebook class
}
});

Dynamically inserting list items to listview in android

Friends i'm new to android and learning on my own. I was creating invoice manager app for learning. Here products are added by the admin and that is working fine. User has only permission to create invoice. When user arrives into create_invoice activity he has set of frame layouts in which one is for adding items. When user presses the frame layout he is made to see another activity where he can find all set of list items along with the product price in List view which admin has added. Now when user presses an item he is again brought back to create_invoice activity and a alert box appears which asks the qty required. When user enters the qty and clicks OK button, for the first the list item is displayed properly as i require. But when i add second item, 1st item gets replaced. So now my problem is how can i resolve this problem.. Guys please help me. Codes you people find may be very silly but i'm still learning. Thanks in advance.
Create_invoice activity
//data from activity invoice add_item
product_name = intent.getStringExtra("product_name");
product_price = intent.getDoubleExtra("product_price",0);
//product_qty = intent.getIntExtra("product_qty",0);
product_code = intent.getIntExtra("product_code",0);
if(product_name!= null && product_price!= 0 && product_code!= 0)
{
try {
builder = new AlertDialog.Builder(this);
builder.setTitle("Product Qty");
layoutInflater = LayoutInflater.from(Create_invoice.this);
view = layoutInflater.inflate(R.layout.dialoglayout_invoice,null);
builder.setView(view);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
EditText etxt_dialog_qty=(EditText)view.findViewById(R.id.
etxt_dialog_qty);
int qty = Integer. parseInt (etxt_dialog_qty.getText().
toString().trim());
invoice_product_list products = new invoice_product_list
(product_name, product_price, qty, product_code);
//arraylist
ArrayList<invoice_product_list> productList = new ArrayList<>();
//customAdapter
customAdapterInvoice = new custom_adapter_invoice
(Create_invoice.this, productList);
customAdapterInvoice.add(products);
customAdapterInvoice.notifyDataSetChanged();
//listview in create_invoice activity
listView_additem = (ListView)
findViewById(R.id.listview_additem);
listView_additem.setAdapter(customAdapterInvoice);
alertDialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog = builder.create();
alertDialog.show();
}
catch (Exception e)
{
System.out.print(e);
}
}
customAdapter
public class custom_adapter_invoice extends ArrayAdapter
<invoice_product_list> {
public custom_adapter_invoice(Context context,
ArrayList<invoice_product_list> product_details) {
super(context, R.layout.custom_row_invoice_item, product_details);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
View view =
layoutInflater.inflate(R.layout.custom_row_invoice_item,parent,false);
invoice_product_list products = getItem(position);
TextView txt_product_name =
(TextView)view.findViewById(R.id.txt_product_name);
TextView txt_product_price =
(TextView)view.findViewById(R.id.txt_product_price);
TextView txt_product_qty =
(TextView)view.findViewById(R.id.txt_product_qty);
TextView txt_product_code =
(TextView)view.findViewById(R.id.txt_product_code);
txt_product_name.setText(products.getProduct_name());
txt_product_price.setText(String.valueOf(products.getProduct_price()));
txt_product_qty.setText(String.valueOf(products.getProduct_qty()));
txt_product_code.setText(String.valueOf(products.getProduct_code()));
return view;
}
create invoice activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.tournonstop.m.invoicemanager.Create_invoice"
tools:showIn="#layout/activity_create_invoice">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/darker_gray">
<include layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="85dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/white"
android:id="#+id/invoice_frame_company">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/company_name"
android:id="#+id/txt_company_name"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/invoice_date"
android:id="#+id/txt_invoice_date"
android:layout_gravity="right"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/invoice_no"
android:id="#+id/textView3"
android:layout_marginLeft="15dp"
android:layout_marginTop="45dp"/>
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/white"
android:id="#+id/invoice_frame_client"
android:clickable="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/to"
android:id="#+id/txt_to"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/txt_client_address"
android:layout_marginLeft="50dp"
android:layout_marginTop="10dp"
android:hint="#string/client_hint"/>
</FrameLayout>
----listview to add items-----
<FrameLayout
android:layout_width="match_parent"
android:layout_height="210dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/white"
android:id="#+id/invoice_frame_add_item"
android:clickable="true">
<ListView
android:layout_width="match_parent"
android:layout_height="150dp"
android:id="#+id/listview_additem"
android:divider="#040404" />
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="2dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/white"
android:id="#+id/invoice_frame_sub_total">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/total_label"
android:id="#+id/txt_sub_total_label"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:textStyle="bold"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/total"
android:id="#+id/txt_sub_total"
android:layout_gravity="right"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:textStyle="bold"
android:hint="#string/total_hint" />
</FrameLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="40dp"
android:text="#string/invoice_btn"
android:textStyle="bold"
android:background="#color/colorPrimaryDark"
android:textColor="#android:color/white"
android:clickable="true"
android:id="#+id/btn_invoice_save" />
</LinearLayout>
< /android.support.v4.widget.DrawerLayout>
invoice product list(getters and setters)
package com.tournonstop.m.invoicemanager;
public class invoice_product_list {
private String product_name;
private double product_price;
private int product_qty;
private int product_code;
public invoice_product_list(){
}
public invoice_product_list(String product_name,double
product_price,int product_qty,int product_code){
this.product_name = product_name;
this.product_price = product_price;
this.product_qty = product_qty;
this.product_code = product_code;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public int getProduct_code() {
return product_code;
}
public void setProduct_code(int product_code) {
this.product_code = product_code;
}
public double getProduct_price() {
return product_price;
}
public void setProduct_price(double product_price) {
this.product_price = product_price;
}
public int getProduct_qty() {
return product_qty;
}
public void setProduct_qty(int product_qty) {
this.product_qty = product_qty;
}
}
Add item to your list that you're using in adapter and (after verifying adapter is not null ) call method notifyDataSetChanged () on adapter object.
create_invoice activity
//arraylist
ArrayList<invoice_product_list> productList = new ArrayList<>();
//customAdapter
customAdapterInvoice = new custom_adapter_invoice
(Create_invoice.this, productList);
customAdapterInvoice.addProduct(products)
custom Adapter
public class custom_adapter_invoice extends ArrayAdapter <invoice_product_list>
{
ArrayList<invoice_product_list> productList = new ArrayList<>();
public custom_adapter_invoice(Context context,
ArrayList<invoice_product_list> product_details) {
super(context, R.layout.custom_row_invoice_item, product_details);
this.productList =product_details
}
public void addProduct(Product products
productList.add(products);
notifyDataSetChanged();
}
......
}
No,it does not change anything. If you want the latest method of working then I would prefer RecyclerView to custom list adapter. this link is very good for recyclerview
recyclerview demo series link

Row layout not inflated in Android

I have a problem. I started a few weeks ago learning Android. I am trying to create an adapter for a list. But the lists doesn't show up AT ALL. Any ideas why? The items are objects type Verb. Here is my code:
///my main activity///
public class Verbs extends Activity {
private ListView listViewVerbs;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verbs);
//instantiate Verb
Verb[] VerbData=new Verb[3];
VerbData[0] = new Verb("machen","mache","machen","mache","machen","mache","machen");
VerbData[1] = new Verb("machen","mache","machen","mache","machen","mache","machen");
VerbData[2] = new Verb("machen","mache","machen","mache","machen","mache","machen");
//pass data to adapter
VerbAdapter adapter = new VerbAdapter(this,R.layout.row_verbs,VerbData);
listViewVerbs = (ListView)findViewById(R.id.list);
listViewVerbs.setAdapter(adapter);
listViewVerbs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String wasClicked = view.findViewById(R.id.nameVerb).toString();
Toast.makeText(Verbs.this,
"You clicked: " + wasClicked, Toast.LENGTH_LONG)
.show();
}
});
}
}
//class for an item of the list
public class Verb {
public String verbname;
public String fpersg;
public String fperspl;
public String sperssg;
public String sperspl;
public String tperssg;
public String tperspl;
//constructor
public Verb(String s, String s1, String s2, String s3, String s4, String s5,String s6){
this.verbname = s;
this.fpersg = s1;
this.fperspl = s2;
this.sperssg = s3;
this.sperspl = s4;
this.tperssg = s5;
this.tperspl = s6;
}
//setters
public void setVbName(String vbName){
this.verbname = vbName;
}
public void setFpersg(String fpersg){
this.fpersg = fpersg;
}
public void setFperpl(String fperpl){
this.fperspl = fperpl;
}
public void setSpersg(String spersg){
this.sperssg = spersg;
}
public void setSperspl(String sperpl){
this.sperspl = sperpl;
}
public void setTpersg(String tpersg){
this.tperssg = tpersg;
}
public void setTperpl(String tperpl){
this.tperspl = tperpl;
}
//getters
public String getVerbname(){
return this.verbname;
}
public String getFpersg(){
return this.fpersg;
}
public String getFperpl(){
return this.fperspl;
}
public String getSpersg(){
return this.sperssg;
}
public String getSperpl(){
return this.sperspl;
}
public String getTpersg(){
return this.tperssg;
}
public String getTperspl(){
return this.tperspl;
}
}
//the adapter
public class VerbAdapter extends ArrayAdapter<Verb>{
Context mContext;
int layoutResourceId;
Verb data[] = null;
public VerbAdapter(Context mContext, int layoutResourceId, Verb[] data){
super(mContext, layoutResourceId, data);
this.mContext = mContext;
this.layoutResourceId =layoutResourceId;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
if (convertView == null){
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId,parent, false);
}
TextView textView0 = (TextView) convertView.findViewById(R.id.nameVerb);
TextView textView1 = (TextView) convertView.findViewById(R.id.firstpersonsg);
TextView textView2 = (TextView) convertView.findViewById(R.id.firstpersonpl);
TextView textView3 = (TextView) convertView.findViewById(R.id.secondpersonsg);
TextView textView4 = (TextView) convertView.findViewById(R.id.secondpersonpl);
TextView textView5 = (TextView) convertView.findViewById(R.id.thirdpersonsg);
TextView textView6 = (TextView) convertView.findViewById(R.id.thirdpersonpl);
Verb verb = data[position];
textView0.setText(verb.verbname);
textView1.setText(verb.fpersg);
textView2.setText(verb.fperspl);
textView3.setText(verb.sperssg);
textView4.setText(verb.sperspl);
textView5.setText(verb.tperssg);
textView6.setText(verb.tperspl);
return convertView;
}
}
------and two XML files named activity_verbs where the list is declared and row_verbs where the layout of each item is declared-----
row_verbs.xml ------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/nameVerb"
android:text="#string/nameVerb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#7663d5"
android:textColor="#f8f8f8"
android:padding="10dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="0dp"
android:textStyle="bold" />
<TextView
android:id="#+id/firstpersonsg"
android:layout_width="182dp"
android:layout_height="wrap_content"
android:text="#string/firstsg"
android:layout_below="#+id/nameVerb"
android:layout_marginLeft="10dp"
android:layout_marginTop="2dp"
android:padding="5dp"
android:background="#cacaca"
android:textColor="#7663d5" />
<TextView
android:id="#+id/firstpersonpl"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:text="#string/firstpl"
android:padding="5dp"
android:layout_marginTop="2dp"
android:layout_marginLeft="2dp"
android:background="#FFCACACA"
android:textColor="#7663d5"
android:layout_below="#+id/nameVerb"
android:layout_toRightOf="#+id/firstpersonsg"/>
<TextView
android:id="#+id/secondpersonsg"
android:layout_width="182dp"
android:layout_height="wrap_content"
android:text="#string/secondsg"
android:layout_below="#+id/firstpersonsg"
android:layout_marginLeft="10dp"
android:layout_marginTop="2dp"
android:padding="5dp"
android:background="#FFCACACA"
android:textColor="#7663d5" />
<TextView
android:id="#+id/secondpersonpl"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:text="#string/secondpl"
android:padding="5dp"
android:layout_marginTop="2dp"
android:layout_marginLeft="2dp"
android:background="#FFCACACA"
android:textColor="#7663d5"
android:layout_below="#+id/firstpersonpl"
android:layout_toRightOf="#+id/secondpersonsg"/>
<TextView
android:id="#+id/thirdpersonsg"
android:layout_width="182dp"
android:layout_height="wrap_content"
android:text="#string/thirdsg"
android:layout_below="#+id/secondpersonsg"
android:layout_marginLeft="10dp"
android:layout_marginTop="2dp"
android:padding="5dp"
android:background="#FFCACACA"
android:textColor="#7663d5" />
<TextView
android:id="#+id/thirdpersonpl"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:text="#string/thirdpl"
android:padding="5dp"
android:layout_marginTop="2dp"
android:layout_marginLeft="2dp"
android:background="#FFCACACA"
android:textColor="#7663d5"
android:layout_below="#+id/secondpersonpl"
android:layout_toRightOf="#+id/thirdpersonsg"/>
</RelativeLayout>
and the other one activity_verbs.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="${relativePackage}.${activityClass}"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:textSize="20sp"
android:padding="10dp"
android:background="#7663d5"
android:textColor="#f8f8f8"
android:textStyle="bold"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lessonId"
android:layout_below="#+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#292929"
android:textColor="#f0f0f0"
android:padding="10dp"/>
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/lessonId"/>
</RelativeLayout>
I copied your code with only one change:
I removed
tools:context="${relativePackage}.${activityClass}"
from activity_verbs and it works like a charm for me:
I uploaded my test-project with your code to DropBox, feel free to download it:
https://www.dropbox.com/s/8fcdab3rmx8zb57/ElaPinkSO.zip?dl=0
P.S. Very well structured question, good job!

Unable to select an item in a ListView whose content is set by an Array Adapter

I couldn't select an item on ListView. I use Custom Adapter to set content of ListView. I have set OnItemClickListener of ListView. However, it didn't respond. I appriciate your help. Here is my code:
List Item (connections.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="6dip" >
<LinearLayout
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.90"
android:orientation="vertical" >
<TextView
android:id="#+id/connname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/acc1" />
<TextView
android:id="#+id/conntype"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="9sp"
android:text="#string/acctype1" />
</LinearLayout>
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
The screen which containt ListView (groupconnections.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">
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:layout_marginBottom="5dip"
android:orientation="vertical"
android:id="#+id/textOperLayout">
<TextView
android:id="#+id/connectionsLabel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/connections"
android:textColor="#color/conn_text"
android:textSize="25sp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="15dp"
android:background="#color/conn_back"/>
<EditText
android:id="#+id/searchEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="#string/searchhint"
android:layout_marginTop="10dp"
android:inputType="textPersonName" />
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dip"
android:layout_marginBottom="50dip"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_above="#+id/textOperLayout"
android:id="#+id/listviewlayout">
<ListView
android:id="#+id/connectionlist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:choiceMode="singleChoice" />
</LinearLayout>
<Button
android:id="#+id/addConnCommitButton"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginLeft="15dp"
android:text="#string/commitToAdd" />
</RelativeLayout>
The related activity (AddMoreConnections.xml):
public class AddMoreConnections extends Activity implements OnItemClickListener{
private ListView mainListView ;
private ArrayAdapter<AbstractHolder> listAdapter ;
private TextView searchConnTextView;
private Button commitButton;
private ArrayList<AbstractHolder> connlist;
private ArrayList<AbstractHolder> listNotOnView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Generate list View from ArrayLis
setContentView(R.layout.groupconnections);
addListenerOnSearchConnTextView();
//Initialize properties
mainListView = (ListView) findViewById( R.id.connectionlist );
mainListView.setOnItemClickListener(this);
// Create and populate a List of planet names.
listNotOnView = new ArrayList<AbstractHolder>();
connlist = new ArrayList<AbstractHolder>(5);
Iterator<AbstractHolder> iter = SocialRssModel.holders.values().iterator();
while(iter.hasNext())
connlist.add(iter.next());
// Create ArrayAdapter using the planet list.
listAdapter = new CustomAdapter(this,
R.layout.connlist, connlist);
mainListView.setAdapter( listAdapter );
}
public void addListenerToFinishButton(){
commitButton = (Button) findViewById(R.id.addConnCommitButton);
commitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public void addListenerOnSearchConnTextView(){
searchConnTextView = (TextView) findViewById(R.id.searchEditText);
searchConnTextView.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int listNotOnViewsize = listNotOnView.size();
int connlistsize = connlist.size();
for(int i= 0; i < connlistsize; i++){
if(!connlist.get(i).connNameContains(s.toString())){
listNotOnView.add(connlist.remove(i));
i--;
connlistsize--;
}
}
for(int i=0; i < listNotOnViewsize; i++){
if(listNotOnView.get(i).connNameContains(s.toString())){
connlist.add(listNotOnView.remove(i));
i--;
listNotOnViewsize--;
}
}
((CustomAdapter) listAdapter).updateList(connlist);
listAdapter.notifyDataSetChanged();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
AbstractHolder temp = (AbstractHolder)mainListView.getItemAtPosition(arg2);
Intent i = new Intent(this, CategoryContentViewerController.class);
Bundle b = new Bundle();
b.putInt("AbstractHolderKey", temp.getId());
i.putExtras(b);
startActivity(i);
finish();
}
private class CustomAdapter extends ArrayAdapter<AbstractHolder> {
private ArrayList<AbstractHolder> connectionList;
public CustomAdapter(Context context, int textViewResourceId, ArrayList<AbstractHolder> connList) {
super(context, textViewResourceId, connList);
this.connectionList = new ArrayList<AbstractHolder>();
this.connectionList.addAll(connList);
}
public void updateList(ArrayList<AbstractHolder> connList){
connectionList.clear();
connectionList.addAll(connList);
}
private class ViewHolder {
TextView name;
TextView acctype;
CheckBox sel;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)(((Activity)this.getContext()).getSystemService(Context.LAYOUT_INFLATER_SERVICE));
convertView = vi.inflate(R.layout.connlist, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.connname);
holder.acctype = (TextView) convertView.findViewById(R.id.conntype);
holder.sel = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
AbstractHolder conn = connectionList.get(position);
holder.name.setText(conn.getName());
holder.acctype.setText(conn.getConntype());
holder.sel.setChecked(conn.isSelected());
holder.sel.setTag(conn);
return convertView;
}
}
}
It is related to checkbox item in connections.xml which is the list row item. If I remove checkbox, related listeners responses. I think, it may be thought there is no need a setItemOnClickListener(..) method since each row has a checkbox. Or it is a bug.

Categories

Resources