How to show JSON array into Listview of Fragment? - android-fragments

I am trying to implement Listview in Fragment, All items from URL is fetched but unable to do show in Listview. I am using Navigation Drawer and this fragment is one of the item of Drawer. my code is here: Thanks in advance
public class ViewEmployeeFragment extends Fragment {
String Fname,Email,Userlogname,Phone,Company,Lname;
ListView empListView;
Context context;
ArrayList<HashMap<String , String>> ListFirstname = new ArrayList<HashMap<String,String>>();
CustomBaseAdapter mAdapter;
public ViewEmployeeFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.vuemploye_fragment, container, false);
empListView = (ListView)rootView.findViewById(R.id.listView1);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
try{
JSONObject jobject = getJSON();
JSONArray jArry = jobject.getJSONArray("data");
for(int j=0; j<jArry.length(); j++){
JSONObject jObj = jArry.getJSONObject(j);
Fname = jObj.getString(NAME);
Company = jObj.getString(COMPANY);
Email = jObj.getString(EMAIL);
Lname = jObj.getString(LNAME);
Userlogname = jObj.getString(USERLOGNAME);
Phone = jObj.getString(PHONE);
Log.i("Json Value", "First Name: "+Fname);
Log.i("Json Value", "Company Name: "+Company);
Log.i("Json Value", "Email: "+Email);
Log.i("Json Value", "Last name: "+Lname);
Log.i("Json Value", "User ID: "+Userlogname);
Log.i("Json Value", "Phone: "+Phone);
HashMap<String, String> map = new HashMap<String, String>();
map.put(NAME, Fname);
ListFirstname.add(map);
}
}
catch(Exception e){
e.printStackTrace();
}
empListView.setAdapter(mAdapter);
return rootView;
}
public JSONObject getJSON(){
JSONObject jArray = null ;
StringBuilder sBuilder = new StringBuilder();
Log.d("Inside creater", "creating JSON string");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://fwdfuture.com/locationapp/ds-emp-list.php?admid=7");
try{
HttpResponse httpResponse = httpClient.execute(httpPost);
StatusLine statusLine = httpResponse.getStatusLine();
Log.d("Httpresponse", ""+httpResponse);
int statusCode = statusLine.getStatusCode();
Log.d("Status Code ", " is " +statusCode);
if(statusCode == 200){
BufferedReader br = new BufferedReader(new
InputStreamReader(httpResponse.getEntity().getContent()));
String line;
while((line = br.readLine())!= null){
sBuilder.append(line);
Log.d("Getting Json", "Json Data Download "+'\n'+sBuilder);
}
}
else{
Log.d("Error", "Failed to Download");
}
}catch(Exception e){
Log.d("Exception", ""+e);
}
try{
jArray = new JSONObject(sBuilder.toString());
Log.d("JSON array", ""+jArray);
}catch(Exception e ){
e.printStackTrace();
}
return jArray;
}
public class CustomBaseAdapter extends BaseAdapter{
private Context activity;
LayoutInflater inflatr;
// private ArrayList<String> Lfname = null;
public CustomBaseAdapter(Context activity){
this.activity = activity;
// inflatr = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflatr = LayoutInflater.from(activity);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return ListFirstname.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return ListFirstname.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView == null){
convertView = inflatr.inflate(R.layout.emplist_item, parent, false);
}
HashMap<String, String> map = ListFirstname.get(position);
TextView EmpName = (TextView)convertView.findViewById(R.id.textView1_empName);
String S_emp = map.get(NAME);
EmpName.setText(S_emp);
return convertView;
}
}
}

you have to make adapter using baseadapter class, and set this adapter in listview.click here to view example

Related

How to delegate class into an Async Task instance?

I could write postAsync = new PostAsync();
postAsync.delegate = this; outside the setOnClickListener which will work smoothly, but I need to write it within setOnClickListener.
public class Sign_inFragment extends Fragment implements AsyncResponse {
PostAsync postAsync;
String email, password, logInResult;
EditText ev, pv;
Button bv;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.sign_in_fragment, container, false);
bv = (Button) v.findViewById(R.id.signinButton);
ev = (EditText) v.findViewById(R.id.emailTextView);
pv = (EditText) v.findViewById(R.id.passwordTextView);
bv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ev.getText() != null && pv.getText() != null) {
email = ev.getText().toString();
password = pv.getText().toString();
postAsync = new PostAsync();
postAsync.delegate = this;//this will not work.
postAsync.execute(email, password);
//Toast.makeText(getActivity().getApplicationContext(), "SIGN IN SUCCESFUL", Toast.LENGTH_LONG).show();
}
}
});
return v;
}
#Override
public void processFinish(String output) {
logInResult = output;
if (logInResult.equals("true") ) {
Intent intent = new Intent(getActivity().getApplicationContext(), SignedInActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else if(logInResult.equals("false")) {
ev.setError("Invalid Account");
}
}
}
Apparently writing postAsync.delegate = this will not work. Do you have any suggestions?
In your case this is consider as view of button because you are using it inside button click method. If you want to pass fragment you have to write like postAsync.delegate = Sign_inFragment.this or if you want activity then postAsync.delegate = getActivity();

How to refresh Listview with custom base adapter connect with sqlite database?

I've been stuck in this problem for a week. I have a listview dialog fragment that uses a custom base adapter and connect with sqlite database.
My database adapter:
public class DBAdapter {
// Column Product
static final String ROWID = "id";
static final String NAME = "name";
static final String DESC = "desc";
static final String PRICE = "price";
static final String DISPLAY = "display";
// DB Properties
static final String DBNAME = "db_prototype";
static final String TBNAME = "tbl_product";
static final int DBVERSION = 1;
static final String CREATE_TABLE = "CREATE TABLE tbl_product(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL," +
" desc TEXT NOT NULL, price TEXT NOT NULL, display INTEGER NOT NULL)";
final Context c;
SQLiteDatabase db;
DBHelper helper;
public DBAdapter(Context c) {
this.c = c;
helper = new DBHelper(c);
}
private static class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(CREATE_TABLE);
}catch (SQLException e){
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DBHelper.class.getName(), "Upgrading DB");
db.execSQL("DROP TABLE IF EXIST tbl_product");
}
}
// Open Database
public DBAdapter openDB(){
try{
db = helper.getWritableDatabase();
}catch (SQLException e){
e.printStackTrace();
}
return this;
}
public void closeDB(){
helper.close();
}
// Insert Into Table
public long add(String name, String desc, String price, int display){
try{
ContentValues cv = new ContentValues();
cv.put(NAME, name);
cv.put(DESC, desc);
cv.put(PRICE, price);
cv.put(DISPLAY, display);
return db.insert(TBNAME, ROWID, cv);
}catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
// Delete Table
public long delete(String name){
try{
return db.delete(TBNAME, NAME + "='" + name + "'", null);
}catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
// Get All Value
public Cursor getAllValue(){
String[] columns = {ROWID, NAME, DESC, PRICE, DISPLAY};
return db.query(TBNAME, columns, null, null, null, null, null);
}
}
My Listview adapter (void refreshAdapter to refresh dataset):
public class CartAdapter extends BaseAdapter {
private Context c;
private ArrayList<Integer> display;
private ArrayList<String> nama;
private ArrayList<String> harga;
public CartAdapter(Context c, ArrayList<Integer> display, ArrayList<String> nama, ArrayList<String> harga) {
this.c = c;
this.display = display;
this.harga = harga;
this.nama = nama;
}
#Override
public int getCount() {
return nama.size();
}
#Override
public Object getItem(int position) {
return nama.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cart_display, null);
}
// Get View
TextView txtNama = (TextView) convertView.findViewById(R.id.txtNama);
TextView txtHarga = (TextView) convertView.findViewById(R.id.txtHarga);
ImageView imgGambar = (ImageView) convertView.findViewById(R.id.imgGambar);
//Assign Data
txtNama.setText(nama.get(position));
txtHarga.setText(harga.get(position));
imgGambar.setImageResource(display.get(position));
return convertView;
}
public void refreshAdapter(ArrayList<Integer> display, ArrayList<String> nama, ArrayList<String> harga){
this.display.clear();
this.harga.clear();
this.nama.clear();
this.display = display;
this.harga = harga;
this.nama = nama;
this.notifyDataSetChanged();
}
}
My Listview dialog fragment:
public class CartDialog extends DialogFragment {
ArrayList<String> cart_name;
ArrayList<String> cart_price;
ArrayList<Integer> cart_pict;
DBAdapter dbAdapter;
CartAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_cart_dialog, null);
ListView LV = (ListView) rootView.findViewById(R.id.listCart);
Button btnDelete = (Button) rootView.findViewById(R.id.button);
// Prepare ArrayList to assign with DB
cart_pict = new ArrayList<Integer>();
cart_name = new ArrayList<String>();
cart_price = new ArrayList<String>();
getDialog().setTitle("Keranjang Belanjaan");
dbAdapter = new DBAdapter(getActivity());
adapter = new CartAdapter(getActivity(), cart_pict, cart_name, cart_price);
refreshDB();
LV.setAdapter(adapter);
LV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = adapter.getItem(position).toString();
// Delete Selected Item on SQLite Database
dbAdapter.openDB();
long result = dbAdapter.delete(name);
dbAdapter.closeDB();
//Refresh Cart
refreshDB();
adapter.refreshAdapter(cart_pict, cart_name, cart_price);
}
});
return rootView;
}
public void refreshDB(){
// Refresh Data
dbAdapter.openDB();
Cursor c = dbAdapter.getAllValue();
while(c.moveToNext()){
String name = c.getString(1);
String price = c.getString(3);
int display = c.getInt(4);
cart_name.add(name);
cart_price.add(price);
cart_pict.add(display);
}
Toast.makeText(getActivity(), "Jumlah: " + c.getCount(), Toast.LENGTH_SHORT).show();
dbAdapter.closeDB();
}
}
So, whenever I click an item in the listview, DBAdapter will remove these items from SQLite Database and then CartAdapter will refresh listview. I've been looking for references to this problem, add notifyDatasetChange (), but the problem is after I called the refreshData() method, the data in listview will empty.
Try this bro
public void refreshDB(){
// Refresh Data
ArrayList<Integer> displayBaru = new ArrayList<Integer>();
ArrayList<String> namaBaru = new ArrayList<String>();
ArrayList<String> hargaBaru = new ArrayList<String>();
dbAdapter.openDB();
Cursor c = dbAdapter.getAllValue();
while(c.moveToNext()){
String name = c.getString(1);
String price = c.getString(3);
int display = c.getInt(4);
namaBaru.add(name);
hargaBaru.add(price);
displayBaru.add(display);
}
adapter.refreshAdapter(displayBaru, namaBaru, hargaBaru);
dbAdapter.closeDB();
}

how to fix Integer cannot be cast in ViewHolder

I have adapter and retrieving the details into listview
private class ChatDisplayAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ChatDisplayAdapter() {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private class ViewHolder {
TextView chatTitle;
TextView chatPlace;
TextView chatDate;
TextView notificationCount;
}
#Override
public int getCount() {
return groupEventMoList.size();
}
#Override
public Object getItem(int position) {
return groupEventMoList.get(position);
}
#Override
public long getItemId(int id) {
// for sqllite management
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.chatwindow, null);
holder = new ViewHolder();
convertView.setClickable(true);
convertView.setFocusable(true);
holder.chatTitle = (TextView) convertView.findViewById(R.id.chat_title);
holder.chatPlace = (TextView) convertView.findViewById(R.id.event_place);
holder.chatDate = (TextView) convertView.findViewById(R.id.event_date);
holder.notificationCount = (TextView) convertView.findViewById(R.id.notification_count);
holder.chatPlace.setTextColor(getResources().getColor(R.color.black));
holder.chatDate.setTextColor(getResources().getColor(R.color.black));
holder.chatTitle.setTextColor(getResources().getColor(R.color.black));
holder.notificationCount.setTextColor(getResources().getColor(R.color.black));
convertView.setTag(holder);
//Log.e("view", "holder" + convertView.getTag());
}
else {
// Log.e("view", "holder" + convertView.getTag());
holder = (ViewHolder) convertView.getTag();
// Log.e("view", "holder" + holder);
}
// holder = (ViewHolder) convertView.getTag();
convertView.setTag(groupEventMoList.get(position));
holder.chatPlace.setText(groupEventMoList.get(position).getPlace());
holder.notificationCount.setText(Integer.toString(groupEventMoList.get(position).getCount()));
holder.chatTitle.setText(groupEventMoList.get(position).getText());
String actualDate = groupEventMoList.get(position).getEventDate();
Log.e("view", "notification" + groupEventMoList.get(position).getCount());
Log.e("view", "after notification position" + position);
try {
//date format changed here
Date formatDate = new SimpleDateFormat("yyyy-MM-dd").parse(actualDate);
dateResult = new SimpleDateFormat("dd-MM-yyyy").format(formatDate);
holder.chatDate.setText(dateResult);
} catch (ParseException e) {
e.printStackTrace();
}
Log.e("view", "position" + groupEventMoList.get(position).getPlace());
final EventMO eventMO = groupEventMoList.get(position);
convertView.setTag(position);
View v = convertView.findViewById(R.id.chat_window_single);
v.getRootView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("position", v.getTag().toString());
Intent groupAct = new Intent(context, GroupChatActivity.class);
groupAct.putExtra("eventMo", eventMO);
groupAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(groupAct);
}
});
return convertView;
}
}
}
this is my log
12-30 17:19:54.324 17652-17652/com.ringee.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.ClassCastException: java.lang.Integer cannot be cast to com.ringee.app.GroupChatFragment$ChatDisplayAdapter$ViewHolder
at com.ringee.app.GroupChatFragment$ChatDisplayAdapter.getView(GroupChatFragment.java:345)
I have the error exactly at else part. how to fix this issue
I am getting error near this line : holder = (ViewHolder) convertView.getTag();
and holder returns as 0
You are setting the view tag three times. Notice the lines:
convertView.setTag(holder);
...
convertView.setTag(groupEventMoList.get(position));
...
convertView.setTag(position);
With the last line, you are setting an Integer as a tag and thats why you get ClassCastException.
Remove the excess setTags and leave only the first, correct one.
Similar cases here and here.

Refresh list and adapter when DB changed in custom Adapter

my project is todo
i have 4 tab , 4 fragment with 4 list(Actionbar navigation contain 4 tab and ViewPager).
4 list(tab) use same db table but each of them retrieve different data with categoryID.
i use a Asynctask for all of them ,to read data and set adapter to list.
public class AsyncTaskDB extends AsyncTask<Void, Void, listAdapter> {
Context act;
int Categoryid;
ArrayList<memo> arraymemo;
listAdapter myadapter;
ListView list;
listAdapter listAdp;
public AsyncTaskDB(Context acti, int categoryID) {
this.act = acti;
this.Categoryid = categoryID;
}
#Override
protected listAdapter doInBackground(Void... params) {
MemoDBHelper helper = new MemoDBHelper(act);
// getAllDataByCategoryID
if (Categoryid != CategoryID.Done_ID)
arraymemo = helper.getAllTaskByCategory(Categoryid);
else
arraymemo = (ArrayList<memo>) helper.gatDoneMemo();
myadapter = new listAdapter(act, arraymemo);
if (myadapter == null) {
Toast.makeText(act, "no data", Toast.LENGTH_SHORT).show();
cancel(true);
}
return myadapter;
}
#Override
protected void onPostExecute(listAdapter result) {
switch (Categoryid) {
case CategoryID.Urgent_Imprtant_ID:
list = (ListView) ((Activity) act)
.findViewById(R.id.Urgent_Important_list);
break;
case CategoryID.Urgent_Less_Imprtant_ID:
list = (ListView) ((Activity) act)
.findViewById(R.id.Urgent_Less_Important_list);
break;
case CategoryID.Less_Urgent_Imprtant_ID:
list = (ListView) ((Activity) act)
.findViewById(R.id.Less_Urgent_Imprtant_list);
break;
case CategoryID.Neither_Urgent_Or_Imprtant_ID:
list = (ListView) ((Activity) act)
.findViewById(R.id.Neither_Urgent_Imprtant_list);
break;
case CategoryID.Done_ID:
list = (ListView) ((Activity) act).findViewById(R.id.ArchiveList);
break;
}
list.setAdapter(result);
this.listAdp = result;
}
public listAdapter getlistAdapter() {
return this.listAdp;
}
}
each memo in list have Done CheckBox.when user check and uncheck it,automatically memo update in db.(in custom adapter)
----------------------------
| -- |
| | | memotitle |
| -- |
----------------------------
public class listAdapter extends BaseAdapter implements OnCheckedChangeListener { Context act;
ArrayList<memo> MemoArray;
SparseBooleanArray mcheck;
int pos;
MemoDBHelper helper;
public listAdapter(Context activity, ArrayList<memo> memoarray) {
this.act = activity;
this.MemoArray = memoarray;
mcheck = new SparseBooleanArray(memoarray.size());
helper = new MemoDBHelper(act);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return MemoArray.size();
}
#Override
public memo getItem(int position) {
// TODO Auto-generated method stub
return MemoArray.get(position);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public class viewHolder {
TextView title;
// TextView description;
CheckBox chkstatus;
}
viewHolder it;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
pos = position;
LayoutInflater in = ((Activity) act).getLayoutInflater();
if (convertView == null) {
convertView = in.inflate(R.layout.list_item, null);
it = new viewHolder();
it.title = (TextView) convertView.findViewById(R.id.txt_list_title);
it.chkstatus = (CheckBox) convertView
.findViewById(R.id.chkStatusid);
convertView.setTag(it);
} else {
it = (viewHolder) convertView.getTag();
}
it.title.setText(MemoArray.get(position).GetTitle());
it.chkstatus.setChecked(MemoArray.get(position).GetSattus());
it.chkstatus.setOnCheckedChangeListener(this);
it.chkstatus.setTag(String.valueOf(MemoArray.get(position).GetID()));
return convertView;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mcheck.put(Integer.valueOf((String) buttonView.getTag()), isChecked);
helper.updateStatusByID(Integer.valueOf((String) buttonView.getTag()),
(isChecked));
helper.close();
//after db updatedt ,call method in fragment to notifydatsetchanged!
UrgentImportant_frg.notifyAdapter();
}
}
adapter must notify data changed ,and list don't show done memo.i don't how to do it !
my first fragment :
public class UrgentImportant_frg extends Fragment {
static listAdapter myadp;
ListView list;
// memo selectedmemo;
long[] checkid;
AsyncTaskDB asyn;
ArrayList<memo> selectedMemoArray;
final static int RQS_MoveTo = 10;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.urgentimportant_layout,
container, false);
return rootview;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
selectedMemoArray = new ArrayList<memo>();
list.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.list_select_menu, menu);
/*
* MenuInflater inflater = getActivity().getMenuInflater();
* inflater.inflate(R.menu.list_select_menu, menu);
*/
mode.setTitle("Select Items");
return true;
}
#Override
public boolean onActionItemClicked(final ActionMode mode,
MenuItem item) {
switch (item.getItemId()) {
case R.id.deletemenu:
final int[] myitemsid = getSelectedID();
final MemoDBHelper helper = new MemoDBHelper(getActivity());
AlertDialog.Builder myAlert = new AlertDialog.Builder(
getActivity());
myAlert.setMessage(
"Are you sure to delete " + myitemsid.length
+ " memo ?")
.setPositiveButton("yes", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
for (int j = 0; j < myitemsid.length; j++) {
helper.deleteRow(myitemsid[j]);
/*
* if (j == myitemsid.length - 1) {
* strid[j] = String
* .valueOf(myitemsid[j]); } else {
* strid[j] = String
* .valueOf(myitemsid[j]) + ","; }
*/
}
mode.finish();
onResume();
}
}).setNegativeButton("no", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
mode.finish();
}
});
AlertDialog alert = myAlert.create();
alert.show();
// mode.finish();
break;
case R.id.MoveTomenu:
// myadp.getItem(position);
Intent i = new Intent(getActivity(),
MoveToCategory_act.class);
i.putExtra("categoryid", CategoryID.Urgent_Imprtant_ID);
startActivityForResult(i, RQS_MoveTo);
mode.finish();
break;
}
return true;
}
// get selected id to delete and move category
#Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
if (myadp == null) {
myadp = asyn.getlistAdapter();
}
int p = ifMemoSelectedBefore(myadp.getItem(position));
if (p != -1) {
selectedMemoArray.remove(p);
} else if (checked) {
selectedMemoArray.add(myadp.getItem(position));
}
final int checkedCount = list.getCheckedItemCount();
switch (checkedCount) {
case 0:
mode.setSubtitle(null);
break;
case 1:
mode.setSubtitle("One Item Selected");
break;
default:
mode.setSubtitle(checkedCount + " Item Selected");
break;
}
}
});
getActivity().getActionBar().setSubtitle("subtitle");
}
public int ifMemoSelectedBefore(memo m) {
return selectedMemoArray.indexOf(m);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
list = (ListView) view.findViewById(R.id.Urgent_Important_list);
// -------------click item
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
if (myadp == null) {
myadp = asyn.getlistAdapter();
}
// Log.d("tag", myadp.getItem(position).GetTitle() + "");
Intent nextintent = new Intent(getActivity(),
EditMemo_act.class);
memo g = myadp.getItem(position);
/*
* MemoDBHelper helper = new MemoDBHelper(getActivity());
* helper.updateStatusByID(g.GetID(), true);
*/
nextintent.putExtra("editmemo", g);
startActivity(nextintent);
}
});
}
#Override
public void onResume() {
asyn = new AsyncTaskDB(getActivity(), CategoryID.Urgent_Imprtant_ID);
asyn.execute();
super.onResume();
}
public int[] getSelectedID() {
int[] SelectedArray_ID = new int[selectedMemoArray.size()];
for (int j = 0; j < selectedMemoArray.size(); j++) {
SelectedArray_ID[j] = selectedMemoArray.get(j).GetID();
// Log.d("id", selectedMemoArray.get(j).GetID() + "");
}
return SelectedArray_ID;
}
//-------------a method to notifymyadpter
public static void notifyAdapter() {
if (myadp != null) {
myadp.notifyDataSetChanged();
Log.d("notify", "here");
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RQS_MoveTo) {
if (resultCode == Result.RESULT_OK) {
int id = data.getExtras().getInt("NEWCategoryID");
MemoDBHelper helper = new MemoDBHelper(getActivity());
final int[] myitemsid = getSelectedID();
for (int j = 0; j < myitemsid.length; j++) {
helper.updateCategory(myitemsid[j], id);
}
onResume();
}
}
}
}
is there any method in fragment to run after adapter changed?or in myadapter ,after db updated i call a method in fragment to notify data changed ? i think the second solution isn't right >_<
p.s:notifyAdapter() doesn't work,is it because my adapter fill in asyntask ?
When the adapter changed, try to call below method.
Once you use FragmentPagerAdapter or ListView, when you change the data, you should call this.
notifyDataSetChanged();
read about it : notifyDataSetChanged

how to get the data and update to UI when new record available in SqliteDB?

I am working on a sample application by communicate with .net web service.In my application I am getting records from web service into my activity class then i am displaying entire records in ListView by using ArrayAdapter and also i am running a service class at background process for get the latest record from web service when the new records are available from web service then i am saving those records in to SQLite data base.This process is happening at back ground.Here i would like to get the latest data from SQLite DB and append to my ListView.
I have implemented Activity class as follows:
public class GetMsgsScreen extends ListActivity
{
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
static String[] userName = null;
static String[] usrMessages = null;
private Integer[] imgid = null;
ShoutRepeatService bg;
////////////////////////////////////////////////////
List<Message> resultShoutMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
resultMessage = new ParseXml().convertMessages(new Model().getMessages("0"));
usrMessages = new String[resultMessage.size()];
userName = new String[resultMessage.size()];
imgid = new Integer[resultMessage.size()];
getSharedPreferences("Values", 0).edit().putString("msgid",resultMessage.get(0).getMessageID()).commit();
for(int i=0;i<resultMessage.size();i++)
{
Log.v("GetMsgsScreen", "resultMessage*******>>>>"+resultMessage.get(i).getMessageText());
Log.v("GetMsgsScreen", "resultNames*******>>>>"+resultMessage.get(i).getUserFirstName());
usrMessages[i] = resultMessage.get(i).getMessageText();
userName[i] = resultMessage.get(i).getUserFirstName();
imgid[i] = R.drawable.person;
}
///////////////////////////////////////////////////////
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for(int i=0;i<userName.length;i++){
try {
rd = new RowData(i,userName[i],usrMessages[i]);
} catch (ParseException e) {
e.printStackTrace();
}
data.add(rd);
}
CustomAdapter adapter = new CustomAdapter(this, R.layout.list, R.id.usrName, data);
setListAdapter(adapter);
bindService(new Intent(GetMsgsScreen.this, RepeatService.class), mConnection, Context.BIND_AUTO_CREATE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getListView().setTextFilterEnabled(true);
}
#Override
protected void onDestroy() {
unbindService(mConnection);
super.onDestroy();
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
bg = ((RepeatService.MyBinder) binder).getService();
Toast.makeText(GetMsgsScreen.this, "Connected",
Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) {
bg = null;
}
};
public void onListItemClick(ListView parent, View v, int position, long id) {
Toast.makeText(getApplicationContext(), "You have selected "
+(position+1)+"th item", Toast.LENGTH_SHORT).show();
}
private class CustomAdapter extends ArrayAdapter<RowData> {
public CustomAdapter(Context context, int resource, int textViewResourceId, List<RowData> objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TextView name = null;
TextView messages = null;
ImageView i11=null;
RowData rowData= getItem(position);
if(null == convertView){
convertView = mInflater.inflate(R.layout.list, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
name = holder.gettitle();
name.setText(rowData.mName);
messages = holder.getdetail();
messages.setText(rowData.mMessage);
i11=holder.getImage();
i11.setImageResource(imgid[rowData.mId]);
return convertView;
}
private class ViewHolder {
private View mRow;
private TextView names = null;
private TextView messageText = null;
private ImageView i11=null;
public ViewHolder(View row) {
mRow = row;
}
public TextView gettitle() {
if(null == names){
names = (TextView) mRow.findViewById(R.id.usrName);
}
return names;
}
public TextView getdetail() {
if(null == messageText){
messageText = (TextView) mRow.findViewById(R.id.msgText);
}
return messageText;
}
public ImageView getImage() {
if(null == i11){
i11 = (ImageView) mRow.findViewById(R.id.img);
}
return i11;
}
}
}
}
I have implemented background service class as follows:
public class RepeatService extends Service
{
List<Message> resultMessage;
String[] userNameLatest = null;
String[] usrMessagesLatest = null;
String[] usrMessageID = null;
String msgID = null;
private Timer timer = new Timer();
private static final long UPDATE_INTERVAL = 500;
SQLiteDB db;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
pollForUpdates();
super.onCreate();
}
private void pollForUpdates() {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Log.v("!!!!!!!!!!!!!!!!", "service is calling");
msgID = getSharedPreferences("Values", 0).getString("msgid","");
resultMessage = new ParseXml().convertMessages(new Model().getMessages(msgID));
usrMessagesLatest = new String[resultMessage.size()];
userNameLatest = new String[resultMessage.size()];
usrMessageID = new String[resultMessage.size()];
db = new SQLiteDB();
for(int i=0;i<resultMessage.size();i++)
{
Log.v("RepeatService", "getMessageID------>"+resultMessage.get(i).getMessageID());
Log.v("RepeatService", "getMessageText------>"+resultMessage.get(i).getMessageText());
Log.v("RepeatService", "getUserFirstName------>"+resultMessage.get(i).getUserFirstName());
usrMessagesLatest[i] = resultMessage.get(i).getMessageText();
userNameLatest[i] = resultMessage.get(i).getUserFirstName();
usrMessageID[i] = resultMessage.get(i).getMessageID();
//Save the data into Sqlite db here
db.insertValues(usrMessageID[i], userNameLatest[i], usrMessagesLatest[i], RepeatService.this);
}
}
}, 0, UPDATE_INTERVAL);
Log.v(getClass().getSimpleName(), "Timer started.");
}
public class MyBinder extends Binder {
ShoutRepeatService getService()
{
return ShoutRepeatService.this;
}
}
}
The above class always run at back ground if any new record available from web service then store the record into Sqlite db.
From the above code i can save the data in to Sqlite data base then
How can i show the latest record to my ListView on My Activity class?
please any body help me with code explanation.........
I would probably use a BroadcastReceiver that is notified from the service when something new has been added. It could then update your list. Also look at LocalBroadcastManager since all the communication is in your app.

Resources