items in listview not appear - android

I try to make items appear in my list view, when add new contact then add it to list view ,it's not appear when I add new contact.
here is main_fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main, container, false);
ImageView contactImage;
final EditText nametxt, emailTxt, phoneTxt, addressTxt;
nametxt = (EditText) view.findViewById(R.id.txtName);
emailTxt = (EditText) view.findViewById(R.id.txtEmail);
phoneTxt = (EditText) view.findViewById(R.id.txtPhone);
addressTxt = (EditText) view.findViewById(R.id.txtAddress);
dbHandler = new DatabaseHandler(getActivity().getApplicationContext());
final Button addBtn = (Button) view.findViewById(R.id.btnadd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri imageUri = Uri.parse("android.resource://org.intracode.contactmanager/drawable/no_user_logo.png");
import_fragment.Contact contact = new import_fragment.Contact(dbHandler.getContactsCount(), String.valueOf(nametxt.getText()), String.valueOf(phoneTxt.getText()), String.valueOf(emailTxt.getText()), String.valueOf(addressTxt.getText()), imageUri);
if (!contactExists(contact)) {
dbHandler.createContact(contact);
Contacts.add(contact);
if (contactAdapter != null) contactAdapter.notifyDataSetChanged();
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(nametxt.getText()) + " has been added to your Contacts!", Toast.LENGTH_SHORT).show();
resetAddContactPanel();
return;
}
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(nametxt.getText()) + " already exists. Please use a different name.", Toast.LENGTH_SHORT).show();
}
});
final Button addContact = (Button) view.findViewById(R.id.btnadd);
nametxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
addContact.setEnabled(!nametxt.getText().toString().trim().equals(""));
}
#Override
public void afterTextChanged(Editable s) {
}
});
return view;
}
ArrayAdapter<import_fragment.Contact> contactAdapter;
ListView contactListView;
DatabaseHandler dbHandler;
int longClickedItemIndex;
public void onActivityResult(int reqCode, int resCode, Intent data) {
Uri imageUri = Uri.parse("android.resource://org.intracode.contactmanager/drawable/no_user_logo.png");
ImageView contactImageImgView;
contactImageImgView = (ImageView) getActivity().findViewById(R.id.ivContactImage);
if (resCode == Activity.RESULT_OK) {
if (reqCode == 1) {
imageUri = data.getData();
contactImageImgView.setImageURI(data.getData());
}
}
}
private void resetAddContactPanel() {
final EditText nametxt, emailTxt, phoneTxt, addressTxt;
nametxt = (EditText) getActivity().findViewById(R.id.txtName);
emailTxt = (EditText) getActivity().findViewById(R.id.txtEmail);
phoneTxt = (EditText) getActivity().findViewById(R.id.txtPhone);
addressTxt = (EditText) getActivity().findViewById(R.id.txtAddress);
nametxt.setText("");
phoneTxt.setText("");
emailTxt.setText("");
addressTxt.setText("");
}
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
{
ImageView contactImageImgView;
contactImageImgView = (ImageView) view.findViewById(R.id.ivContactImage);
contactImageImgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
}
});
if (dbHandler.getContactsCount() != 0)
Contacts.addAll(dbHandler.getAllContacts());
populateList();
}
menu.setHeaderIcon(R.drawable.pencil_icon);
menu.setHeaderTitle("Contact Options");
menu.add(Menu.NONE, EDIT, menu.NONE, "Edit Contact");
menu.add(Menu.NONE, DELETE, menu.NONE, "Delete Contact");
}
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case EDIT:
// TODO: Implement editing a contact
break;
case DELETE:
dbHandler.deleteContact(Contacts.get(longClickedItemIndex));
Contacts.remove(longClickedItemIndex);
contactAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
private boolean contactExists(import_fragment.Contact contact) {
String name = contact.getName();
int contactCount = Contacts.size();
for (int i = 0; i < contactCount; i++) {
if (name.compareToIgnoreCase(Contacts.get(i).getName()) == 0)
return true;
}
return false;
}
private void populateList() {
contactAdapter = new ContactListAdapter(getActivity());
contactListView.setAdapter(contactAdapter);
}
final List<import_fragment.Contact> Contacts = new ArrayList<import_fragment.Contact>();
private class ContactListAdapter extends ArrayAdapter<import_fragment.Contact> {
public ContactListAdapter(Context cntx) {
super(cntx, R.layout.fragment_import, Contacts);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getActivity().getLayoutInflater().inflate(R.layout.fragment_import, parent, false);
import_fragment.Contact currentContact = Contacts.get(position);
TextView name = (TextView) view.findViewById(R.id.contactName);
name.setText(currentContact.getName());
TextView phone = (TextView) view.findViewById(R.id.phoneNumber);
phone.setText(currentContact.getPhone());
TextView email = (TextView) view.findViewById(R.id.emailAddress);
email.setText(currentContact.getEmail());
TextView address = (TextView) view.findViewById(R.id.cAddress);
address.setText(currentContact.getAddress());
return view;
}
}
Someone told me u must setAdapter in onCreateView and when I did that i get error Null so I removed it, if this will solve problem then please tell me how to setAdapter in onCreateView without getting null error.

Related

Why is my Listview not showing anything on my activity?

I have created a custom list and then put some data and inflate it into my listview but it is not showing. Can you please tell me what am I missing on my code? It doesn't show any errors related to this problem on my logcat.
What I wanted to happen is when the user enter all the details from AddStudentActivity, all the data will be shown in another activity which is in the MainActivity.
I am using intent on this one. Thanks for any help.
MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<Student> studentArrayList = new ArrayList<>();
CustomAdapter adapter;
private Uri imageUri;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.student_listview);
adapter = new CustomAdapter(this, studentArrayList);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
}
//for menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home){
onBackPressed();
return true;
}else if(id == R.id.action_add){
Intent add = new Intent(MainActivity.this, AddStudentActivity.class);
startActivity(add);
}
return super.onOptionsItemSelected(item);
}
//inflate the menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.addmenu, menu);
return super.onCreateOptionsMenu(menu);
}
//handles the onclick listener for the listview
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK){
Bundle b = data.getExtras();
imageUri = b.getParcelable("image");
String lastname = b.getString("lastname");
String firstname = b.getString("firstname");
String course = b.getString("course");
Student student = new Student(imageUri, lastname, firstname, course);
studentArrayList.add(student);
adapter.notifyDataSetChanged();
}else{
}
}
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
Context context;
//data container
ArrayList<Student> list;
LayoutInflater inflater;
//contructor
public CustomAdapter(Context context, ArrayList<Student> list) {
this.context = context;
this.list = list;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_layout, parent, false);
holder.iv = (ImageView) convertView.findViewById(R.id.imageView);
holder.lname = (TextView) convertView.findViewById(R.id.textLastname);
holder.fname= (TextView) convertView.findViewById(R.id.textFirstname);
holder.course = (TextView) convertView.findViewById(R.id.textCourse);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
//inflate
holder.iv.setImageURI(list.get(position).getUriImage());
holder.lname.setText(list.get(position).getStudlname());
holder.fname.setText(list.get(position).getStudfname());
holder.course.setText(list.get(position).getStudcourse());
return convertView;
}
//creating a static class
static class ViewHolder{
ImageView iv;
TextView lname, fname,course;
}
}
AddStudentActivity.java
public class AddStudentActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
ListView lv;
ImageView studImage;
Uri studImageUri;
EditText lastname, firstname;
String selectedCourse;
Spinner course;
Button btnsave, btncancel;
CustomAdapter adapter;
private static final int PICK_IMAGE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_student);
//
studImage = (ImageView) findViewById(R.id.addstudentimage);
lastname = (EditText) findViewById(R.id.editTextLastname);
firstname = (EditText) findViewById(R.id.editTextFirstname);
course = (Spinner) findViewById(R.id.spinnerCourse);
btnsave = (Button) findViewById(R.id.btn_save);
btncancel = (Button) findViewById(R.id.btn_cancel);
studImage.setOnClickListener(this);
btnsave.setOnClickListener(this);
btncancel.setOnClickListener(this);
course.setOnItemSelectedListener(this);
}
//on click listeners for the buttons and imageview
#Override
public void onClick(View v) {
int id = v.getId();
switch (id){
case R.id.addstudentimage:
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
break;
case R.id.btn_save:
String lname = lastname.getText().toString();
String fname = firstname.getText().toString();
String newCourse = course.getSelectedItem().toString();
if(!studImage.equals(R.drawable.user) && !lastname.equals(" ") && !firstname.equals("") && !course.getSelectedItem().toString().trim().equals(0)){
Intent intent = new Intent();
intent.putExtra("image", this.studImageUri);
intent.putExtra("lastname", lname);
intent.putExtra("firstname", fname);
intent.putExtra("course", newCourse);
this.setResult(Activity.RESULT_OK, intent);
Toast.makeText(getApplicationContext(), "New student successfully added!", Toast.LENGTH_SHORT).show();
finish();
}else{
Toast.makeText(getApplicationContext(), "Error in adding a new student!", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn_cancel:
studImage.setImageResource(R.drawable.user);
lastname.setText("");
firstname.setText("");
course.setSelection(0);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode != 0){
if(data != null){
studImageUri = data.getData();
studImage.setImageURI(studImageUri);
}
}else {
}
}
//on click listeners for the spinners
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int sid = parent.getId();
switch (sid){
case R.id.spinnerCourse:
selectedCourse = this.course.getItemAtPosition(position).toString();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
Student.java
public class Student {
Uri uriImage;
String studlname, studfname, studcourse;
//constructor
public Student(Uri uriImage, String studlname, String studfname, String studcourse) {
super();
this.uriImage = uriImage;
this.studlname = studlname;
this.studfname = studfname;
this.studcourse = studcourse;
}
//getters and setters
public Uri getUriImage() {
return uriImage;
}
public void setUriImage(Uri uriImage) {
this.uriImage = uriImage;
}
public String getStudlname() {
return studlname;
}
public void setStudlname(String studlname) {
this.studlname = studlname;
}
public String getStudfname() {
return studfname;
}
public void setStudfname(String studfname) {
this.studfname = studfname;
}
public String getStudcourse() {
return studcourse;
}
public void setStudcourse(String studcourse) {
this.studcourse = studcourse;
}
}
You used the wrong syntax, replace startActivity -> startActivityForResult
refer : https://developer.android.com/training/basics/intents/result

How to add items to a Listview without using a database?

I've already exhausted my efforts on this one but can't seem to find answers. So our instructor told us not to use Database. So the app is like filling up a form, asking for your picture, lastname, firstname and your course and then will display the items on your listview which is another activity.
How can I do this without using a database? Thanks! Please check out the my code below:
MainActivity.java
public class MainActivity extends AppCompatActivity {
ArrayList<Student> studentArrayList = new ArrayList<Student>();
StudentAdapter studentAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listview);
studentAdapter = new StudentAdapter(this, studentArrayList);
listView.setAdapter(studentAdapter);
}
//back button
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home){
onBackPressed();
return true;
}else if(id == R.id.action_add){
Intent add = new Intent(MainActivity.this, AddStudentActivity.class);
startActivity(add);
}
return super.onOptionsItemSelected(item);
}
//show add menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.add_menu, menu);
return true;
}
StudentAdapter.java
Context context;
ArrayList<Student> studentArrayList;
LayoutInflater inflater;
//contructor
public StudentAdapter(Context context, ArrayList<Student> studentArrayList) {
this.context = context;
this.studentArrayList = studentArrayList;
}
#Override
public int getCount() {
return studentArrayList.size();
}
#Override
public Object getItem(int position) {
return studentArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_layout, parent, false);
holder.image = (ImageView) convertView.findViewById(R.id.imageView);
holder.lname = (TextView) convertView.findViewById(R.id.textLName);
holder.fname = (TextView) convertView.findViewById(R.id.textFName);
holder.course = (TextView) convertView.findViewById(R.id.textCourse);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
//
holder.image.setImageResource(studentArrayList.get(position).getImage());
holder.lname.setText(studentArrayList.get(position).getLname());
holder.fname.setText(studentArrayList.get(position).getFname());
holder.course.setText(studentArrayList.get(position).getCourse());
return convertView;
}
private static class ViewHolder{
ImageView image;
TextView lname, fname, course;
}
AddStudentActivity.java
ImageView studentImage;
EditText studLname, studFname;
Button btnSave, btnCancel;
Spinner cboCourse;
String selectedCourse;
Uri imageUri;
private static final int PICK_IMAGE = 100;
ArrayList<Student> studentArrayList = new ArrayList<Student>();
StudentAdapter studentAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_student);
//
studentImage = (ImageView) findViewById(R.id.imageView2);
studLname = (EditText) findViewById(R.id.editText1);
studFname = (EditText) findViewById(R.id.editText2);
cboCourse = (Spinner) findViewById(R.id.spinner);
btnSave = (Button) findViewById(R.id.btnsave);
btnCancel = (Button) findViewById(R.id.btncancel);
cboCourse.setOnItemSelectedListener(this);
studentImage.setOnClickListener(this);
btnSave.setOnClickListener(this);
btnCancel.setOnClickListener(this);
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Unsaved Changes");
builder.setMessage("Are you sure you want to leave?");
builder.setPositiveButton("LEAVE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home){
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id){
case R.id.imageView2:
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
break;
case R.id.btnsave:
if(studLname.equals("") || studFname.equals("") || cboCourse.getSelectedItem().equals(0)){
Toast.makeText(getApplicationContext(), "Fields can not be empty!", Toast.LENGTH_SHORT).show();
}else{
//add a statement to add an item here
studentArrayList.add(studentImage.getResources().toString(), studLname.getText().toString(), studFname.getText().toString(), cboCourse.getSelectedItem());
// studentArrayList.add(studentImage.getBaseline(), studLname.getText().toString(), studFname.getText().toString(), cboCourse.getSelectedItem().toString());
Toast.makeText(getApplicationContext(), "Item successfully added!", Toast.LENGTH_SHORT).show();
Intent home = new Intent(AddStudentActivity.this, MainActivity.class);
startActivity(home);
studentAdapter.notifyDataSetChanged();
}
break;
case R.id.btncancel:
studLname.setText("");
studFname.setText("");
break;
}
}
//handles opening the camera
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == PICK_IMAGE){
imageUri = data.getData();
studentImage.setImageURI(imageUri);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//for the spinner
int sid = parent.getId();
switch (sid){
case R.id.spinner:
selectedCourse = this.cboCourse.getItemAtPosition(position).toString();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
Student.java
package com.example.studentinfoapplication;
import java.io.Serializable;
public class Student implements Serializable {
private int image;
private String lname, fname, course;
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
Student class
I added a global Arraylist to your Student Class.
public class Student implements Serializable {
public static ArrayList<Student> studentArrayList = new ArrayList<>();
private Uri image;
private String lname, fname, course;
public Student(){ //Add your constructor.
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
StudentAdapter studentAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listview);
Log.d("test", "students" + Student.studentArrayList);
if (Student.studentArrayList != null) {
studentAdapter = new StudentAdapter(this, Student.studentArrayList);
listView.setAdapter(studentAdapter);
}
}
AddStudentActivity
ArrayList<Student> studentArrayList = new ArrayList<Student>();
Remove this line at the top because we are referring to the global arraylist in Student class.
#Override
public void onClick(View v) {
int id = v.getId();
switch (id){
case R.id.imageView2:
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
break;
case R.id.btnsave:
if(!studLname.equals("") || !studFname.equals("") || !cboCourse.getSelectedItem().equals(0)){
String lname = studLname.getText().toString();
String fname = studFname.getText().toString();
String course = cboCourse.getSelectedItem().toString();
student.setLname(lname);
student.setFname(fname);
student.setCourse(course);
Student.studentArrayList.add(student); //Global arraylist
Log.d("test", "students:" + Student.studentArrayList);
Toast.makeText(getApplicationContext(), "Item successfully added!", Toast.LENGTH_SHORT).show();
Intent home = new Intent(AddStudentActivity.this, MainActivity.class);
startActivity(home);
}else{
Toast.makeText(getApplicationContext(), "Fields can not be empty!", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btncancel:
studLname.setText("");
studFname.setText("");
cboCourse.setSelection(0);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == PICK_IMAGE){
if (data != null) {
imageUri = data.getData();
}
student.setImage(imageUri);
studentImage.setImageURI(imageUri);
}
}
StudentAdapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_layout, parent, false);
holder.image = (ImageView) convertView.findViewById(R.id.imageView);
holder.lname = (TextView) convertView.findViewById(R.id.textLName);
holder.fname = (TextView) convertView.findViewById(R.id.textFName);
holder.course = (TextView) convertView.findViewById(R.id.textCourse);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
//
holder.lname.setText(studentArrayList.get(position).getLname());
holder.fname.setText(studentArrayList.get(position).getFname());
holder.image.setImageURI(studentArrayList.get(position).getImage());
holder.course.setText(studentArrayList.get(position).getCourse());
return convertView;
}
There can be couple of approaches you can try
a) Create singleton class and maintain a list of students that you add and then use the same singleton object in mainactivity to populate list.
b) create serializable/parcellable model having list of studuent ,every time you add the student and send this list to main activity and vice versa to use same model b/w two activities. This is just workaround apprach. I will prefer first one.

ListView lost focus

I am working on an app in android studio.
My app has a listview, whiche has Edittext , textview and checkbox in its row.
my proplem is when I have more than five items in my listvew, the listview lost focus, for example: when I press on checkbox on the 6th item , the textview shows me the name from the first item.
I wish I could explain my proplem very well.
This is my adapter:
public AdapterListView(Context context, int resource, ArrayList<ObjectPeople> arraypeople) {
super(context, resource);
this.mContext = context;
this.arrayPeople = arraypeople;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_listview, null);
holder = new ViewHolder();
holder.mission_name = (TextView) convertView.findViewById(R.id.mission_name);
holder.mission_time = (TextView) convertView.findViewById(R.id.mission_time);
holder.edit_time = (EditText) convertView.findViewById(R.id.edit_time);
holder.mission_image= (ImageView) convertView.findViewById(R.id.mission_image);
holder.cbm = (CheckBox) convertView.findViewById(R.id.checkbo);
convertView.setTag(holder);
holder.cbm.setOnClickListener(new View.OnClickListener() {
public void onClick(View v ) {
CheckBox cb = (CheckBox) v ;
final ObjectPeople person = arrayPeople.get(position);
if(cb.isChecked()) {
arrayPeople.get(position).checkbox= true;
int mis_tm=0;
try{ mis_tm= Integer.parseInt( holder.edit_time.getText().toString());}
catch (Exception e){
cb.setChecked(false);
Toast.makeText(mContext, "يرجى إدخال قيمة معينة", Toast.LENGTH_SHORT).show();}
person.time= mis_tm;
if(mis_tm>0&&mis_tm<1200){
holder.mission_name.setText("اسم المهمة: "+person.name);
holder.mission_time.setText( "مدة المهمة: "+ person.time );
holder.edit_time.setVisibility(View.GONE);}
else{
cb.setChecked(false);
Toast.makeText(mContext, "يرجى اختيار رقم حقيقي", Toast.LENGTH_SHORT).show();
}
}
else {
arrayPeople.get(position).checkbox= false;
holder.edit_time.setVisibility(View.VISIBLE);
}
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
final ObjectPeople person = arrayPeople.get(position);
holder.mission_name.setText("اسم المهمة: "+person.name);
holder.mission_time.setText( "مدة المهمة: ");
holder.mission_image.setImageResource(arrayPeople.get(position).image);
holder.edit_time.setId(position);
holder.edit_time.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
try {
if (!hasFocus) {
final int position = v.getId();
final EditText Caption = (EditText) v;
arrayPeople.get(position).time = Integer.parseInt(Caption.getText().toString());
}
}catch (Exception e){}
}
});
holder.cbm.setTag(arrayPeople);
return convertView;
}
#Override
public int getCount() {
return arrayPeople.size();
}
static class ViewHolder {
TextView mission_name;
TextView mission_time;
EditText edit_time;
ImageView mission_image;
CheckBox cbm;
}
}
and this select.java which contains the arraylist and list view:
public class select extends AppCompatActivity {
ArrayList<ObjectPeople> arrPeople;
ListView lvPeople;
AdapterListView adapter;
ObjectPeople person;
SharedPreferences settings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select);
settings = getApplicationContext().getSharedPreferences("shared", 0);
lvPeople= (ListView) findViewById(R.id.lvPeopl);
arrPeople=new ArrayList<>();
person = new ObjectPeople("حفظ قرآن", 0,false, R.drawable.quran_hifz_r);
arrPeople.add(person);
person = new ObjectPeople("تلاوة قرآن", 0 ,false,R.drawable.img);
arrPeople.add(person);
person = new ObjectPeople("قراءة كتاب", 0 , false,R.drawable.books_r);
arrPeople.add(person);
person = new ObjectPeople("دورات تطوير مهارات", 0 , false,R.drawable.courses_r);
arrPeople.add(person);
person = new ObjectPeople("رياضة", 15 , false,R.drawable.sport_r);
arrPeople.add(person);
final String[] misson_name = new String[1];
Button adf= (Button) findViewById(R.id.add_mission_out_btn);
adf.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View view = LayoutInflater.from(select.this).inflate(R.layout.add_mission_lyt,null);
final EditText add_name = (EditText) view.findViewById(R.id.add_mission_name);
AlertDialog.Builder builder = new AlertDialog.Builder(select.this);
builder.setMessage("add your mission")
.setView(view)
.setPositiveButton("إضافة", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
misson_name[0] = add_name.getText().toString();
arrPeople.add(new ObjectPeople(misson_name[0], 0, true,R.drawable.smile_small_r));
}
})
.setNegativeButton("إلغاء",null)
.setCancelable(false);
AlertDialog alert =builder.create();
alert.show();
}
});
adapter=new AdapterListView(this,R.layout.item_listview,arrPeople);
lvPeople.setAdapter(adapter);
checkButtonClick();
}
private void checkButtonClick() {
Button myButton = (Button) findViewById(R.id.btn_save);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences settings = getApplicationContext().getSharedPreferences("shared", 0);
int hours2=settings.getInt("hours",0)*60;
ArrayList<ObjectPeople> selected_missions = new ArrayList<>();
int missoins_time_calc=0;
for (int i = 0; i <arrPeople.size(); i++) {
if(arrPeople.get(i).checkbox==true){
selected_missions.add(arrPeople.get(i));
missoins_time_calc= missoins_time_calc + arrPeople.get(i).time;}
}
if (hours2 == missoins_time_calc){
Gson gson = new Gson();
String jsonText = gson.toJson(selected_missions);
SharedPreferences.Editor editor = settings.edit();
editor.putString("selected_array", jsonText);
editor.commit();
Intent intent = new Intent(select.this, yourprogram.class);
startActivity(intent);
overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
}
else if (hours2 > missoins_time_calc){
Toast.makeText(select.this, "بقي"+(-missoins_time_calc+ hours2)+" دقيقة ", Toast.LENGTH_SHORT).show();}
else if (hours2< missoins_time_calc){
Toast.makeText(select.this,"يوجد "+ (-hours2+missoins_time_calc)+" دقيقة زيادة على الوقت المخصص", Toast.LENGTH_SHORT).show();
}
/* ArrayList<missions> missionsList = dataAdapter.missionsList;
for(int i = 0; i< missionsList.size(); i++){
missions missions = missionsList.get(i);
if(missions.isSelected()){}}*/
}
});
}
}
I think the error is the way your arrayPeople List is being populated, if you say the sixth item gets you the first you can try reversing the order with
Collections.reverse(arrayPeople);
you can place this line of code below your holder.cbm.setOnClickListener on your adapter
Hope it helps.

android filter listview with edittext item come from database

i have a listview . in which item come from database listview has also checkbox . listview work fine . now i put a edittext on listview i wana filter my listview i try a lot . i do some thing like this.i use custom adapter.
this is my list data code
public class DataListActivity extends Activity {
ListView listView;
SQLiteDatabase sqLiteDatabase;
FoodDbHelper foodDbHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
private Button button1;
ListDataAdapter dataAdapter = null;
Button button;
DataProvider dataProvider;
ArrayList<HashMap<String, String>> namessList;
EditText inputSearch;
String search_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.data_list_layout);
inputSearch = (EditText)findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changes the Text
listDataAdapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(DataListActivity.this, button1);
//Inflating the Popup using xml file
popup.getMenuInflater()
.inflate(R.menu.popup_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
AlertDialog.Builder a_builder = new AlertDialog.Builder(DataListActivity.this);
a_builder.setMessage("Do You Want To Close This App !!!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), MainMenu.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("EXIT", true);
startActivity(intent);
//finish();
}
})
.setNegativeButton("No" , new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = a_builder.create();
alert.setTitle("Alert !!!");
alert.show();
// Toast.makeText(
// MainMenu.this,
// "You Clicked : " + item.getTitle(),
// Toast.LENGTH_SHORT
// ).show();
return true;
}
});
popup.show(); //showing popup menu
}
});
listView = (ListView) findViewById(R.id.list_View);
listDataAdapter = new ListDataAdapter(getApplicationContext(),
R.layout.row_layout) {
#Override
protected void showCheckedButton(int position, boolean value) {
// TODO Auto-generated method stub
final DataProvider item = (DataProvider) listDataAdapter
.getItem(position);
Log.i("", "");
item.setSelected(value);
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
responseText
.append("The following dishes were selected...\n");
ArrayList<DataProvider> list = listDataAdapter
.getSelectedIndexes();
int sum = 0;
for (int i = 0; i < list.size(); i++) {
DataProvider dataProvider = list.get(i);
sum = sum + dataProvider.getCalorie();
responseText.append("\n" + dataProvider.getName()
+ " : " + dataProvider.getCalorie()
+ " kcal"
);
}
Toast.makeText(getApplicationContext(), ""+responseText+"\n"+"................................."
+"\n"+"Total Calories In Your Menu Is : " +sum,
Toast.LENGTH_LONG).show();
}
});
}
};
listView.setAdapter(listDataAdapter);
foodDbHelper = new FoodDbHelper(getApplicationContext());
sqLiteDatabase = foodDbHelper.getReadableDatabase();
cursor = foodDbHelper.getInformations(sqLiteDatabase);
if (cursor.moveToFirst()) {
do {
String name, quantity, fat, protein, sugar, carbohydrates;
boolean selected = false;
String names = null;
Integer calorie;
name = cursor.getString(0);
quantity = cursor.getString(1);
calorie = Integer.valueOf(cursor.getString(2));
fat = cursor.getString(3);
protein = cursor.getString(4);
sugar = cursor.getString(5);
carbohydrates = cursor.getString(6);
DataProvider dataProvider = new DataProvider(name, quantity,
calorie, fat, protein, sugar, carbohydrates, names, selected);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(getApplicationContext(),
"dish name is : " + name, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),
Detail.class);
}
});
}
public void gobackk(View view) {
Intent intent = new Intent(this, MainMenu.class);
startActivity(intent);
}
}
this is custom adapter code
public abstract class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
boolean index[];
public ListDataAdapter(Context context, int resource) {
super(context, resource);
index = new boolean[list.size()];
}
static class LayoutHandler {
TextView name, quantity, calorie, fat, protein, sugar, carbohydrates;
CheckBox names;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
index = new boolean[list.size()];
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout, parent, false);
layoutHandler = new LayoutHandler();
layoutHandler.name = (TextView) row
.findViewById(R.id.text_dish_name);
layoutHandler.quantity = (TextView) row
.findViewById(R.id.text_dish_quantity);
layoutHandler.calorie = (TextView) row
.findViewById(R.id.text_dish_calorie);
layoutHandler.fat = (TextView) row.findViewById(R.id.text_dish_fat);
layoutHandler.protein = (TextView) row
.findViewById(R.id.text_dish_protein);
layoutHandler.sugar = (TextView) row
.findViewById(R.id.text_dish_sugar);
layoutHandler.carbohydrates = (TextView) row
.findViewById(R.id.text_dish_carbohydrates);
layoutHandler.names = (CheckBox) row.findViewById(R.id.checkBox1);
row.setTag(layoutHandler);
} else {
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider) this.getItem(position);
layoutHandler.name.setText(dataProvider.getName());
layoutHandler.quantity.setText(dataProvider.getQuantity());
layoutHandler.calorie
.setText(String.valueOf(dataProvider.getCalorie()));
layoutHandler.fat.setText(dataProvider.getFat());
layoutHandler.protein.setText(dataProvider.getProtein());
layoutHandler.sugar.setText(dataProvider.getSugar());
layoutHandler.carbohydrates.setText(dataProvider.getCarbohydrates());
//layoutHandler.names.setChecked(dataProvider.isSelected());
layoutHandler.names.setTag(position);
layoutHandler.names.setChecked(index[position]);
layoutHandler.names
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
int pos = (Integer) buttonView.getTag();
index[pos] = isChecked;
showCheckedButton(position, isChecked);
}
});
return row;
}
public ArrayList<DataProvider> getSelectedIndexes() {
int size = list.size();
ArrayList<DataProvider> selectedItems = new ArrayList<DataProvider>();
for (int i = 0; i < size; i++) {
DataProvider cItem = (DataProvider) list.get(i);
if (index[i]) {
selectedItems.add(cItem);
}
}
return selectedItems;
}
protected abstract void showCheckedButton(int position, boolean value);
}

How to put a ListView in Fragment

I have a very big problem, well for me it is... So here it is.
I have a fragment that contains a TextView and a Button, when I click the button and choose contacts and I need there numbers and names stored in a ListView and to the right of the name and number I want a button that will be there so that the choosen contact can be deleted... I don't know if you understand, so in the ListView all that will be stored as a single item, NAME than under the name is the contact's NUMBER and on the right side is the delete button... I know that I have to use custom adapter, but I just don't get it.
Here is the code for my adapter
private class MessageAdapter extends ArrayAdapter<Message> {
public MessageAdapter(ArrayList<Message> messages) {
super(getActivity(), 0, messages);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If we weren't given a view, inflate one
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(
R.layout.list_item_contact, null);
}
// Configure the view for this Contact
Message m = getItem(position);
TextView nameTextView = (TextView) convertView
.findViewById(R.id.contact_list_item_nameTextView);
nameTextView.setText(m.getNames());
TextView numberTextView = (TextView) convertView
.findViewById(R.id.contact_list_item_numberTextView);
numberTextView.setText(m.getNumbers());
return convertView;
}
}
and here is what I try to do to put the contact in the list...
if (requestCode == REQUEST_CONTACT) {
Uri result = data.getData();
Log.v("Contact", "Got a result: " + result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for phone numbers for the selected contact id
Cursor c = getActivity().getContentResolver()
.query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + "=?",
new String[] { id },
ContactsContract.Contacts.DISPLAY_NAME);
int phoneIdx = c.getColumnIndex(Phone.NUMBER);
int phoneType = c.getColumnIndex(Phone.TYPE);
int nameIdx = c.getColumnIndex(Phone.DISPLAY_NAME);
if (c.getCount() == 1) {
c.moveToFirst();
// contact has a single phone number, so there's no need to
// display a second dialog
mName = c.getString(nameIdx);
mNumber = c.getString(phoneIdx);
// Ovo radim ovako da bih mogao da ih upisem u fajl
mMessage.setmNames(mName);
mMessage.setmNumbers(mNumber);
((MessageAdapter) getListAdapter()).notifyDataSetChanged();
c.close();
}
}
So when I get the number and name of the selected contact I want to add it to the list, but I always get only the last selected number and name... Hope you understand what I mean, thank you.
And here are the onCreate and onCreateView, just in case:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_message, container, false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Ovo ispod omogucava da se ugase sve activities i da se vrati na
// pocetnu valjda
// Zavisi sta smo stavili da nam bude parent class u xml manifest
if (NavUtils.getParentActivityName(getActivity()) != null) {
getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
mTextField = (EditText) v.findViewById(R.id.message_text);
mTextField.setText(mMessage.getmText());
mTextField.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
mMessage.setmText(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
mAddContactButton = (Button) v.findViewById(R.id.message_contact);
mAddContactButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(i, REQUEST_CONTACT);
}
});
return v;
}
and onCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMessage = new Message();
UUID messageId = (UUID) getArguments()
.getSerializable(EXTRA_MESSAGE_ID);
mMessage = MessageLab.get(getActivity()).getMessage(messageId);
mMessages = MessageLab.get(getActivity()).getMessages();
MessageAdapter adapter = new MessageAdapter(mMessages);
setListAdapter(adapter);
setHasOptionsMenu(true);
}
the class
public class MessageFragment extends ListFragment {
private ArrayList<String> names_list = new ArrayList<String>();
private ArrayList<String> numbers_list = new ArrayList<String>();
private ArrayList<Message> mMessages;
private Message mMessage;
private EditText mTextField;
private Button mAddContactButton;
private String mName, mNumber;
private String build_name="", build_number="";
public static final String EXTRA_MESSAGE_ID = "com.falca.emergencymessage.message_id";
private static final int REQUEST_CONTACT = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMessage = new Message();
UUID messageId = (UUID) getArguments()
.getSerializable(EXTRA_MESSAGE_ID);
mMessage = MessageLab.get(getActivity()).getMessage(messageId);
mMessages = MessageLab.get(getActivity()).getMessages();
MessageAdapter adapter = new MessageAdapter(mMessages);
setListAdapter(adapter);
setHasOptionsMenu(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (NavUtils.getParentActivityName(getActivity()) != null) {
NavUtils.navigateUpFromSameTask(getActivity());
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#TargetApi(11)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_message, container, false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Ovo ispod omogucava da se ugase sve activities i da se vrati na
// pocetnu valjda
// Zavisi sta smo stavili da nam bude parent class u xml manifest
if (NavUtils.getParentActivityName(getActivity()) != null) {
getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
mTextField = (EditText) v.findViewById(R.id.message_text);
mTextField.setText(mMessage.getmText());
mTextField.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
mMessage.setmText(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
mAddContactButton = (Button) v.findViewById(R.id.message_contact);
mAddContactButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(i, REQUEST_CONTACT);
}
});
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK)
return;
if (requestCode == REQUEST_CONTACT) {
Uri result = data.getData();
Log.v("Contact", "Got a result: " + result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for phone numbers for the selected contact id
Cursor c = getActivity().getContentResolver()
.query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + "=?",
new String[] { id },
ContactsContract.Contacts.DISPLAY_NAME);
int phoneIdx = c.getColumnIndex(Phone.NUMBER);
int phoneType = c.getColumnIndex(Phone.TYPE);
int nameIdx = c.getColumnIndex(Phone.DISPLAY_NAME);
if (c.getCount() > 1) { // contact has multiple phone numbers
final CharSequence[] numbers = new CharSequence[c.getCount()];
int i = 0;
if (c.moveToFirst()) {
mName = c.getString(nameIdx);
while (!c.isAfterLast()) { // for each phone number, add it
// to the numbers array
String type = (String) Phone.getTypeLabel(
this.getResources(), c.getInt(phoneType), ""); // insert
// a
// type
// string
// in
// front
// of
// the
// number
String number = type + ": " + c.getString(phoneIdx);
numbers[i++] = number;
c.moveToNext();
}
// build and show a simple dialog that allows the user to
// select a number
AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
builder.setTitle(R.string.select_contact_phone_number_and_type);
builder.setItems(numbers,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int item) {
mNumber = (String) numbers[item];
int index = mNumber.indexOf(":");
mNumber = mNumber.substring(index + 2);
// Ovo radim ovako da bih mogao da ih upisem
// u fajl
build_name += mName + ";";
build_number += mNumber + ";";
mMessage.setmNames(build_name);
mMessage.setmNumbers(build_number);
((MessageAdapter) getListAdapter()).notifyDataSetChanged();
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(getActivity());
alert.show();
} else
Log.w("Contact", "No results");
} else if (c.getCount() == 1) {
c.moveToFirst();
// contact has a single phone number, so there's no need to
// display a second dialog
mName = c.getString(nameIdx);
mNumber = c.getString(phoneIdx);
// Ovo radim ovako da bih mogao da ih upisem u fajl
build_name += mName + ";";
build_number += mNumber + ";";
mMessage.setmNames(build_name);
mMessage.setmNumbers(build_number);
((MessageAdapter) getListAdapter()).notifyDataSetChanged();
c.close();
}
}
}
#Override
public void onResume() {
super.onResume();
// Update the list view
((MessageAdapter) getListAdapter()).notifyDataSetChanged();
}
//MessageAdapter sluzi za rucno pravljenje liste poruka
private class MessageAdapter extends ArrayAdapter<Message> {
public MessageAdapter(ArrayList<Message> messages) {
super(getActivity(), 0, messages);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If we weren't given a view, inflate one
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(
R.layout.list_item_contact, null);
}
// Configure the view for this Message
Message m = getItem(position);
TextView nameTextView = (TextView) convertView
.findViewById(R.id.contact_list_item_nameTextView);
nameTextView.setText(m.getmNames());
TextView numberTextView = (TextView) convertView
.findViewById(R.id.contact_list_item_numberTextView);
numberTextView.setText(m.getmNumbers());
return convertView;
}
}
public static MessageFragment newInstance(UUID messageId) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_MESSAGE_ID, messageId);
MessageFragment fragment = new MessageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onPause() {
super.onPause();
MessageLab.get(getActivity()).saveMessages();
}
}
It seems that you always update the same single mMessage field.
mMessage.setmNames(build_name);
mMessage.setmNumbers(build_number);
When you have a new entry you have to update you ArrayList mMessages. Add an entry to the list. The adapter always has this arrayList as data source so you have to update this arrayList.
So for every entry create a new message and add it to the mMessages array list.

Categories

Resources