Not Working notifyDataSetChanged() in BaseAdapter class - android

This is my code base adapter to set list item. My code in notifyDataSetChanged() not work. Delete Btn click to delete item of listview how can I change to work this code please help me
public class CustomListviewMyCartitem extends BaseAdapter {
ArrayList<Mycartitem> myList = new ArrayList<Mycartitem>();
LayoutInflater inflater;
Context context;
int loader = R.drawable.loader;
static int minteger = 0;
public String Response_code;
Mycartitem currentListData;
String cid, qcount;
UserSessionManager session;
String rem, b, userid, btntag;
public CustomListviewMyCartitem(Context context, ArrayList<Mycartitem> list) {
this.myList = list;
this.context = context;
inflater = LayoutInflater.from(context);
session = new UserSessionManager(context);
HashMap<String, String> user = session.getUserDetails();
userid = user.get(UserSessionManager.KEY_ID);
Log.e("", "#myList" + myList);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return myList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return myList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
/*
* public void updateReceiptsList() { myList.clear(); this.myList = list;
* this.notifyDataSetChanged(); }
*/
public void updateResults(ArrayList<Mycartitem> results) {
this.myList = results;
// Triggers the list update
this.notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.customcartlist, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
currentListData = myList.get(position);
mViewHolder.txtproductnamecart.setText(currentListData.getCategoryName());
mViewHolder.txtprizecart.setText("$" + currentListData.getCharge());
mViewHolder.txttotalitemcart.setText(currentListData.getQuantity());
mViewHolder.delete.setTag(currentListData.getCartItemId());
mViewHolder.delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
btntag = mViewHolder.delete.getTag() + "";
new DeleteItem().execute();
}
});
return convertView;
}
private class MyViewHolder {
TextView txtproductnamecart, txtprizecart, txttotalitemcart;
Button delete;
public MyViewHolder(View item) {
txtproductnamecart = (TextView) item.findViewById(R.id.txtproductnamecart);
txtprizecart = (TextView) item.findViewById(R.id.txtprizecart);
txttotalitemcart = (TextView) item.findViewById(R.id.txttotalitemcart);
delete = (Button) item.findViewById(R.id.btndelete);
}
}
private class DeleteItem extends AsyncTask<String, Void, Void> {
protected void onPreExecute() {
// Utils.Pdialog(Cart.this);
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
request();
return null;
}
protected void onPostExecute(Void unused) {
Utils.Pdialog_dismiss();
try {
JSONObject jsonObject;
jsonObject = new JSONObject(Response_code);
String msg = jsonObject.getString("status");
if (msg.equals("200")) {
JSONObject jsonArray = jsonObject.getJSONObject("payload");
updateResults(myList);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
Toast.makeText(context, "No item Found", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
private void request() {
try {
List<NameValuePair> values = new ArrayList<NameValuePair>(2);
values.add(new BasicNameValuePair("userId", userid));
values.add(new BasicNameValuePair("cartItemId", btntag));
values.add(new BasicNameValuePair("action", "singleItem"));
values.add(new BasicNameValuePair("cartId", Utils.CARTID));
Log.e("", "#Parameteruserid" + userid);
Log.e("", "#ParametercartItemId" + currentListData.getCartItemId());
Log.e("", "#Parameteaction" + "singleItem");
Log.e("", "#ParametercartId" + Utils.CARTID);
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient client = new DefaultHttpClient(httpParams);
String url = Utils.link + "index.php/api/deletecartitem/";
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(values));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Response_code = client.execute(httppost, responseHandler);
Log.e("Cart item delete Response :---", "CratItemDelete" + Response_code);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Instead of the method:
public void updateResults(ArrayList<Mycartitem> results) {
this.myList = results;
// Triggers the list update
this.notifyDataSetChanged();
}
Use the following method:
public void updateResults(ArrayList<Mycartitem> results) {
this.myList.clear();
this.myList.addAll(results);
// Triggers the list update
this.notifyDataSetChanged();
}

you are not updating myList variable. clear all the items from list and update with new items and then call notifyDatasetchange.

Related

LIstView Filter From Json Returns First Item Only Everytime

I tried to get help on this post without any luck, I played around with code but still no luck. My list for example is as follows: Blue, Red, Purple from Json remote server.
When I type B.. it returns Blue. OK
When I type X.. it returns no results because no color matched "X". OK
When I type R.. (or RE.. or RED) it returns Blue instead of returning Red.
Conclusion - The code always returns the first item on the list when filtered.
My code:
JSON:
private class JsonReadTask extends AsyncTask<String, Void, String> {
//Pending 01
private ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPreExecute() {
this.dialog.setMessage("Loading Rooms, Please Wait");
this.dialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getActivity(),"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
//Pending 02
if (dialog.isShowing()) {
dialog.dismiss();
}
adapter.notifyDataSetChanged();
try{
ListDrwaer(); //has ConnectionException (when it cannot reach server)
}catch (Exception e){
Toast.makeText(getActivity(), "Please check your connection..", Toast.LENGTH_LONG).show();
}
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { "http://www.website.com/file.php?psortby="+sortby});
}
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("room_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String request_title = jsonChildNode.optString("Title");
String request_members = jsonChildNode.optString("Members");
request_title_replaced = request_title.replace("room_", "");
arrRequest_Title.add(request_title_replaced);
arrRequest_Members.add(request_members);
}
} catch (JSONException e) {
System.out.println("Json Error Rooms" +e.toString());
//Toast.makeText(getApplicationContext(), "No Rooms To Load", Toast.LENGTH_SHORT).show();
}
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
Adapter:
class RoomsAdapter extends ArrayAdapter<String>
{
#Override
public void clear() {
super.clear();
arrRequest_Title.clear();
arrRequest_Members.clear();
}
Context context;
List<String> Request_Title;
List<String> Request_Members;
RoomsAdapter(Context c, List<String> Request_Title, List<String> Request_Members)
{
super(c, R.layout.activity_rooms_single, R.id.textTitle, Request_Title);
this.context=c;
this.Request_Title=Request_Title;
this.Request_Members=Request_Members;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row=convertView;
if(row==null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.activity_rooms_single, parent, false);
}
TextView txtTitle = (TextView) row.findViewById(R.id.textTitle);
TextView txtMembers = (TextView) row.findViewById(R.id.textMembers);
txtTitle.setText(Request_Title.get(position));
txtMembers.setText(Request_Members.get(position));
return row;
}
}
Fragment Class:
public class Fragment_01_Rooms extends Fragment

Add Update and Delete Item from Listview on Server Response Dynamically

Hi I don't know asking proper question or not but i want to develop Like Comment on Facebook post, Update comment and Delete Comment.
When i will add comment it will send request to server and it will give response with new values to fill in listadapter and that change may appear on my listview after click on enter or add button, and on delete it will send request to server and in response fill my listAdapter. and change may appear on my listview without refreshing listview. how can i perform this operation .
Thank You in Adavance.
Here is my Class.
public class CommmentActivity extends Activity{
DatabaseHandler db = new DatabaseHandler(this);
List<CommentListInfo> list_CommentInfo = new ArrayList<CommentListInfo>();
List<String> SuggetionList;
AutoCompleteTextView aCompletView;
EditText etComment;
String strComment;
ArrayAdapter<String> mentionList;
ListCommentAdapter commentAdapter;
ImageView IvAddComment;
ListView CommentList;
SessionCreator m_session;
boolean m = false;
boolean mBuzy;
int FirstPosition;
int ItemCounted;
int CurrentScrollState;
int TotalItemCount;
String UserId;
String VidoId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.commentvideo_main);
SuggetionList = new ArrayList<String>();
String Curl = GlobalMethod.TokenGenerator() + "&action=getCommentsVideo";
Intent data = getIntent();
UserId = data.getStringExtra("userId");
VidoId = data.getStringExtra("videoId");
init();
String strfriendsSyncDate = m_session.getfriendsSyncDate();
Log.d("mData", strfriendsSyncDate);
new CommentsDetail().execute(UserId,VidoId,strfriendsSyncDate,Curl,"1");
commentAdapter = new ListCommentAdapter(getApplicationContext(), list_CommentInfo);
CommentList.setAdapter(commentAdapter);
CommentList.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
switch (scrollState) {
case OnScrollListener.SCROLL_STATE_IDLE:{
commentAdapter.notifyDataSetChanged();
//ManipulateVisibleView(view);
break;
}
case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
{
mBuzy = true;
break;
}
case OnScrollListener.SCROLL_STATE_FLING:{
mBuzy = true;
break;
}
default:
break;
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
FirstPosition = firstVisibleItem;
ItemCounted = visibleItemCount;
TotalItemCount = totalItemCount;
int LastPosition = view.getLastVisiblePosition();
Log.d("First Position", ""+FirstPosition);
Log.d("ItemCountes",""+ItemCounted);
Log.d("totalItemCount",""+TotalItemCount);
Log.d("LastPosition",""+LastPosition);
if(visibleItemCount!=0 && ((firstVisibleItem+visibleItemCount)>=(totalItemCount))){
Log.d("mCalled", "call");
}
isScrollCompleted();
}
});
IvAddComment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
strComment = etComment.getText().toString();
etComment.getText().clear();
String strUrl = GlobalMethod.TokenGenerator() + "&action=addCommentsVideo";
new CommentsDetail().execute(UserId,VidoId,strComment,strUrl,"0");
commentAdapter.notifyDataSetChanged();
}
});
}
private void isScrollCompleted(){
if(this.ItemCounted >0 && this.CurrentScrollState == OnScrollListener.SCROLL_STATE_IDLE){
Log.d("ItemCounted",""+ItemCounted);
Log.d("CurrentScrollState",""+CurrentScrollState);
}
}
private void init() {
// TODO Auto-generated method stub
m_session = new SessionCreator(getApplicationContext());
etComment = (EditText)findViewById(R.id.etComments);
CommentList = (ListView)findViewById(R.id.lvLatestComments);
IvAddComment = (ImageView)findViewById(R.id.addComment);
}
public class CommentsDetail extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ServiceHandler serviceClient;
String mJsonString;
try{
String userId = (String)params[0];
String vId = (String)params[1];
if(params[4].equals("0")){
String comment = (String)params[2];
String strUrl = (String)params[3];
List<NameValuePair> paramsNameValuePairs = new ArrayList<NameValuePair>();
paramsNameValuePairs.add(new BasicNameValuePair("userId", userId));
paramsNameValuePairs.add(new BasicNameValuePair("videoId", vId));
paramsNameValuePairs.add(new BasicNameValuePair("commentText", comment));
serviceClient = new ServiceHandler();
mJsonString = serviceClient.makeServiceCall(strUrl,
ServiceHandler.POST, paramsNameValuePairs);
Log.i("---->>>>>>>>>>", paramsNameValuePairs + "");
}else{
String syncdate = (String)params[2];
String strUrl = (String)params[3];
List<NameValuePair> paramsNameValuePairs = new ArrayList<NameValuePair>();
paramsNameValuePairs.add(new BasicNameValuePair("userId", userId));
paramsNameValuePairs.add(new BasicNameValuePair("videoId", vId));
paramsNameValuePairs.add(new BasicNameValuePair("friendsSyncDate", syncdate));
serviceClient = new ServiceHandler();
mJsonString = serviceClient.makeServiceCall(strUrl,
ServiceHandler.POST, paramsNameValuePairs);
Log.i("---->>>>>>>>>>", paramsNameValuePairs + "");
}
Log.d("Response Json-----------------------",mJsonString );
return mJsonString;
}catch (Exception e) {
e.getStackTrace();
}
return null;
}
#SuppressWarnings({ "unchecked", "unchecked", "unchecked" })
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try{
if (result != null) {
JSONObject responsJsonObj = new JSONObject(result);
JSONObject jsonObj = (JSONObject) responsJsonObj
.optJSONObject("data");
try {
String str = jsonObj.getString("error");
if ( str != null || str.length() != 0) {
// error
//Toast.makeText(NewsfeedActivity.this, jsonObj.getString("error"),Toast.LENGTH_LONG).show();
return;
}
} catch (JSONException je) {
Log.d("jex ------>", "" + je.getMessage());
try {
String str = jsonObj.getString("message");
Log.d("message=", "" + str);
if ( str != null || str.length() != 0) {
// VALID RESPONSE, NOW PARSE IT
if (jsonObj.has("comments")) {
JSONArray colArray = jsonObj.getJSONArray("comments");
Log.d("Colunm Array", ""+colArray);
int nComments = colArray.length();
Log.d("# comments", "" + nComments);
for(int i=0; i<nComments; i++){
JSONObject obj = colArray.getJSONObject(i);
Gson Comments = new Gson();
String strComments = Comments.toJson(obj);
Log.d("# obj=", "" + obj.toString());
CommentListInfo cmtInfo = new CommentListInfo();
cmtInfo.c_userId = obj.getString("userId");
cmtInfo.c_name = obj.getString("name");
cmtInfo.DateAdded = obj.getString("dateAdded");
cmtInfo.CommentId = obj.getString("commentId");
cmtInfo.CommentText = obj.getString("text");
cmtInfo.ImageUrl = obj.getString("imageLink");
list_CommentInfo.add(cmtInfo);
}
}
}
if ( str != null || str.length() != 0) {
// VALID RESPONSE, NOW PARSE IT
if (jsonObj.has("addPosition")) {
Log.d("# obj=", "" + jsonObj.toString());
Log.d("Add Position", jsonObj.getString("addPosition"));
}
}
//
if ( str != null || str.length() != 0) {
// VALID RESPONSE, NOW PARSE IT
if (jsonObj.has("friendsSyncDate")) {
Log.d("# friendsDeleted", "" + jsonObj);
Log.d("# obj=", "" + jsonObj.toString());
String myString = m_session.getfriendsSyncDate();
Log.d("myString", myString);
m_session.putfriendsSyncDate(jsonObj.getString("friendsSyncDate"));
Log.d("Sync Date "," "+jsonObj.getString("friendsSyncDate"));
}
}
} catch (JSONException je2) {
je2.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Here is my Adapter Class.
public class ListCommentAdapter extends BaseAdapter{
private Context mContext;
private List<CommentListInfo> CommentsInfo;
private LayoutInflater inflater;
private String szUserId;
private String szVideoID;
private boolean mBuzy = false;
public ListCommentAdapter(Context context, List<CommentListInfo> cmtInfo) {
// TODO Auto-generated constructor stub
mContext = context;
CommentsInfo = cmtInfo;
AppData mmap = (AppData)this.mContext.getApplicationContext();
szUserId = mmap.getUserId();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return CommentsInfo.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return CommentsInfo.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
Holder holder = new Holder();
CommentListInfo c = CommentsInfo.get(position);
try{
Log.i("nUserId", c.c_userId);
Log.i("nName", c.c_name);
Log.i("nCommentId", c.CommentId);
Log.i("nCommnet", c.CommentText);
Log.i("nImageUrl",c.ImageUrl);
}catch(Exception e){
Log.e("Erore is",""+e);
}
try{
if(inflater==null){
inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if(convertView==null){
convertView = inflater.inflate(R.layout.comment_list_item, null);
holder.ciProfileImage = (CircleImageView)convertView.findViewById(R.id.civCFLeftPic);
holder.tvComments = (TextView)convertView.findViewById(R.id.tvCommentbox);
holder.tvCDate = (TextView)convertView.findViewById(R.id.tvCfNotifyDate);
holder.tvName = (TextView)convertView.findViewById(R.id.tvCommentName);
convertView.setTag(holder);
}else{
holder = (Holder)convertView.getTag();
}
if(!mBuzy){
RemoteImageLoader task = new RemoteImageLoader();
task.setImageView(holder.ciProfileImage);
task.execute(c.ImageUrl);
Log.d("ImagerUrl", c.ImageUrl);
if(c.ImageUrl!=null){
Picasso.with(mContext)
.load(R.drawable.world1)
.placeholder(R.drawable.world1)
.error(R.drawable.world1)
.into(holder.ciProfileImage);
}else{
Picasso.with(mContext)
.load(R.drawable.world1)
.placeholder(R.drawable.world1)
.error(R.drawable.world1)
.into(holder.ciProfileImage);
}
holder.tvComments.setText(c.CommentText);
holder.tvCDate.setText(c.DateAdded);
holder.tvName.setText(c.c_name);
holder.tvComments.setTag(null);
}else{
holder.tvComments.setText("Loading...");
holder.tvComments.setTag(this);
}
return convertView;
}catch(Exception e){
System.out.println("Error IS :- "+ e);
}
return convertView;
}
private static class Holder{
private TextView tvName,tvComments,tvCDate;
private CircleImageView ciProfileImage;
}
}
You might have solved this already but I was working on a different app in Java and came across something similar. Mine was a bit simpler because I am using a local database but ~same thing. In your CommmentActivity's onCreate method pull out the commentAdapter declaration and the CommentList.setOnScrollListener and put them in their own method. Then call your newly defined commentAdapter method in onCreate and after you parse through the response.
Something like this
public void myAdaperMethod(Context context, List<CommentListInfo> list_CommentInfo){
commentAdapter = new ListCommentAdapter(this, list_CommentInfo);
CommentList.setAdapter(commentAdapter);
CommentList.setOnScrollListener(new OnScrollListener(){...}
}
onCreate{
myAdapterMethod(...);
}
post{...}
get{myAdapterMethod(...);}
Hope that helps.
You just need to re-bind your control after the listadapter has the new dataset.
CommentList.DataBind();

listview is jerking on scrolling

i hv an application in which i am getting data from api,when data get loads and i tried to scroll the listview it get starts jerking,i tried to find the solution but get nothing.please help me to sort it out.
InboxActivity.java
list=(ListView)rootView.findViewById(R.id.list);
catagery = new ArrayList<ProfileInbox>();
String fontPath = "font/Roboto-Regular.ttf";
// Loading Font Face
Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), fontPath);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View arg1,
int position, long id) {
// TODO Auto-generated method stub
//arg0.getp.setBackgroundColor(Color.WHITE);
//parent.getChildAt(position).setBackgroundColor(Color.BLUE);
IsRead=true;
catagery.get(position).setRead(IsRead);
new Task().execute(url);
adapter.notifyDataSetChanged();
msg=catagery.get(position).getMessage();
dateFrom=catagery.get(position).getSentDate();
sub=catagery.get(position).getSubject();
Intent i= new Intent(getActivity(),InboxDetail.class);
startActivity(i);
}
});
return rootView;
}
private void loadNextPageOfReviews()
{
page_no_count += 1;
new JSONAsyncTask().execute(loadMoreUrl);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Please Wait, Loading...");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
// ------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("inbox");
String unread_msg= jsono.getString("unread_msg");
Log.i("unreadMsg", unread_msg);
for (int i = 0; i < jarray.length(); i++) {
JSONObject c = jarray.getJSONObject(i);
ProfileInbox category = new ProfileInbox();
String id = c.getString("msg_id");
String sub = c.getString("subject");
String name = c.getString("message");
String imageSetter=c.getString("sent_on");
//Log.i("id", id);
//Log.i("name", name);
//Log.i("imageSetter", imageSetter);
category.setMsgId(((JSONObject) c).getString("msg_id"));
if(unread_msg.contains(id)){
category.setRead(false);
}
else{
category.setRead(true);
}
category.setSubject(((JSONObject) c).getString("subject"));
category.setMessage(((JSONObject) c).getString("message"));
category.setSentDate(((JSONObject) c).getString("sent_on"));
//Log.i("category", category.toString());
catagery.add(category);
//Log.i("category", category.toString());
}
return true;
}
// ------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
if (result == false){
Toast.makeText(getActivity(),
"Unable to fetch data from server", Toast.LENGTH_LONG)
.show();
}
else if(Blank.notice.equals("true")){
msg=catagery.get(0).getMessage();
dateFrom=catagery.get(0).getSentDate();
sub=catagery.get(0).getSubject();
adapter = new InboxAdaptor(getActivity(),
catagery);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
Intent i= new Intent(getActivity(),InboxDetail.class);
startActivity(i);
}
else if(Blank.notice.equals("false"))
{
//adapter.notifyDataSetChanged();
adapter = new InboxAdaptor(getActivity(),
catagery);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
InboxAdapter
public class InboxAdaptor extends BaseAdapter {
private List<ProfileInbox> originalData;
private List<ProfileInbox> filteredData;
private Context context;
public static String url;
public static String bussinessId;
public InboxAdaptor(Context context, ArrayList<ProfileInbox> Data) {
this.context = context;
this.originalData = Data;
//Log.i("originalData", Data.toString());
filteredData = new ArrayList<ProfileInbox>();
filteredData.addAll(this.originalData);
//Log.i("filterData", filteredData.toString());
}
#Override
public int getCount() {
return filteredData.size();
}
#Override
public Object getItem(int position) {
return filteredData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.inboxlist, null,false);
holder.coloredlay=(RelativeLayout)convertView.findViewById(R.id.coloredlay);
holder.txtWelcom = (TextView) convertView.findViewById(R.id.txtWelcom);
holder.dateTime = (TextView) convertView.findViewById(R.id.dateTime);
holder.txtdetails = (TextView) convertView.findViewById(R.id.txtdetails);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
if(filteredData.get(position).getRead()==true)
{
holder.coloredlay.setBackgroundColor(Color.WHITE);
notifyDataSetChanged();
}else{
holder.coloredlay.setBackgroundColor(Color.parseColor("#E5E4E2"));
}
// holder.img.setTag(position);
String fontPath = "font/Roboto-Regular.ttf";
// Loading Font Face
Typeface tf = Typeface.createFromAsset(convertView.getContext().getAssets(), fontPath);
holder.txtWelcom.setText(filteredData.get(position).getSubject());
holder.txtWelcom.setTypeface(tf);
holder.dateTime.setText(filteredData.get(position).getSentDate());
holder.dateTime.setTypeface(tf);
holder.txtdetails.setText(filteredData.get(position).getMessage());
holder.txtdetails.setTypeface(tf);
/* if(Blank.notice.equals("true")){
holder.coloredlay.setBackgroundColor(Color.WHITE);
notifyDataSetChanged();
}
*/
notifyDataSetChanged();
return convertView;
}
public static class ViewHolder {
public RelativeLayout coloredlay;
public TextView txtdetails;
public TextView dateTime;
public TextView txtWelcom;
}
Remove notifyDataSetChanged() from getView() , notifyDataSetChanged() will update adapter when the data which you provided for your adapter has been changed , but you are using that wrong when a View of your list has been changed.
Remove notifyDataSetChanged() from getView().
You dot need that here. Rather have Remove notifyDataSetChanged() in onPostExecute() call back of JSONAsyncTask
Use cachecolorHint for come out of your solution:
<ListView
android:id="#+id/listNewsMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#android:color/transparent" >
</ListView>

how to insert json from server to sqlite

I am creating an application which works offline. My app is working fine in online mode and getting json from url. How can I make it work offline? How do I insert json from a url into SQLite? I want to get all data from a url first, then insert it in SQLite and then use database.
This is my complete code:
public class MainActivity extends Activity {
CategoryListAdapter3 cla;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
String URL, URL2;
String SelectMenuAPI;
String _response;
String status;
GridView gridview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridview = (GridView) findViewById(R.id.gridview);
cla = new CategoryListAdapter3(MainActivity.this);
new TheTask().execute();
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(MainActivity.this,
Subcategory.class);
iMenuList.putExtra("Category_ID",
Category_ID.get(position));
iMenuList.putExtra("Category_name",
Category_name.get(position));
startActivity(iMenuList);
}
});
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class TheTask extends AsyncTask<Void, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... arg0) {
SelectMenuAPI = "http://www.syddddds.pk/beta7/_webservices
/mobile_api.php?response=getmaincategories";
clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
Log.i("url", "" + URL2);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
HttpEntity resEntity = response.getEntity();
_response = EntityUtils.toString(resEntity);
} catch (Exception e) {
e.printStackTrace();
}
return _response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject json2 = new JSONObject(result);
status = json2.getString("Status");
if (status.equals("1")) {
JSONArray school2 = json2.getJSONArray("data");
//
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
Category_ID.add(Long.parseLong(object .getString("category_id")));
Category_name.add(object.getString("name"));
Category_image.add(object.getString("image_path"));
}
}
else {
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
gridview.setAdapter(cla);
cla.notifyDataSetChanged();
}
}
public class CategoryListAdapter3 extends BaseAdapter {
private Activity activity;
private AQuery androidAQuery;
public CategoryListAdapter3(Activity act) {
this.activity = act;
// imageLoader = new ImageLoader(act);
}
public int getCount() {
// TODO Auto-generated method stub
return MainActivity.Category_ID.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
androidAQuery = new AQuery(getcontext());
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.viewitem2, null);
holder = new ViewHolder();
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtText = (TextView) convertView.findViewById(R.id.title2);
holder.imgThumb = (ImageView) convertView.findViewById(R.id.image2);
holder.txtText.setText(MainActivity.Category_name.get(position));
androidAQuery.id(holder.imgThumb).image(MainActivity.Category_image.get(position),
true, true);
return convertView;
}
private Activity getcontext() {
// TODO Auto-generated method stub
return null;
}
static class ViewHolder {
TextView txtText;
ImageView imgThumb;
}
}

Http image parsing problem

I'm trying to set different images by parsing, but I can set only last image. I don't know where the problem is in this code:
public class GridActivity extends Activity{
private EfficientAdapter adap;
String strUrl;
AddAlbumDetailBean aBean;
XmlParser parser;
ArrayList<Object> result;
ArrayList<Object> data;
ImageButton btnAdd;
private Context context;
static Bitmap bitmap;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
Utils.onActivityCreateSetTheme(this);
setContentView(R.layout.photos_activity);
GridView gView = (GridView)findViewById(R.id.gridview);
adap = new EfficientAdapter(this);
gView.setAdapter(adap);
/*btnAdd = (ImageButton)findViewById(R.id.btnAddPhotos);
btnAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(GridActivity.this,AddAlbum.class));
}
});
*/
}
public static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context context;
String strUrl;
AddAlbumDetailBean aBean;
XmlParser parser;
ArrayList<Object> result;
public EfficientAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
this.context = context;
String userId = ConstantData.user_id;
String albumId = ConstantData.album_id;
int pageNo = 1;
int limit = 20;
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.5.10/ijoomer_development/index.php?option=com_ijoomer&plg_name=jomsocial&pview=album&ptask=photo_paging&userid="+ ConstantData.user_id +"&sessionid="+ ConstantData.session_id +"&tmpl=component&albumid="+ ConstantData.album_id +"&pageno=1&limit=20");
StringBuffer strBuffer = new StringBuffer("<data><userid>" + userId + "</userid><albumid>" + albumId + "</albumid><pageno>" + pageNo +"</pageno><limit>"+ limit +"</limit></data>");
StringEntity strEntity = new StringEntity(strBuffer.toString());
post.setEntity(strEntity);
HttpResponse response = client.execute(post);
InputStream in = response.getEntity().getContent();
String strResponse = convertStreamToString(in);
parser = new XmlParser(in, new AddAlbumDetailBean());
result = parser.parse("data", "data");
String startThumb ="<thumb>";
String endThumb = "</thumb>";
String startUrl = "<url>";
String endUrl = "</url>";
if (startThumb.equalsIgnoreCase("<thumb>") && endThumb.equalsIgnoreCase("</thumb>"))
{
int startT = strResponse.indexOf(startThumb);
int endT = strResponse.indexOf(endThumb);
Log.i("startThumb", ""+startT);
Log.i("endThumb", ""+endT);
String OldThumb = strResponse.substring(startT, endT);
int startUrlindex = OldThumb.indexOf(">");
String thumb = OldThumb.substring(startUrlindex + 1).trim();// getting Url from webservice
Log.i("Thu0mb", ""+thumb);
URL newurl = new URL(thumb);
bitmap = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());// converting Url into Bitmap but dont know how to use bitmap array here
Log.d("Bitmap in ConstantData", ""+bitmap);
}
if (startUrl.equalsIgnoreCase("<url>") && endUrl.equalsIgnoreCase("</url>"))
{
int startL = strResponse.indexOf(startUrl);
int endL = strResponse.indexOf(endUrl);
Log.i("startUrl", ""+startL);
Log.i("endUrl", ""+endL);
String OldUrl = strResponse.substring(startL, endL);
int startUrlindex = OldUrl.indexOf(">");
String url = OldUrl.substring(startUrlindex + 1).trim();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.icon, null);
holder = new ViewHolder();
holder.iconImage = (ImageView) convertView.findViewById(R.id.icon_image);
convertView.setOnClickListener(new OnClickListener() {
private int pos = position;
#Override
public void onClick(View v) {
Toast.makeText(context, "Click-" + String.valueOf(pos), Toast.LENGTH_SHORT).show();
context.startActivity(new Intent(context,GridActivity.class));
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Log.d("Bitmap in ConstantData", ""+bitmap);
holder.iconImage.setImageBitmap(bitmap);
return convertView;
}
static class ViewHolder {
ImageView iconImage;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 5; // if i m trying to return result.size(); getting error and returning 5 i can only get 5 images
}
#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 String convertStreamToString(InputStream in)
throws IOException {
if (in != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
// in.close();
}
return writer.toString();
} else {
return "";
}
}
}
Through this code i am trying to set image into the dynamic gridview using adapter....
but i can set only last image into the gridview so i dont know how to use bitmap array
There are a lot of problems on your code:
your bitmap is static, so you overriding it...
you have no loop, so you have only the same bitmap "parsed"
(after that I stopped looking)
Try to clean up your code and try to debug step by step so that you understand what your code does...
update:
some tips:
use AsyncTask to request the XML and parse it there
when finished fill the adapter with the parsed image urls

Categories

Resources