onListItemClick in ListView doesn't work - android

I'm trying to call another Fragment when I click on list item but it doesn't work, I'm using slider menu and the items of ListView are options inside the slider menu. What am I doing wrong?
public class MenuNetimoveis_Fragments extends ListFragment {
private ListView listView;
String[] itensMenu = new String[] {
" Imóveis no mapa",
"Favoritos",
"Agências",
"Dicas para Alugar",
"Alugar meu imóvel",
"Sobre"
};
int[] imagens = new int[]{
R.drawable.map_marker,
R.drawable.star,
R.drawable.house,
R.drawable.coffee,
R.drawable.pricetag,
R.drawable.pricetag
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.list, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ImageView tv = new ImageView(getActivity());
Drawable dw = getResources().getDrawable(R.drawable.menu_netimoveis_locacao);
tv.setImageDrawable(dw);
getListView().addHeaderView(tv);
crateListView();
}
private void crateListView(){
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<6;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", itensMenu[i]);
hm.put("imagens", Integer.toString(imagens[i]) );
aList.add(hm);
}
String[] from = { "txt","imagens" };
int[] to = { R.id.text,R.id.imagemview};
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.list_row, from, to);
setListAdapter(adapter);
}
#Override
public void onListItemClick(ListView lv, View v, int position, long id) {
Fragment newContent = null;
switch (position) {
case 0:
newContent = new Menu_DicasParaAlugar();
break;
case 1:
break;
}
if (newContent != null)
switchFragment(newContent);
}
// the meat of switching the above fragment
private void switchFragment(Fragment fragment) {
if (getActivity() == null)
return;
if (getActivity() instanceof FragmentChangeActivity) {
FragmentChangeActivity fca = (FragmentChangeActivity) getActivity();
fca.switchContent(fragment);
}
}
}

do a getListView().setOnListItemClickListener(this); at the end of onCreate()

Related

How to replace the baseadapter value and how to stop the pagination loading in android filter screen?

I have worked with the concept of filter that have to filter the job from job list based on skills and some list or there.
https://postimg.org/image/g3p1z6lbd/ - DashBoard Fragment.
About DashBoardFragment:
Contains job list view.
Dash Filter Button. - which redirect to the Filter screen.
public class DashBoardRefactor extends Fragment {
public static ProgressDialog progress;
public static List<DashListModel> dashRowList1 = new ArrayList<DashListModel>();
public static View footerView;
// #Bind(R.id.dashListView)
public static ListView dashListView;
int preCount = 2, scroll_Inc = 10, lastCount;
boolean flag = true;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dashboard_fragment, container, false);
ButterKnife.bind(this, v);
setHasOptionsMenu(true);
progress = new ProgressDialog(getActivity());
dashListView = (ListView) v.findViewById(R.id.dashListView);
footerView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dashboard_list_footer, null, false);
dashListView.addFooterView(footerView);
footerView.setVisibility(View.GONE);
dashRowList1.clear();
dashboardViewTask();
dashListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("onItemClick", "onItemClick <---- ");
Intent toPositionDetail = new Intent(getActivity(), PositionDetailScreenRefactor.class);
toPositionDetail.putExtra("id", dashRowList1.get(position).getDashId());
startActivity(toPositionDetail);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
}
});
final int totalJobCount = SessionStores.gettotalJobList(getActivity());
Log.e("totalJobCount", "totalJobCount----" + totalJobCount);
dashListView.setOnScrollListener(new EndlessScrollListener(getActivity(), dashListView, footerView));
return v;
}
public void dashboardViewTask() {
progress.setMessage("Please Wait. It is Loading..job orders....");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
progress.show();
// footerView.setVisibility(View.VISIBLE);
Map<String, String> params = new HashMap<String, String>();
Log.e("candidate_id", "candidate_id---->" + SessionStores.getBullHornId(getActivity()));
params.put("candidate_id", SessionStores.getBullHornId(getActivity()));
params.put("page", "1");
new DashBoardTask(getActivity(), params, dashListView, footerView);
// progress.dismiss();
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
if (menu != null) {
menu.removeItem(R.id.menu_notify);
}
inflater.inflate(R.menu.menu_options, menu);
MenuItem item = menu.findItem(R.id.menu_filter);
item.setVisible(true);
getActivity().invalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.his__menu_accept:
Toast.makeText(getActivity(), "clicked dashboard menu accept", Toast.LENGTH_LONG).show();
return true;
case R.id.menu_filter:
// click evnt for filter
Toast.makeText(getActivity(), "clicked dashboard filter", Toast.LENGTH_LONG).show();
Intent filter_intent = new Intent(getActivity(), DashBoardFilterScreen.class);
startActivity(filter_intent);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onPause() {
super.onPause();
// dashboardViewTask();
}}
DashBoardTask:
public class DashBoardTask {
public DashBoardTask(Context context, Map<String, String> params, ListView dashListView, View footerView) {
this.context = context;
Log.e("context ", "DashBoardTask: " + context);
this.dashListView = dashListView;
this.params = params;
this.footerView = footerView;
ResponseTask();
}
private void ResponseTask() {
new ServerResponse(ApiClass.getApiUrl(Constants.DASHBOARD_VIEW)).getJSONObjectfromURL(ServerResponse.RequestType.POST, params, authorizationKey, context, "", new VolleyResponseListener() {
#Override
public void onError(String message) {
if (DashBoardRefactor.progress.isShowing()) {
DashBoardRefactor.progress.dismiss();
}
}
#Override
public void onResponse(String response) {
//Getting Response and Assign into model Class
int currentPosition = dashListView.getFirstVisiblePosition();
dashListAdapter = new DashListAdapter(context, DashBoardRefactor.dashRowList1, dashListView);
dashListView.setAdapter(dashListAdapter);
((BaseAdapter) dashListAdapter).notifyDataSetChanged();
if (currentPosition != 0) {
// Setting new scroll position
dashListView.setSelectionFromTop(currentPosition + 1, 0);
}
if (footerView.isShown()) {
footerView.setVisibility(View.GONE);
}
//progress.dismiss();
if (DashBoardRefactor.progress.isShowing()) {
try {
DashBoardRefactor.progress.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
DashListAdapter:
________________
public class DashListAdapter extends BaseAdapter {
public static ListView dashListView;
Context c;
private LayoutInflater inflater;
private List<DashListModel> dashRowList;
public DashListAdapter(Context c, List<DashListModel> dashRowList, ListView dashListView) {
this.c = c;
this.dashListView = dashListView;
this.dashRowList = dashRowList;
}
#Override
public int getCount() {
return this.dashRowList.size();
}
#Override
public Object getItem(int position) {
return dashRowList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder dashHolder;
if (inflater == null)
inflater = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.dashboard_jobdetails_list, null);
Log.e("get pos", "get pooooossss---->" + dashRowList.get(position));
final DashListModel dashModel = dashRowList.get(position);
dashHolder = new ViewHolder(convertView);
//Assign the value into screen
dashHolder.dash_company_name.setText(dashModel.getDashCompanyName());
}
the above code for displaying dashboard fragment list.
https://postimg.org/image/nqvp1dud9/ - This link is FilterScreen
By using this image if i filter the job based on the designed UI detail. That should replace into the DashboadFragment list The result should display into the DashBoard Fragment. How can I add pagination on Filter screen the same which have in DashBoardFragment.

Null pointer at setting setAdapter() in customadapter

I have two layouts for a single activity that I will dynamically change the layout. Here the null pointer occurs at the line.
I tried to change the view from layout 1 to layout 2
listview.setadapter(listviewAdapter)
lv2.setAdapter(lva);
The error I am getting is
java.lang.NullPointerException at in.prasilabs.eagleeye.Log$DBSync.onPostExecute(Log.java:170)
public class Log extends Activity {
ListView lv1;
ListView lv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logmenu);
lv1 = (ListView) findViewById(R.id.listView1);
final Activity act = getParent();
String[] menu = new String[]
{
"Last 10 log",
"All logs (100)",
};
ArrayAdapter<String> menuadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,android.R.id.text1, menu);
lv1.setAdapter(menuadapter);
lv1.setOnItemClickListener(new OnItemClickListener() {
DBSync dbs;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
dbs = new DBSync(position, Log.this, act);
dbs.execute();
break;
default:
break;
}
}
});
}
class DBSync extends AsyncTask<String, Void, Void> {
int q;
String[] time = new String[]{"No logs"};
String[] status = new String[]{"closed"};
Context cnt;
Activity act;
public DBSync(int qu, Log lg, Activity ac) {
q = qu;
cnt = lg;
act = ac;
}
#Override
protected Void doInBackground(String... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
//setContentView(R.layout.log);
time = new String[]{"hii","yes"};
status = new String[]{"no", "yes"};
boolean isFirstXml=true;//evaluatingConditionFunction();
LayoutInflater inflator=getLayoutInflater();
View view=inflator.inflate(isFirstXml?R.layout.logmenu:R.layout.log, null, false);
view.startAnimation(AnimationUtils.loadAnimation(cnt, android.R.anim.slide_out_right));
**setContentView(view);**
lv2 = (ListView) findViewById(R.id.listView2);
ListViewAdapter lva = new ListViewAdapter(act, time, status);
**lv2.setAdapter(lva);**
lv2.refreshDrawableState();
}
}
}
You are calling setContentView twice.
setContentView(R.layout.log);
setContentView(R.layout.logmenu);
By calling it twice, only the second one (R.layout.logmenu) will be set. I guess R.id.listView2 is in R.layout.log. Because of this, (ListView) findViewById(R.id.listView2) returns null and lv2 gets null. When you try to call lv2.setAdapter, you try to set an adapter on an object that is null - Your app crashes.

Android - update ListView from a fragment to another

I am trying to update listView from another fragment class after i delete an item from listView from current class. For example, i delete a consumer that has an expense, then the expense of that consumer will also be deleted. But consumer and expense is different page that using tab control, which is fragment, when i delete consumer, the expense list is not updated, until i go to previous page, then enter the page again. What can i do to update the expense list when consumer from consumer list is deleted? i heard of using broadcast receiver is able to do that, but how can i implement it in my code? I am new in android, please guide me.Thanks
Here is the code for consumer/participant list :
public class Participant extends ListFragment implements OnClickListener{
Intent intent;
TextView friendId;
Button addparticipant;
String eventId;
ListView lv;
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
ArrayList<HashMap<String, String>> friendList = controller
.getAllFriends(queryValues);
if (friendList.size() != 0) {
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
friendId = (TextView) view.findViewById(R.id.friendId);
String valFriendId = friendId.getText().toString();
Intent objIndent = new Intent(getActivity(),
EventPage.class);
objIndent.putExtra("friendId", valFriendId);
startActivity(objIndent);
}
});
lv.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
friendId = (TextView) arg1.findViewById(R.id.friendId);
registerForContextMenu(getListView());
return false;
}
});
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
friendList, R.layout.view_friend_entry, new String[] {
"friendId", "friendName", "friendSpending" },
new int[] { R.id.friendId, R.id.friendName,
R.id.friendSpending });
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.participant, container, false);
addparticipant = (Button) rootView.findViewById(R.id.addpart);
addparticipant.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent objIntent = new Intent(getActivity(),
AddParticipant.class);
objIntent.putExtra("eventId", eventId);
startActivity(objIntent);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
String[] menuItems = getResources().getStringArray(R.array.menu);
for (int i = 0; i < menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
int menuItemIndex = item.getItemId();
EventController controller = new EventController(getActivity());
switch (menuItemIndex) {
case 0:
String valFriendId = friendId.getText().toString();
Intent objIndent = new Intent(getActivity(),
EditParticipant.class);
objIndent.putExtra("friendId", valFriendId);
startActivity(objIndent);
break;
case 1:
String valFriendId2 = friendId.getText().toString();
controller.deleteFriend(valFriendId2);
onResume();
}
return true;
}
#Override
public void onResume() {
super.onResume();
if (getListView() != null) {
updateData();
}
}
private void updateData() {
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
controller.getAllFriends(queryValues),
R.layout.view_friend_entry, new String[] { "friendId",
"friendName", "friendSpending" }, new int[] {
R.id.friendId, R.id.friendName, R.id.friendSpending });
setListAdapter(adapter);
}
}
Here is the code for expense list:
public class Expense extends ListFragment implements OnClickListener {
Button addexp;
TextView expenseId;
ListView lv;
String eventId, friendId;
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
ArrayList<HashMap<String, String>> expenseList = controller
.getAllExpenses(queryValues);
if (expenseList.size() != 0) {
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
expenseId = (TextView) view.findViewById(R.id.expenseId);
String valExpenseId = expenseId.getText().toString();
Intent objIndent = new Intent(getActivity(),
EditExpense.class);
objIndent.putExtra("expenseId", valExpenseId);
startActivity(objIndent);
}
});
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
expenseList, R.layout.view_expense_entry, new String[] {
"expenseId", "expenseName","expenseQuantity" }, new int[] {
R.id.expenseId, R.id.expenseName, R.id.expenseQuantity });
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.expense, container, false);
addexp = (Button) rootView.findViewById(R.id.addexp);
addexp.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent objIntent = new Intent(getActivity(), AddExpense.class);
objIntent.putExtra("eventId", eventId);
startActivity(objIntent);
}
#Override
public void onResume() {
super.onResume();
if (getListView() != null) {
updateData();
}
}
private void updateData() {
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
controller.getAllExpenses(queryValues),
R.layout.view_expense_entry, new String[] { "expenseId",
"expenseName", "expenseQuantity" }, new int[] { R.id.expenseId,
R.id.expenseName, R.id.expenseQuantity });
setListAdapter(adapter);
}
}
Same scenario with me, if you used FragmentPagerAdapter, Try like this in FirstFragment
private void updateSecondFragment(){
//Way to get TagName which generated by FragmentPagerAdapter
String tagName = "android:switcher:" + R.id.pager + ":" + 1; // Your pager name & tab no of Second Fragment
//Get SecondFragment object from FirstFragment
SecondFragment f2 = (SecondFragment)getActivity().getSupportFragmentManager().findFragmentByTag(tagName);
//Then call your wish method from SecondFragment to update appropriate list
f2.updateList();
}
I got that idea by reading this. Then edit a little !
One way could be creating the methods in the activity that contains the two fragments, and access to the fragments methods from the activity. You can update the database and reload the list in the same method.
For example, In the activity
public void updateFragment2(){ ... }
In fragment 1 you should call:
((ActivityClass)getActivity()).updateFragment2();
In the section "Communicating with the Activity" you can see the explanation of this example:
http://developer.android.com/guide/components/fragments.html

any advice or hints for refreshing ArrayAdapter?

here I have a Fragment, I use this code and everything works normally, and what I want to do is update my shown list if there is a new file, could you guys give any advice or hint?
CODE:
public class HomeFragment extends Fragment {
public static final String TITLE = "title";
private List<String> library = new ArrayList<String>();
private TextView tv;
private ListView lv;
private ArrayAdapter<String> adapter;
public static Handler handHF;
private String[] temp;
private Object UIlock = new Object();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home_fragment, container,
false);
library = getLibraryList();
if (!library.isEmpty()) {
if (tv != null) {
tv.setVisibility(View.GONE);
} else {
temp = library.toArray(new String[library.size()]);
lv = (ListView) rootView.findViewById(R.id.library_list);
adapter = new ArrayAdapter<String>(rootView.getContext(),
android.R.layout.simple_list_item_1, temp);
lv.setAdapter(adapter);
setListener(lv);
tv = (TextView) rootView.findViewById(R.id.library_tv1);
tv.setVisibility(View.GONE);
tv = null;
}
} else {
tv = (TextView) rootView.findViewById(R.id.library_tv1);
tv.setText("No Manga found...");
}
return rootView;
}
#SuppressLint("HandlerLeak")
#Override
public void onResume() {
/*
* Fragment on pause state
*/
super.onResume();
handHF = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
if (msg.what == 0) {
refreshAdapter();
}
}
};
}
private void setListener(ListView lv) {
/*
* Sets listener on listView
*/
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent myIntent = new Intent(view.getContext(),
ChapterActivity.class);
myIntent.putExtra(TITLE, parent.getItemAtPosition(position)
.toString());
startActivity(myIntent);
}
});
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(view.getContext(),
parent.getItemAtPosition(position).toString(),
Toast.LENGTH_SHORT).show();
return true;
}
});
}
private final List<String> getLibraryList() {
/*
* Returns List<String> of library
*/
List<String> l = new ArrayList<String>();
File dir = new File(Constants.UNDUH);
if (dir.exists()) {
File[] dirs = dir.listFiles();
for (File i : dirs) {
l.add(i.getName());
}
return l;
} else {
return l;
}
}
private void refreshAdapter() {
/*
* It will update library and
*/
synchronized (UIlock) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
if (tv != null) {
tv.setVisibility(View.GONE);
}
library = getLibraryList();
temp = library.toArray(new String[library.size()]);
lv = (ListView) getActivity().findViewById(
R.id.library_list);
adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, temp);
lv.setAdapter(adapter);
}
});
}
}
}
any advice will be appreciated, thank you!
Update your list of string which you are passing to the ListView in your case you are using
private String[] temp;
Use notifyDataSetChanged Method, just call this after your adapter and it will automatically adds more items to list if your temp[] increments.
like this
adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, temp);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
Where you are adding more data into temp[]
add an extra line
((ArrayAdapter) lv.getAdapter()).notifyDataSetChanged();

listview with simpleadapter not refreshing after adding new data to sqlite database

I have a problem with my listview that when I add a task to my database, I need to update my listview with this new added task....
I'm new to android and Eclipse...
Here is my code for Main (that shows the ListView)
public class Main extends ListActivity {
Button newCat;
TextView todaytaskId;
ResultDatabase controller5 = new ResultDatabase(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
newCat = (Button) findViewById(R.id.bNewCat);
newCat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen = new Intent(getApplicationContext(),
CategoryList.class);
startActivity(nextScreen);
}
});
ArrayList<HashMap<String, String>> todaytaskList = controller5
.getTodayTasks();
if (todaytaskList.size() != 0) {
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
todaytaskId = (TextView) view
.findViewById(R.id.todaytaskId);
String valtaskId = todaytaskId.getText().toString();
Intent objIndent = new Intent(getApplicationContext(),
DelayTask.class);
objIndent.putExtra("todaytaskId", valtaskId);
startActivity(objIndent);
}
});
SimpleAdapter adapter = new SimpleAdapter(Main.this, todaytaskList,
R.layout.view_today_task, new String[] { "taskId",
"taskName", "taskTime" }, new int[] {
R.id.todaytaskId, R.id.todaytasktv,
R.id.todaytasktimetv});
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
Here's my code to select tasks from ResultDatabase class
public ArrayList<HashMap<String, String>> getTodayTasks() {
ArrayList<HashMap<String, String>> wordList;
wordList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM tasks where taskDate = date('now') AND taskDone = 'No'";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("taskId", cursor.getString(0));
map.put("taskName", cursor.getString(1));
map.put("taskTime", cursor.getString(3));
// map.put("taskDate", cursor.getString(4));
wordList.add(map);
} while (cursor.moveToNext());
}
return wordList;
}
After modifying the data set that is connected on the adapter you must call notifyDataSetChanged to notify the adapter to update the views with the new data. You must also call requery on the Cursor to update the cursor with new data. To clarify you should call requery before notifyDataSetChanged.
Check sample code below
public class WeatherAppActivity extends ListActivity {
Button buton;
ItemsAdapter lista;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
List<String> initialList = new ArrayList<String>();
initialList.add("Bucuresti");
initialList.add("Sibiu");
lista=new ItemsAdapter(this, initialList);
buton=(Button)findViewById(R.id.button1);
buton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
lista.add(""+System.currentTimeMillis()); // e chiar getText()
lista.notifyDataSetChanged();
}
});
setListAdapter(lista);
}
class ItemsAdapter extends ArrayAdapter<String> {
public ItemsAdapter(Context context, List<String> list) {
super(context, R.layout.lista, list);
}
#Override
public View getView(final int position, View row, final ViewGroup parent) {
final String item = getItem(position);
ItemWrapper wrapper = null;
if (row == null) {
row = getLayoutInflater().inflate(R.layout.lista, parent, false);
wrapper = new ItemWrapper(row);
row.setTag(wrapper);
} else {
wrapper = (ItemWrapper) row.getTag();
}
wrapper.refreshData(item);
return row;
}
class ItemWrapper {
TextView text;
public ItemWrapper(View row) {
text = (TextView) row.findViewById(R.id.elementLista);
}
public void refreshData(String item) {
text.setText(item);
}
}
}
}

Categories

Resources