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
Related
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.
I'm trying to parse a JSON result from a URL in my Android app.
I have tried a few examples on the Internet, but can't get it to work.
What's the simplest way to fetch the URL and parse the JSON data show it in the listview
Json data :
[{"MemberID":"1","Username":"weerachai","Password":"12345","Name":"Weerachai
Nukitram","Tel":"0819876107","Email":"weerachai#gmail.com"},{"MemberID":"2","Username":"adisorn","Password":"ac143","Name":"Adisorn
Bunsong","Tel":"021978032","Email":"adisorn#gmail.com"},{"MemberID":"3","Username":"surachai","Password":"gg111","Name":"Surachai
Sirisart","Tel":"0876543210","Email":"surachai#gmail.com"}]
Android code :
public class MainActivity extends AppCompatActivity {
ArrayList<HashMap<String, String>> MyArrList;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ShowData();
// btnSearch
final Button btnSearch = (Button) findViewById(R.id.btnSearch);
//btnSearch.setBackgroundColor(Color.TRANSPARENT);
// Perform action on click
btnSearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ShowData();
}
});
}
public void ShowData()
{
// listView1
final ListView lisView1 = (ListView)findViewById(R.id.listView1);
// keySearch
EditText strKeySearch = (EditText)findViewById(R.id.txtKeySearch);
// Disbled Keyboard auto focus
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);imm.hideSoftInputFromWindow(strKeySearch.getWindowToken(), 0);
String url = "http:...............php";
// Paste Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("txtKeyword", strKeySearch.getText().toString()));
try {
JSONArray data = new JSONArray(getJSONUrl(url,params));
MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("MemberID", c.getString("MemberID"));
map.put("Username", c.getString("Username"));
map.put("Password", c.getString("Password"));
map.put("Name", c.getString("Name"));
map.put("Email", c.getString("Email"));
map.put("Tel", c.getString("Tel"));
MyArrList.add(map);
}
lisView1.setAdapter(new ImageAdapter(this));
// OnClick Item
lisView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int position, long mylng) {
String sMemberID = MyArrList.get(position).get("MemberID").toString();
String sName = MyArrList.get(position).get("Name").toString();
String sTel = MyArrList.get(position).get("Tel").toString();
Intent newActivity = new Intent(MainActivity.this,DetailActivity.class);
newActivity.putExtra("MemberID", sMemberID);
startActivity(newActivity);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
// TODO Auto-generated method stub
context = c;
}
public int getCount() {
// TODO Auto-generated method stub
return MyArrList.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(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_column, null);
}
// ColMemberID
TextView txtMemberID = (TextView) convertView.findViewById(R.id.ColMemberID);
txtMemberID.setPadding(10, 0, 0, 0);
txtMemberID.setText(MyArrList.get(position).get("MemberID") +".");
// R.id.ColName
TextView txtName = (TextView) convertView.findViewById(R.id.ColName);
txtName.setPadding(5, 0, 0, 0);
txtName.setText(MyArrList.get(position).get("Name"));
// R.id.ColTel
TextView txtTel = (TextView) convertView.findViewById(R.id.ColTel);
txtTel.setPadding(5, 0, 0, 0);
txtTel.setText(MyArrList.get(position).get("Tel"));
return convertView;
}
}
public String getJSONUrl(String url,List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Download OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
}
Call BaseAdapter In Fragment Close Application
Comment in line spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
Work
Error Log
Class FragmentNews
public class FragmentNews extends Fragment {
ArrayList<Category> categorylist = new ArrayList<Category>();
#Override
public View onCreateView(final LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
final View rootView = inflater.inflate(R.layout.fragment_news,
container, false);
Spinner spinner = (Spinner) rootView.findViewById(R.id.category);
new fechPosts().execute("");
return rootView;
}
class fechPosts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
ringProgressDialog = new ProgressDialog(getActivity());
ringProgressDialog.setMessage("در حال ارسال پیام");
ringProgressDialog.setCancelable(true);
ringProgressDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result = fetch(params[0]);
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Activity myActivity = getActivity();
spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
ringProgressDialog.dismiss();
}
}
public String fetch(String titel) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = null;
httppost = new HttpGet(
"http://mynikan.ir/paliz/mobile/GetAllProduct.php");
String r = "ok";
String result = null;
InputStream inputStream = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
JSONArray array = null;
try {
array = new JSONArray(result);
} catch (JSONException e) {
e.printStackTrace();
}
if (array.length() != 0) {
for (int i = 0; i < array.length(); i++) {
JSONObject json_data;
try {
json_data = array.getJSONObject(i);
Category obj = new Category();
obj.Image = json_data.getString("Product_Image");
obj.Title = json_data.getString("Price");
categorylist.add(obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return r;
}
Class Adapter
public class Category_Adapter extends BaseAdapter {
public String[] items;
public LayoutInflater myinflater;
Context context;
static class ViewHolder
{
TextView text;
TextView price;
ImageView im;
}
public int[] picmenu;
ArrayList<Category> categorylist = new ArrayList<Category>();
public Category_Adapter(Context c, ArrayList<Category> pthemop) {
myinflater = LayoutInflater.from(c);
context = c;
categorylist = pthemop;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return categorylist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
// /////
if (convertView == null) {
convertView = myinflater.inflate(R.layout.snipper_single, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.im = (ImageView) convertView.findViewById(R.id.image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(categorylist.get(position).Title);
Picasso.with(context).load(categorylist.get(position).Image)
.into(holder.im);
return convertView;
}}
Class Category
public class Category {
String Title;
String Image;
}
Here:
spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
line causing issue because spinner object of Spinner is null.
In onCreateView method creating new object instead of initializing object which is using in spinner.
Change onCreateView method as:
spinner = (Spinner) rootView.findViewById(R.id.category);
new fechPosts().execute("");
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();
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;
}
}