I am working on an application that has a ListView of movies. The list is declared as an array in strings.xml. It has elements, Title, Gross and Date Released. When a row is long clicked, it brings up a context menu that allows the user to edit said row or delete it. When the user picks Edit, he/she is brought to a 2nd screen with 3 Edit Text corresponding to Title, Gross and Date. The EditText fields are initialized with the data from the clicked row. Here is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] titleList = getResources().getStringArray(R.array.title_array);
String[] grossList = getResources().getStringArray(R.array.gross_array);
String[] dateList = getResources().getStringArray(R.array.date_array);
results = new ArrayList<Lab8_082588FetchDetails>();
for (int i = 0; i < titleList.length; i++) {
Lab8_082588FetchDetails sr = new Lab8_082588FetchDetails();
sr.setTitle(titleList[i]);
sr.setGross(grossList[i]);
sr.setDate(dateList[i]);
results.add(sr);
}
adapter = new SampleCustomAdapter(results);
setListAdapter(adapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
registerForContextMenu(lv);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
// places the contents of the XML to the menu
inflater.inflate(R.menu.context_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
switch (item.getItemId()) {
case R.id.delete:
results.remove(info.position);
adapter.notifyDataSetChanged();
return true;
case R.id.edit:
System.out.println(info.id);
System.out.println(info.position);
Intent newData = new Intent(Lab8_082588.this, Lab8_082588Edit.class);
results.get(info.position);
TextView movieTitle = (TextView) findViewById(R.id.title);
TextView movieGross = (TextView) findViewById(R.id.gross);
TextView movieDate = (TextView) findViewById(R.id.date);
String startTitle = movieTitle.getText().toString();
String startGross = movieGross.getText().toString();
String startDate = movieDate.getText().toString();
newData.putExtra(Lab8_082588Edit.TITLE_STRING, startTitle);
newData.putExtra(Lab8_082588Edit.GROSS_STRING, startGross);
newData.putExtra(Lab8_082588Edit.DATE_STRING, startDate);
startActivityForResult(newData, Lab8_082588.EDIT_MOVIE);
return true;
default:
return super.onContextItemSelected(item);
}
}
For the Edit screen:
public class Lab8_082588Edit extends Activity {
public static final String TITLE_STRING = "TITLE_STRING";
public static final String GROSS_STRING = "GROSS_STRING";
public static final String DATE_STRING = "DATE_STRING";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addedit);
initialize();
}
private void initialize() {
// TODO Auto-generated method stub
Intent prepopulate = getIntent();
EditText movieTitle = (EditText) findViewById(R.id.etTitle);
EditText movieGross = (EditText) findViewById(R.id.etGross);
EditText movieDate = (EditText) findViewById(R.id.etDate);
String startTitle = prepopulate.getStringExtra(Lab8_082588Edit.TITLE_STRING);
String startGross = prepopulate.getStringExtra(Lab8_082588Edit.GROSS_STRING);
String startDate = prepopulate.getStringExtra(Lab8_082588Edit.DATE_STRING);
movieTitle.setText(startTitle);
movieGross.setText(startGross.replaceAll(",", "").replace("$", ""));
movieDate.setText(startDate);
}
My FetchDetails class
public class Lab8_082588FetchDetails implements Comparable<Lab8_082588FetchDetails> {
private String title;
private String gross;
private String date;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getGross() {
return gross;
}
public void setGross(String gross) {
this.gross = gross;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
#Override
public int compareTo(Lab8_082588FetchDetails another) {
// TODO Auto-generated method stub
return title.compareTo(another.title);
}
}
My Adapter:
private class SampleCustomAdapter extends BaseAdapter {
public SampleCustomAdapter(ArrayList<Lab8_082588FetchDetails> movies) {
internalList = movies;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return internalList.size();
}
#Override
public Object getItem(int index) {
// TODO Auto-generated method stub
return internalList.get(index);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View view;
if (convertView == null) {
view = inflater.inflate(R.layout.row, null);
} else {
view = convertView;
}
// extract the views to be populated
TextView title = (TextView) view.findViewById(R.id.title);
TextView gross = (TextView) view.findViewById(R.id.gross);
TextView date = (TextView) view.findViewById(R.id.date);
// extract the object that will fill these
Lab8_082588FetchDetails movie = internalList.get(position);
title.setText(movie.getTitle());
date.setText(movie.getDate());
gross.setText(movie.getGross());
// return the view
return view;
}
}
My problem is that, indeed, the Edit Texts get populated, but only with the data from the first item in the entire list (e.g. Titanic is first on the list, and is the only one being populated). Even if I click the nth row movie in the listview, Titanic is still the one being retrieved. How do I solve this?
Edit: I realize that somehow, the code is only considering the first element of the list. How do I access the elements of the other rows?
I realize that somehow, the code is only considering the first
element of the list. How do I access the elements of the other rows?
You should never do a search with findViewById for items which are in a ListView row. In the onContextItemSelected callback you have the position of the element clicked so you could use it to get the data associated with this row:
case R.id.edit:
Intent newData = new Intent(Lab8_082588.this, Lab8_082588Edit.class);
// I hope you implemented the adapter correctly
Lab8_082588FetchDetails item = (Lab8_082588FetchDetails) getListView().getItemAtPosition(info.position);
String startTitle = item.getTitle();
String startGross = item.getGross();
String startDate = item.getDate();
newData.putExtra(Lab8_082588Edit.TITLE_STRING, startTitle);
newData.putExtra(Lab8_082588Edit.GROSS_STRING, startGross);
newData.putExtra(Lab8_082588Edit.DATE_STRING, startDate);
startActivityForResult(newData, Lab8_082588.EDIT_MOVIE);
return true;
Related
I saw that this was asked once at How to get current timestamp in Android without it updating like a clock, but it wasn't marked as answered and I don't understand the few suggestions that were given.
Anyway, I'm beyond new to Java and was following a tutorial on making a simple todo app (https://guides.codepath.com/android/Basic-Todo-App-Tutorial) and I decided to try to add a timestamp to each list item. I got as far as that it adds the current time, but its not static. The time keeps updating anytime I try and add a new item or if I close and reopen the app. I can't figure out/find the answer anywhere.
This is what I'm getting:
This is what I want:
Here's the code.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ArrayList<String> items;
private ArrayAdapter<String> TodoAdapter;
private ListView lvItems;
private void readItems() {
File filesDir = getFilesDir();
File todoFile = new File(filesDir, "todo.txt");
try {
items = new ArrayList<String>(FileUtils.readLines(todoFile));
} catch (IOException e) {
items = new ArrayList<String>();
}
}
private void writeItems() {
File filesDir = getFilesDir();
File todoFile = new File(filesDir, "todo.txt");
try {
FileUtils.writeLines(todoFile, items);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items = new ArrayList<String>();
readItems();
TodoAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_2, android.R.id.text1, items);
lvItems = (ListView) findViewById(R.id.lvItems);
lvItems.setAdapter(TodoAdapter);
// Setup remove listener method call
setupListViewListener();
}
// Attaches a long click listener to the listview
// Removes item on long press
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int pos, long id) {
// Remove the item within array at position
items.remove(pos);
// Refresh the adapter
TodoAdapter.notifyDataSetChanged();
writeItems();
// Return true consumes the long click event (marks it handled)
return true;
}
});
}
public void onAddItem(View v) {
EditText etNewItem = (EditText) findViewById(R.id.etNewItem);
String itemText = etNewItem.getText().toString();
TodoAdapter.add(itemText); // Add items to new Adapter type
etNewItem.setText("");
writeItems();
}
}
TodoAdapter.java
public class TodoAdapter extends ArrayAdapter<Todo> {
public TodoAdapter(Context context, ArrayList<Todo> items) {
super(context, 0, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Todo item = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_2, parent, false);
}
TextView text1 = (TextView) convertView.findViewById(android.R.id.text1);
TextView text2 = (TextView) convertView.findViewById(android.R.id.text2);
text1.setText(item.itemText);
text2.setText(item.getCreationTimeString());
text2.setTextSize(10);
return convertView;
}
}
Todo.java
public class Todo {
String itemText;
private Date creationTime;
public Todo(String text) {
this.itemText = text;
this.creationTime = new Date();
}
public String getCreationTimeString() {
return new SimpleDateFormat("h:mm a").format(creationTime);
}
}
Any help provided would be extremely appreciated. Also please keep in mind that I have literally almost no understanding of what I'm doing. :)
The time keeps updating anytime I try and add a new item
Right, that is because the Adapter is recalling new Date(), which will always get the current time that the View is created for an Adapter item.
It would appear that you want items to be associated with a time at which they are created. If that is the case, then you can make a class
public class Todo {
String itemText;
private Date creationTime;
public Todo(String text) {
this.itemText = text;
this.creationTime = new Date();
}
public String getCreationTimeString() {
return new SimpleDateFormat("h:mm a").format(creationTime);
}
}
Then, you should probably make an ArrayAdapter<Todo> to display these items and display something like this
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Todo item = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_2, parent, false);
}
TextView text1 = (TextView) convertView.findViewById(android.R.id.text1);
TextView text2 = (TextView) convertView.findViewById(android.R.id.text2);
text1.setText(item.itemText);
text2.setText(item.getCreationTimeString());
text2.setTextSize(10);
return convertView;
}
And update the add method
public void onAddItem(View v) {
EditText etNewItem = (EditText) findViewById(R.id.etNewItem);
String itemText = etNewItem.getText().toString();
itemsAdapter.add(new Todo(itemText)); // Add items to new Adapter type
etNewItem.setText("");
writeItems();
}
My android app consists of a gridview with an image and a text below it. I am passing a array of strings into the textview. I want the edittext field to act as a search bar and filter the results.I have seen other questions relating this but they seem to filter an arraylist which is passed into a Listview. How do i filter an array of strings in a gridview?
I know i should add a a TextWatcher to listen for text changes on the EditText but after that how do i filter my data?
Here is my code
Mainactivity.java
public class MainActivity extends Activity {
EditText inputSearch;
GridView grid;
public static String[] Sname = {
"one",
"two",
"three",
"four",
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CustomGrid adapter = new CustomGrid(MainActivity.this, Sname);
grid = (GridView) findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at " + Sname[+position], Toast.LENGTH_SHORT).show();
}
});
inputSearch = (EditText) findViewById(R.id.editText);
}
}
CustomGrid.java
public class CustomGrid extends BaseAdapter {
private Context mContext;
private final String[] Sname;
public CustomGrid(Context c,String[] Sname) {
mContext = c;
this.Sname = Sname;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Sname.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
TextView textView = (TextView) grid.findViewById(R.id.grid_text);
ImageView imageView = (ImageView)grid.findViewById(R.id.grid_image);
textView.setText(Sname[position]);
imageView.setImageResource(R.mipmap.image1);
return grid; }}
You can add your adapter ie CustomGrid a filter(String) method.
You also add a field String [] toDisplay in your adapter.
In your constructor you add toDisplay = Sname and in all your other methos you replace Snameby toDisplay
In the filter method create a new string array with only the string from Sname that match the desired string. Set this new array to toDisplay.
Then call the notifyDataSetChanged method on your CustomGrid
Example of filtering method :
public void filter(String toMatch) {
List<String> matches = new ArrayList<String>();
for (String string : Sname) {
if (string.matches(toMatch)) {//on whatever mathcing you feel to use
matches.add(string);
}
}
toDisplay = new String[matches.size()];
toDisplay = matches.toArray(toDisplay);
notifyDataSetChanged(); //update your grid view
}
I have this following class which when runs and comes to a certain line in the class the application crashes. If i comment out that line the application runs well. When i look at the logcat i don't find any CausedBy Text. So can not figure out the cause of this crash. Someone please help me out to solve this.
public class Secondscreen extends Activity {
int total=0;
final ArrayList<Listitem> arrayList=new ArrayList<Listitem>();
BaseAdapter adapter =null;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondscreen);
ListView lv= (ListView) findViewById(R.id.listView1);
final TextView showtotal = (TextView) findViewById(R.id.totalprice);
final Button thirdBtn = (Button) findViewById(R.id.third);
final Controller aController = (Controller) getApplicationContext();
final int cartSize = aController.getCart().getCartSize();
//Addition of item to arraylist
if(cartSize >0)
{
for(int i=0;i<cartSize;i++)
{
String pName = aController.getCart().getProducts(i).getProductName();
int pPrice = aController.getCart().getProducts(i).getProductPrice();
int pQuantity = aController.getCart().getProducts(i).getProductQuantity();
String pDisc = aController.getCart().getProducts(i).getProductDesc();
total = total + pPrice;
Listitem item=new Listitem(pName, pPrice, pDisc, pQuantity);
Log.e("quantity", ""+pQuantity);
Log.e("Intem's quantity", ""+item.getQuantity());
arrayList.add(item);
Log.e("Arraylist item quantity", ""+arrayList.get(i).getQuantity());
}
showtotal.setText(""+total);
}
adapter= new BaseAdapter(){
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView(final int position, View view, ViewGroup viewgroup) {
if (view == null) {
view=inflater.inflate(R.layout.pattern, null);
}
TextView tv=(TextView) view.findViewById(R.id.nameview);
TextView tv2=(TextView) view.findViewById(R.id.pdesc);
TextView tv3=(TextView) view.findViewById(R.id.priceView);
TextView tv4=(TextView) view.findViewById(R.id.quantityView);
Button btn=(Button) view.findViewById(R.id.patternButton);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int tempstore=arrayList.get(position).getPrice();
total=total-tempstore;
arrayList.remove(position);
showtotal.setText(""+total);
ModelProducts tempProductObject = aController.getProducts(position);
aController.getCart().removeProducts(tempProductObject);
adapter.notifyDataSetChanged();
int cartSize2 = aController.getCart().getCartSize();
}
});
tv.setText(arrayList.get(position).getName());
tv2.setText(""+arrayList.get(position).getPrice());
tv3.setText(arrayList.get(position).getDesc());
tv4.setText(arrayList.get(position).getQuantity()); //<-this is the line which when gets executed causes the application to crash.
return view;
}
};
lv.setAdapter(adapter);
}
}
yes getQuantity() returns an int value
So change this
tv4.setText(arrayList.get(position).getQuantity());
to
tv4.setText(String.valueOf(arrayList.get(position).getQuantity()));
What happens is setText(int) looks for a Resource with the int value if not found you end up getting ResourceNotFoundException
What you want is setText(CharacterSequence) so you need use String.valueof(intvalue)
I want to implement a to-do list application. I have three activities: one main activity, one adding activity and one editing activity. In my main activity there is a add button and a listview that shows the to-do items. When I click add button, adding activity is executed. In this activity,there is an edittext for the task, a datepicker and a spinner for priority level. When ok button is clicked, all these entred values are sent to main activity's listview as a line. And, when click an item on this list, editing activity is executed and user can change the values. However, in my code, when user enters the values, I can reach them in my custom adapter class but I could't display them in listview. Listview remains empty. How can i fix my code?
main activity:
public class MainActivity extends Activity {
protected static final String edits = "mainTask";
private ToDoItemAdapter listAdapter;
//private ToDoItemAdapter myCustomAdapter;
//private ArrayList<String> listString;
public ArrayList<ToDoItem> listItems;
public static final int ADD_TASKS = 1;
public static final int EDIT_TASKS = 2;
Button button;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
setListener();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void initUI() {
getViewReferences();
initializeToDoList();
}
private void setListener() {
// TODO Auto-generated method stub
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent addTaskIntent = new Intent(MainActivity.this, AddActivity.class);
startActivityForResult(addTaskIntent, ADD_TASKS);
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
System.out.println(arg2);
ToDoItemAdapter myAdapter = new ToDoItemAdapter(MainActivity.this,R.layout.editing_task,listItems);
listView.setAdapter(myAdapter);
Intent editTaskIntent = new Intent(MainActivity.this, EditingTask.class);
//editTaskIntent.putExtra("mainTask", arg2);
startActivityForResult(editTaskIntent, EDIT_TASKS);
}
});
}
private void getViewReferences() {
// TODO Auto-generated method stub
button = (Button) findViewById(R.id.addButton);
listView = (ListView) findViewById(R.id.listView);
}
private void initializeToDoList() {
// TODO Auto-generated method stub
listItems = new ArrayList<ToDoItem>();
//listString = new ArrayList<String>();
listAdapter = new ToDoItemAdapter(MainActivity.this, R.layout.activity_main, listItems);
listView.setAdapter(listAdapter);
View noTaskView = findViewById(R.id.emptyToDoList);
listView.setEmptyView(noTaskView);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case ADD_TASKS:
updateToDoList(data);
break;
case EDIT_TASKS:
break;
default:
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void updateToDoList(Intent data) {
// TODO Auto-generated method stub
String task = AddActivity.tasks;
ArrayList<String> list = data.getStringArrayListExtra(task);
String addedTask = list.get(0);
String addedDeadline = list.get(1);
String addedPriority = list.get(2);
ToDoItem item = new ToDoItem(addedTask, addedDeadline ,"0", addedPriority);
listItems.add(item);
//listString.add(addedTask + " " + addedDeadline + " " + addedPriority);
Log.w("Items:",listItems.get(0).getTask());
//Log.w("String:",listString.get(0));
listAdapter.notifyDataSetChanged();
}
}
ToDoItemAdapter class:
public class ToDoItemAdapter extends ArrayAdapter<ToDoItem> {
Context context;
private int resource;
ArrayList<ToDoItem> todoItem;
public ToDoItemAdapter(Context context, int resource, ArrayList<ToDoItem> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
this.todoItem = objects;
}
#Override
public ToDoItem getItem(int position) {
return this.todoItem.get(position);
}
#Override
public int getCount() {
return this.todoItem.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
if (convertView == null)
{
/*todoView = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li;
li = (LayoutInflater)getContext().getSystemService(inflater);
li.inflate(resource, todoView, true);
*/
LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(resource, parent, false);
}
//LinearLayout todoView;
ToDoItem todo = getItem(position);
String taskString = todo.getTask();
Log.w("task:", taskString);
String dateString = todo.getDeadline();
String priorityString = todo.getPriority();
String itemRow = taskString + " " + dateString + " " + priorityString;
return row;
}
}
Adding class:
public class AddActivity extends Activity{
private String[] states;
private Spinner spinner;
int position1;
String priority;
EditText etDate;
Button change_date;
final int Date_Dialog_ID=0;
int cDay,cMonth,cYear; // this is the instances of the current date
Calendar cDate;
int sDay,sMonth,sYear; // this is the instances of the entered date
protected static final String tasks = "addingTask";
private static final String LOG_TAG = "addingTaskActivity";
MainActivity main;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
initUI();
showDatePicker();
showPriorityLevel();
}
private void showPriorityLevel() {
// TODO Auto-generated method stub
states = getResources().getStringArray(R.array.priority_level);
spinner = (Spinner) findViewById(R.id.priority_spinner);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, states);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
position1 = spinner.getSelectedItemPosition();
switch(position1)
{
case 0: priority = "0";
break;
case 1: priority = "1";
break;
case 2: priority = "2";
break;
case 3: priority = "3";
break;
case 4: priority = "4";
break;
case 5: priority = "5";
break;
case 6: priority = "6";
break;
case 7: priority = "7";
break;
case 8: priority = "8";
break;
case 9: priority = "9";
break;
default: break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
private void showDatePicker() {
// TODO Auto-generated method stub
etDate=(EditText)findViewById(R.id.EditText01);
change_date=(Button)findViewById(R.id.Button01);
change_date.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//triggers the DatePickerDialog
showDialog(Date_Dialog_ID);
}
});
//getting current date
cDate=Calendar.getInstance();
cDay=cDate.get(Calendar.DAY_OF_MONTH);
cMonth=cDate.get(Calendar.MONTH);
cYear=cDate.get(Calendar.YEAR);
//assigning the edittext with the current date in the beginning
sDay=cDay;
sMonth=cMonth;
sYear=cYear;
updateDateDisplay(sYear,sMonth,sDay);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case Date_Dialog_ID:
return new DatePickerDialog(this, onDateSet, cYear, cMonth,
cDay);
}
return null;
}
private void updateDateDisplay(int year,int month,int date) {
// TODO Auto-generated method stub
etDate.setText(date+"-"+(month+1)+"-"+year);
}
private OnDateSetListener onDateSet=new OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
sYear=year;
sMonth=monthOfYear;
sDay=dayOfMonth;
updateDateDisplay(sYear,sMonth,sDay);
}
};
private void initUI() {
// TODO Auto-generated method stub
setContentView(R.layout.adding_task);
final EditText editTextTask = (EditText) findViewById(R.id.edit_text_task);
Button OKbutton = (Button) findViewById(R.id.ok_Button);
final EditText editTextDate = (EditText) findViewById(R.id.EditText01);
OKbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ArrayList<String> addedDatas = new ArrayList<String>();
String addingTask = editTextTask.getText().toString();
String deadline = editTextDate.getText().toString();
//String concatenate = priority + " " + addingTask + " " + deadline;
Intent myIntent = new Intent();
addedDatas.add(addingTask);
addedDatas.add(deadline);
addedDatas.add(priority);
myIntent.putExtra("addingTask", addedDatas);
setResult(Activity.RESULT_OK, myIntent);
finish();
}
});
}
}
ToDoItem class
public class ToDoItem {
String task;
String deadline;
String status;
String priority;
public ToDoItem(String task, String deadline, String status, String priority) {
super();
this.task = task;
this.deadline = deadline;
this.status = status;
this.priority = priority;
}
public String getTask() {
return task;
}
public String getDeadline() {
return deadline;
}
public String getStatus() {
return status;
}
public String getPriority() {
return priority;
}
#Override
public String toString() {
return priority + " " + task + " " + deadline + " " + status;
}
What you should do, is make sure that the Adding Activity can access the ToDoItem Array that is used to populate the ListView in the Main Activity. Then it can just add to or modify this list directly. Then you can call a notifyAdapters() in onStart() of MainActivity to check for updates whenever it becomes visible.
I have a custom listview with custom adapter extending BaseAdapter if i add items to this list view in OnCreate method they show up in list, but if i add them from other methods like a packet listener method then items do not show up , on the screen below this listview there is a textbox if i select textbox to entertext using virtual keyboard immediately the listview gets populated with previousely inserted items which didnt show up. This activity is a chat window basically
I have tried calling notifyDataSetChanged, invalidate on Layout or on listview but nothing helped.
What i think is i need to have a way to refresh activity , as same thing must be happening when the virtual keyboard pops up .
Help will be highly appreciated
Thanks
Code:
package com.arounds;
public class ChatActivity extends Activity implements OnClickListener,PacketListener{
private ListView chatView;
private ChatListViewCustomAdapter adapter;
private String user;
private XMPPConnection connection;
private Conversation conv;
private ChatActivity selfRef = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_win);
AroundApplication app = (AroundApplication) this.getApplicationContext();
connection = app.getConnection();
chatView = (ListView) findViewById(R.id.conversationList);
adapter = new ChatListViewCustomAdapter(this);
chatView.setAdapter(adapter);
// set send btn listener
ImageButton send = (ImageButton)findViewById(R.id.imgBtnSend);
send.setOnClickListener(this);
ImageButton smiley = (ImageButton)findViewById(R.id.imgBtnSmiley);
smiley.setOnClickListener(this);
// get the parameter passed by previouse activity
Bundle b = this.getIntent().getExtras();
String temp = b.getString("user");
user = temp;
TextView v = (TextView)this.findViewById(R.id.txtViewTitle_chat);
v.setText(temp);
v = (TextView)this.findViewById(R.id.txtViewDescription_chat);
temp = b.getString("status");
v.setText(temp);
//chatView.setOnItemClickListener(this);
HashMap convs = app.getConversations();
if(convs.containsKey(user) == true)
conv = (Conversation) convs.get(user);
else {
conv = new Conversation();
convs.put(user,conv);
}
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(this,filter);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.imgBtnSend)
{
EditText msg = (EditText)this.findViewById(R.id.editChat);
String s = msg.getText().toString();
Message message = new Message(user, Message.Type.chat);
message.setBody(s);
connection.sendPacket(message);
ArrayList<ChatMessage> m = conv.messages;
String currentDate = DateFormat.getDateInstance().format(new Date());
m.add(new ChatMessage(s,currentDate));
adapter.addItem("I said",s,currentDate,Constants.SEND_LIST_TYPE);
//adapter.notifyDataSetChanged();
}
else
{
//View view = this.findViewById(R.id.linerLayoutChat);
chatView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
public void processPacket(Packet packet) {
// TODO Auto-generated method stub
System.out.println("in");
Message message = (Message) packet;
if (message.getBody() != null) {
System.out.println("in1");
String fromName = StringUtils.parseBareAddress(message.getFrom());
ArrayList<ChatMessage> m = conv.messages;
String currentDate = DateFormat.getDateInstance().format(new Date());
m.add(new ChatMessage(message.getBody(),currentDate));
adapter.addItem(fromName+" said",message.getBody(),currentDate,Constants.REC_LIST_TYPE);
//chatView.postInvalidate();
}
}
}
Adapter class:
public class ChatListViewCustomAdapter extends BaseAdapter
{
public ArrayList<ChatListItem> items;
public Activity context;
public LayoutInflater inflater;
public Boolean temp=false;
public ChatListViewCustomAdapter(Activity context) {
super();
this.context = context;
this.items = new ArrayList<ChatListItem>();
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
TextView txtViewTitle;
TextView txtViewDescription;
TextView txtViewDate;
}
public void addItem(String title,String desc,String d,int type)
{
ChatListItem item = new ChatListItem(title,desc,d,type);
items.add(item);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ChatListItem item = items.get(position);
ViewHolder holder;
System.out.println("Title:"+item.title+" type:"+item.type);
if(convertView==null)
{
holder = new ViewHolder();
int type = this.getItemViewType(position);
if(type == 0)
{
convertView = inflater.inflate(R.layout.list_item_even, null);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.txtViewTitleEven);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.txtViewDescriptionEven);
holder.txtViewDate = (TextView) convertView.findViewById(R.id.txtViewDateEven);
}
else
{
convertView = inflater.inflate(R.layout.list_item_odd, null);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.txtViewTitleOdd);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.txtViewDescriptionOdd);
holder.txtViewDate = (TextView) convertView.findViewById(R.id.txtViewDateOdd);
}
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
holder.txtViewTitle.setText(item.title);
holder.txtViewDescription.setText(item.desc);
holder.txtViewDate.setText(item.date);
return convertView;
}
#Override
public int getItemViewType(int position) {
ChatListItem item = items.get(position);
return item.type;
}
#Override
public int getViewTypeCount() {
return 2;
}
}
Handle all the updates within your Adapter and ensure you invoke notifyDataSetChanged() after you update it (within your Adapter)?
In cases where notifyDataSetChanged() does not work, re-set the adapter on the ListView by calling ListView.setAdapter() with the same Adapter again. This should refresh the view.
the only thing I can see not right are these methods:
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
These methods should return proper values.
items.get(position) and position respectively.