How to display image from url in json ListView? - android

ImageView is displayed but its not display all the list items, How to correct it ?
*this is the image view code *
try {
URL thumb_u = new URL("http://yathu.net46.net/uploads/19.jpg");
Drawable thumb_d = Drawable.createFromStream(thumb_u.openStream(), "src");
image.setImageDrawable(thumb_d);
}
catch (Exception e) {
// handle it
}
Full code below
public class Solutions extends Activity {
ArrayList<Person> arrayofWebData=new ArrayList<Person>();
class Person{
public String id;
public String Diseases_type, Treatments_type, desise_name, img_url;
}
FancyAdapter aa=null;
static ArrayList<String> resultRow;
public void onCreate(Bundle savedInstanceState){
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.solutions);
final String data = getIntent().getExtras().getString("Diseases_type");
String post_id = getIntent().getExtras().getString("id");
final String gen = getIntent().getExtras().getString("gen_id");
Toast.makeText(getApplicationContext(),
"Solution.java value is : "+post_id, Toast.LENGTH_LONG).show();
String result="";
try{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://yathu.net46.net/application/database/view_treadment.php");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("desise_id",post_id));
params.add(new BasicNameValuePair("gender_id",gen));
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response=httpclient.execute(httppost);
HttpEntity entity=response.getEntity();
InputStream webs= entity.getContent();
try{
BufferedReader reader= new BufferedReader(new InputStreamReader(webs,"iso-8859-1"),8);
StringBuilder sb= new StringBuilder();
String line=null;
while((line=reader.readLine())!=null){
sb.append(line+"\n");
}
webs.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result" + e.toString());
}
}catch(Exception e){
Log.e("log_tag","Error in http connection"+e.toString());
}
try{
JSONArray jArray=new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data=jArray.getJSONObject(i);
Person resultRow=new Person();
resultRow.id=json_data.getString("image");
resultRow.Treatments_type=json_data.getString("Treatments_type");
resultRow.desise_name=data+" - jPh;T "+(i+1);
resultRow.img_url="http://yathu.net46.net/uploads/"+json_data.getString("image");
arrayofWebData.add(resultRow);
}
}
catch(JSONException e){
Log.e("log_tag","Error parsing data"+e.toString());
}
final ListView myListView =(ListView)findViewById(R.id.solutionListView);
aa=new FancyAdapter();
myListView.setAdapter(aa);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
Person p = (Person) myListView.getItemAtPosition(position);
Log.i("SomeTag", "diseases_id: " + p.Treatments_type);
Log.i("SomeTag", "Tid: " + p.id);
Intent i = new Intent(Solutions.this, Single_diseases.class);
i.putExtra("diseases_id", p.Treatments_type);
i.putExtra("Tid", p.id);
i.putExtra("gend_id", gen);
i.putExtra("des_name", data);
Solutions.this.startActivity(i);
}
});
}
catch(Exception e){
Log.e("ERROR","ERROR IN CODE"+e.toString());
e.printStackTrace();
}
}
class FancyAdapter extends ArrayAdapter<Person> {
FancyAdapter(){
super(Solutions.this,android.R.layout.simple_list_item_1,arrayofWebData);
}
public View getView(int position,View convertView, ViewGroup parent){
ViewHolder holder;
if(convertView==null){
LayoutInflater inflater=getLayoutInflater();
convertView=inflater.inflate(R.layout.sol_list, null);
holder=new ViewHolder(convertView);
convertView.setTag(holder);
}
else{
holder=(ViewHolder)convertView.getTag();
}
holder.populateFrom(arrayofWebData.get(position));
return(convertView);
}
}
class ViewHolder{
public TextView desise_name=null;
public ImageView image = null;
public TextView showresult=null;
public TextView image_urldisplay=null;
int loader;
ImageLoader imgLoader;
public Activity activity = null;
ViewHolder(View row){
this.activity = activity;
Typeface font1 = Typeface.createFromAsset(getAssets(), "fonts/Bamini.ttf");
desise_name=(TextView)row.findViewById(R.id.solutions_types);
desise_name.setTypeface(font1);
showresult=(TextView)row.findViewById(R.id.showresult);
image_urldisplay=(TextView)row.findViewById(R.id.textView1);
image = (ImageView) findViewById(R.id.image);
}
void populateFrom(Person r){
desise_name.setText(r.desise_name);
showresult.setText(r.Treatments_type);
image_urldisplay.setText(r.img_url);
try {
URL thumb_u = new URL("http://yathu.net46.net/uploads/19.jpg");
Drawable thumb_d = Drawable.createFromStream(thumb_u.openStream(), "src");
image.setImageDrawable(thumb_d);
}
catch (Exception e) {
// handle it
}
}
}
}
Please help anyone

I can recommend a different way that works like a charm: Android Query.
You can download that JAR file from here
AQuery androidAQuery = new AQuery(this);
As an example:
androidAQuery.id(YOUR IMAGEVIEW).image(YOUR IMAGE TO LOAD, true, true, getDeviceWidth(), ANY DEFAULT IMAGE YOU WANT TO SHOW);
It's very fast and accurate, and using this you can find many more features like animation when loading, getting a bitmap (if needed), etc.

Related

onResume Does Not Update ListView With New Data

I am trying to update a ListView on previous fragment after back button press. The onResume is called (verified with Toast) and the webservice runs (listView is displayed after it is cleared). The problem is that the ListView is still showing old values and not new value after accessWebService_getUsername is called. I verify the values from MySQL and even though the DB is updated, the ListView only returns old values.
#Override
public void onResume() {
Toast.makeText(getActivity(), "onResume", Toast.LENGTH_SHORT).show();
super.onResume();
adapter.clear();
getIMEI();
accessWebService_getUsername();
adapter.notifyDataSetChanged();
}
Update:
//ListView
ListView lv =(ListView)view.findViewById(R.id.listView);
adapter = new ContactsAdapter(getActivity(), arrRequest_Contact, arrRequest_NameSurname, arrRequest_MessageCount, arrRequest_Time, arrRequest_Image);
lv.setAdapter(adapter);
// Json
private class JsonGetUsername extends AsyncTask<String, Void, String> {
//Pending 01
private ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPreExecute() {
this.dialog.setMessage("Loading Contacts, 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{
ListDrawer_getUsername(); //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_getUsername() {
JsonGetUsername task = new JsonGetUsername();
// passes values for the urls string array
task.execute(new String[] { "http://mywebsite/php/get_username.php?pIMEI="+IMEI});
}
// build hash set for list view
public void ListDrawer_getUsername() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("username_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
request_username = jsonChildNode.optString("Username");
}
accessWebService_getContacts();
} catch (JSONException e) {
System.out.println("Json Error Rooms" +e.toString());
//Toast.makeText(getApplicationContext(), "No Rooms To Load", Toast.LENGTH_SHORT).show();
}
}
UPDATE 2:
//ContactsAdpater
class ContactsAdapter extends ArrayAdapter<String>
{
Context context;
List<String> Request_Contact;
List<String> Request_NameSurname;
List<String> Request_MessageCount;
List<String> Request_Time;
List<String> Request_Image;
ContactsAdapter(Context c, List<String> Request_Contact, List<String> Request_NameSurname, List<String> Request_MessageCount, List<String> Request_Time, List<String> Request_Image)
{
super(c, R.layout.activity_contacts_single, R.id.textContact, Request_Contact);
this.context=c;
this.Request_Contact=Request_Contact;
this.Request_NameSurname=Request_NameSurname;
this.Request_MessageCount=Request_MessageCount;
this.Request_Time=Request_Time;
this.Request_Image=Request_Image;
}
#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_contacts_single, parent, false);
}
TextView txtContact = (TextView) row.findViewById(R.id.textContact);
TextView txtNameSurname = (TextView) row.findViewById(R.id.textNameSurname);
TextView txtMessageCount = (TextView) row.findViewById(R.id.textMessageCount);
TextView txtTime = (TextView) row.findViewById(R.id.textTime);
ImageView imageView = (ImageView) row.findViewById(R.id.imageView);
txtContact.setText(Request_Contact.get(position));
txtNameSurname.setText(Request_NameSurname.get(position));
txtMessageCount.setText(Request_MessageCount.get(position));
txtTime.setText(Request_Time.get(position));
Picasso.with(context).load(arrRequest_Image.get(position)).transform(new CircleTransform()).placeholder(R.drawable.ic_launcher).into(imageView);
return row;
}
}
You'll need to override the clear method in your ContactsAdapter to actually clear the lists you are storing your data in.
It looks like you'll need to clear all your lists, so if you add this to ContactsAdapter, your code should work as expected:
#Override
public void clear() {
super.clear();
Request_Contact.clear();
Request_NameSurname.clear();
Request_MessageCount.clear();
Request_Time.clear();
Request_Image.clear();
}

all images not displaying from the same url

Not all images are displaying when running my app. I am getting from json this result
{"result":[{"id":"1","name":null,"path":"http://api.androidhive.info/json/movies/1.jpg"},{"id":"2","name":null,"path":"http://www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"32","name":null,"path":"http://www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"31","name":null,"path":"http://www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"30","name":null,"path":"http://www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"29","name":null,"path":"http://www.justedhak.comlu.com/images/uploaded_images.jpg"}]}
the first 2 url images are displaying correctly in the app however the rest of the url are not displaying
these are working
[{"id":"1","name":null,"path":"http:\api.androidhive.info\json\movies\1.jpg"},{"id":"2","name":null,"path":"http:\justedhak.comlu.com\images\uploaded_images.jpg"}
these is my code of reading the image
//showlist() is under asynctask prePostExecute
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String id = c.getString(TAG_ID);
String url = c.getString(TAG_PATH);
Listitem.add(new Listitem(id,url));
}
GridViewAdapter adapter = new GridViewAdapter(this, R.layout.grid_item_layout, Listitem);
// gridView.setAdapter(gridAdapter);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://justedhak.comlu.com/get-data.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
I guess my error is here grid view adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(mcontext);
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.imageView = (ImageView) row.findViewById(R.id.imageView);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
Listitem item = getItem(position);
System.out.println(item.getUrl());
holder.imageTitle.setText(item.getId());
Picasso.
with(mcontext).
load(item.getUrl())
.placeholder(R.drawable.ic_launcher)
.fit()
.into(holder.imageView);
return row;
}
static class ViewHolder {
TextView imageTitle;
ImageView imageView;
}
}
upload
public void upload()
{
Calendar thisCal = Calendar.getInstance();
thisCal.getTimeInMillis();
// android.util.Log.i("Time Class ", " Time value in millisecinds "+ thisCal);
// Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
// ByteArrayOutputStream stream = new ByteArrayOutputStream();
// bmp.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
Intent intent = getIntent();
String selectedImage= intent.getStringExtra("imagePath");
Uri fileUri = Uri.parse(selectedImage);
// Uri selectedImage = intent.getData();
System.out.println(fileUri);
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(fileUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 30, stream);
byte[] byteArray = stream.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
imageview.setImageBitmap(bitmap);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
System.out.println(width);
System.out.println(height);
getResizedBitmap( bitmap, 200);
try {
stream.close();
stream = null;
} catch (IOException e) {
e.printStackTrace();
}
String image_str = Base64.encodeBytes(byteArray);
final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",image_str));
nameValuePairs.add(new BasicNameValuePair("caption",caption));
nameValuePairs.add(new BasicNameValuePair("name","je"));
nameValuePairs.add(new BasicNameValuePair("categorie",categorie));
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://justedhak.comlu.com/images/upload_image.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
final String the_string_response = convertResponseToString(response);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(AddImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
}
});
}catch(final Exception e){
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(AddImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
System.out.println("Error in http connection "+e.toString());
}
}
});
t.start();
}
Getting reference for GridView sample from here, I have just customized and tested loading all your images with it.
Item.java:
public class Item {
String imageUrl;
String title;
public Item(String imageUrl, String title) {
super();
this.imageUrl = imageUrl;
this.title = title;
}
public String getImageUrl() {
return imageUrl;
}
public String getTitle() {
return title;
}
}
CustomGridViewAdapter.java:
public class CustomGridViewAdapter extends ArrayAdapter<Item> {
Context context;
int layoutResourceId;
ArrayList<Item> data = new ArrayList<>();
public CustomGridViewAdapter(Context context, int layoutResourceId,
ArrayList<Item> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RecordHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RecordHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.item_text);
holder.imageItem = (ImageView) row.findViewById(R.id.item_image);
row.setTag(holder);
} else {
holder = (RecordHolder) row.getTag();
}
Item item = data.get(position);
holder.txtTitle.setText(item.getTitle());
Picasso.with(context).load(item.getImageUrl()).into(holder.imageItem);
return row;
}
static class RecordHolder {
TextView txtTitle;
ImageView imageItem;
}
}
And MainActivity.java:
customGridAdapter = new CustomGridViewAdapter(this, R.layout.row_grid, gridArray);
gridView.setAdapter(customGridAdapter);
String url = "http://justedhak.comlu.com/get-data.php";
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (response != null && !response.isNull("result")) {
try {
JSONArray jsonArray = response.getJSONArray("result");
if (jsonArray != null && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject != null && !jsonObject.isNull("path")) {
String imagePath = jsonObject.getString("path");
if (imagePath != null && !imagePath.isEmpty()) {
gridArray.add(new Item(imagePath,"BNK"));
}
}
}
customGridAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
});
queue.add(jsonObjectRequest);
Other files such as layout... I think you know already
Here is the screenshot
As per my study It's a bug that is reported to be fixed in the next release of the lib.
You can clone the repo of the lib and compile your own jar or wait.
I recommend you to take a look at Glide. Migrating from Picasso is quite trivial, it has better performance and it makes a nice smooth scrolling on lists.
Or try to remove .fit() from picasso.
Picasso.
with(mcontext).
load(item.getUrl())
.placeholder(R.drawable.ic_launcher)
.into(holder.imageView);
Hope it will help you.
You should normalize your Uri cause this seems to be to problem here.
Take a look at normalizeScheme() of the Uri class.
It fixes such problems regargng to upper/lowercase letters.
It will convert:
Http:\justedhak.comlu.com\images\uploaded_images.jpg
to
http:\justedhak.comlu.com\images\uploaded_images.jpg
If you want some more details you can take a look at this RFC 2396
Scheme names consist of a sequence of characters beginning with a
lower case letter and followed by any combination of lower case
letters[...]

Data varying in GridView in Android App

I am developing an Android app which displays information of different historical places. In my App, I have made a page to review and rate the place. The app is retrieving usernames, ratings, and comments from database and displaying it in a GridView. It is displaying correct number of comments but instead of displaying all the comments it duplicates some of the comments. Here is my code which retrieve data from database.
Can anyone tell what is the problem with my code??
class task extends AsyncTask<String, String, Void>
{
private ProgressDialog progressDialog = new ProgressDialog(Comments.this);
InputStream is = null ;
String result = "";
protected void onPreExecute()
{
if (get)
progressDialog.setMessage("Retrieving reviews...");
else
progressDialog.setMessage("Posting review...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener()
{
#Override
public void onCancel(DialogInterface arg0)
{
task.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params)
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
try
{
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//read content
is = httpEntity.getContent();
}
catch (Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
}
catch (Exception e)
{
// TODO: handle exception
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v)
{
try
{
if(get)
{
name=new ArrayList<String>();
comment=new ArrayList<String>();
rating=new ArrayList<Float>();
JSONArray Jarray = new JSONArray(result);
for(int i=0;i<Jarray.length();i++)
{
JSONObject Jasonobject = new JSONObject();
Jasonobject = Jarray.getJSONObject(i);
String names=null;
names=Jasonobject.getString("name");
name.add(names);
comment.add(Jasonobject.getString("comment"));
rating.add((float)Jasonobject.getDouble("rating"));
}
CustomGrid adapter = new CustomGrid(Comments.this, name,comment,rating);
grid.setAdapter(adapter);
get=false;
}
progressDialog.dismiss();
}
catch (Exception e)
{
// TODO: handle exception
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
Adapter Code:
public class CustomGrid extends BaseAdapter
{
private Context mContext;
private final ArrayList<String> name;
private final ArrayList<String> comment;
private final ArrayList<Float> rating;
public CustomGrid(Context c,ArrayList<String> name, ArrayList<String> comment, ArrayList<Float> rating )
{
mContext = c;
this.name= name;
this.comment = comment;
this.rating=rating;
}
#Override
public int getCount()
{
// TODO Auto-generated method stub
return comment.size();
}
#Override
public Object getItem(int position)
{
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
{
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid, null);
TextView textName = (TextView) grid.findViewById(R.id.grid_name);
TextView textComment = (TextView) grid.findViewById(R.id.grid_comment);
RatingBar ratingBar1 = (RatingBar)grid.findViewById(R.id.grid_rating);
textName.setText(name.get(position));
textComment.setText(comment.get(position));
ratingBar1.setRating(rating.get(position));
}
else
{
grid = (View) convertView;
}
return grid;
}
}
convertView is null just once. After you inflate and return it, due to the recycling mechanism of the GridView/ListView it will be never null again. What you are doing is assign to your TextViews the content of your dataset at position 0, and then return on of the pooled view with the same content over and over. Change your getView like:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.grid, null);
}
TextView textName = (TextView) convertView.findViewById(R.id.grid_name);
TextView textComment = (TextView) convertView.findViewById(R.id.grid_comment);
RatingBar ratingBar1 = (RatingBar)convertView.findViewById(R.id.grid_rating);
textName.setText(name.get(position));
textComment.setText(comment.get(position));
ratingBar1.setRating(rating.get(position));
return convertView;
}
also you probably want to look in the ViewHolder pattern, which makes your GridView/ListView scroll smoother

Json object displaying on listview

public ArrayList<String> getData()
{
ArrayList<String> listItems = new ArrayList<String>();
String result = "";
InputStream isr=null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/get_data.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
//resultView.setText("Couldnt connect to database");
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso- 8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++)
{
JSONObject json=jArray.getJSONObject(i);
listItems.add(json.getString("name"));
listItems.add(json.getString("ph.no"));
listItems.add(json.getString("id"));
// adding HashList to ArrayList
}
// resultView.setText(s);
} catch (Exception e)
{
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
return listItems;
// selecting single ListView item
}
I am developing an android application called phone book. I am extracting details of person
from sever as json object. Displaying details on android
I am able to display contact details of a particular person in different rows. How to display details of a single person on same row.
You can Customizing Android ListView Items with Custom ArrayAdapter.
You can do this way,
/* In main activity */
ListView myListView = (ListView)findViewById(R.id.myListView);
final ArrayList<Phonebook> todoItems = new ArrayList<Phonebook>();
final YourAdapter x= new YourAdapter(this,R.layout.your_listviewlayout,todoItems);
myListView.setAdapter(x);
Phonebook phnbk= new Phonebook();
// enter code for set values to Phonebook class variables
/* Inserting the values to array */
todoItems.add(phnbk);
/* Customized array adaptor class */
private class YourAdapter extends ArrayAdapter<Phonebook>
{
private ArrayList<Phonebook> items;
public YourAdapter (Context context, int textViewResourceId, ArrayList<Phonebook> items)
{
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
if (v == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.your_listviewlayout, null);
}
Phonebook o = items.get(position);
if (o != null)
{
//insert values to each text view in your list view layout
tv1.setText(o.name);
tv2.setText(o.phnnum);
tv3.setText(o.email);
}
return v;
}
}
/* Phonebook class */
public class Phonebook{
public String name;
public String phnnum;
public String email;
public Phonebook(){
super();
}
public Phonebook(String name, String phnnum, String email) {
super();
this.name = name;
this.phnnum = phnnum;
this.email = email;
}
}

how to maintain scroll position of listview when it updates

I have read plenty of examples ,but if I wish to maintain my scroll position after a ListView is updated from JSON ,then can I do that without using an AsyncTask instance ???
the code for my list is
String wrd;
//ArrayList<HashMap<String,String>> mylist;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent i2=getIntent();
wrd=i2.getStringExtra("entrd");
Log.v("keyis",wrd);
final Handler handler = new Handler();
Runnable runable = new Runnable() {
#Override
public void run() {
//call the function
LoadData();
//also call the same runnable
handler.postDelayed(this, 40000);
}
};
handler.postDelayed(runable, 10);
}public void LoadData(){
JSONObject j2=JSONfunctions.getJSONfromURL("/webservice_search.php?keyword="+wrd+"&format=json");
ArrayList<HashMap<String,String>> mylist = new ArrayList<HashMap<String,String>>();
try{JSONArray jray=j2.getJSONArray("listings");
for(int i=0;i<jray.length();i++){
Log.v("state","json data being read");
JSONObject j3= jray.getJSONObject(i);
String first=j3.getString("listing");
Log.v("sublist", first);
JSONObject j4=j3.getJSONObject("listing");
String sec=j4.getString("links");
int maxLength = (sec.length() < 30)?sec.length():27;
sec.substring(0, maxLength);
String cutsec=sec.substring(0,maxLength);
Log.v("links are",cutsec);
String img=j4.getString("image_name");
Log.v("image name is ",img);
//Uri dimg=Uri.parse("http://zeesms.info/android_app_images/Koala.jpg");
HashMap<String,String> map=new HashMap<String,String>();
map.put("Id",String.valueOf(i));
map.put(Li_nk,cutsec);
map.put(Image_name,j4.getString("image_name"));
map.put(KEY_THUMB_URL,"http://zeesms.info/android_app_images/"+img);
mylist.add(map);
}
}
catch(JSONException e){
Log.e("loG_tag","Error parsing"+e.toString());
}
LazyAdapter adapter = new LazyAdapter(this,mylist);
adapter.notifyDataSetChanged();
ListView list=(ListView)findViewById(R.id.lv1);
list.setEmptyView(findViewById(R.id.empty));
list.setAdapter(adapter);
list.setItemsCanFocus(false);
and my adapter is
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.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(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.custom_row_view1, null);
TextView title = (TextView)vi.findViewById(R.id.linkname); // merchnts name
TextView artist = (TextView)vi.findViewById(R.id.imagename); // address
//TextView duration = (TextView)vi.findViewById(R.id); // distance
ImageView thumb_image=(ImageView)vi.findViewById(R.id.mClogo); // logo
HashMap<String, String> jsn = new HashMap<String, String>();
jsn = data.get(position);
// Setting all values in listview
title.setText(jsn.get(Second.Li_nk));
artist.setText(jsn.get(Second.Image_name));
//duration.setText(song.get(CustomizedListView.KEY_DURATION));
imageLoader.DisplayImage(jsn.get(Second.KEY_THUMB_URL), thumb_image);
return vi;
}
and finally the class being used for json parsing is
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONObject jArray = null;
String str1="http://zeesms.info"+url;
// ArrayList<NameValuePair> namevaluepairs = new ArrayList<NameValuePair>();
Log.v("url result",url);
//namevaluepairs.add(new BasicNameValuePair("location",str1));
//http post
try{
HttpClient httpclient= new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(str1));
HttpResponse response = httpclient.execute(request);
is = response.getEntity().getContent();
if(is==null){
Log.v("url result","is null");
}
else
{
Log.v("url result","is not null");
}
/* BufferedReader buf = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder sb = new StringBuilder();
String s;
while(true )
{
s = buf.readLine();
if(s==null || s.length()==0)
break;
sb.append(s);
}
buf.close();
is.close();
sb.toString(); */
// httppost.setEntity(new UrlEncodedFormEntity(namevaluepairs));
//HttpResponse response=httpclient.execute(httppost);
//HttpEntity entity=response.getEntity();
//is=entity.getContent();
/*
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
*/
}catch(Exception e){
Log.v("log_tag", "Error in http connection "+e.toString());
AlertDialog.Builder alert=new AlertDialog.Builder(null);
alert.setMessage("Invalid Keyword").setPositiveButton("Ok", new OnClickListener(){
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
});
}
//convert response to string
try{
Log.v("url result","getting result starts");
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
Log.v("url result","getting result");
while ((line = reader.readLine()) != null) {
Log.v("url result","getting result");
sb.append(line + "\n");
}
is.close();
result=sb.toString();
Log.v("url result",result);
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
along with this if the data is updated from the webpage, what would be the simplest way to show the updated item on top ??
It is easier to maintain scroll position by calling notifydatasetchanged() only. The problem there is that you are creating a new adapter every time the data gets updated... you should do something like this:
if(listView.getAdapter()==null)
listView.setAdapter(myAdapter);
else{
myAdapter.updateData(myNewData); //update adapter's data
myAdapter.notifyDataSetChanged(); //notifies any View reflecting data to refresh
}
This way, your listview will mantain the scrolling position.
In case you want to scroll to a new position, use:
list.smoothScrollToPosition(int position);
In case for some reason you don't want to call notifyDataSetChanged(), the you can maintain the position by using setSelectionFromTop()
Before updating the adaptor:
lastViewedPosition = listView.getFirstVisiblePosition();
//get offset of first visible view
View v = listView.getChildAt(0);
topOffset = (v == null) ? 0 : v.getTop();
After updating the adaptor:
listView.setSelectionFromTop(lastViewedPosition, topOffset);
list.smoothScrollToPosition(int position); //my favorite :)
It may also help you to scroll nice'n'smooth to a particular item
listview.setSelection( i );
this will help you to set particular row at top
For overall picture:
In your API response callback, call this function(example) below:
MyAdapter mAdapter;
ArrayList<Users> mUsers;
private void updateListView(ArrayList<Users> users) {
mUsers.addAll(users);
if(mAdapter == null) {
mAdapter = new MyAdapter(getContext(), mUsers);
mListView.setAdapter(mAdapter);
}
mAdapter.notifyDataSetChanged(); // Add this one
}
If you're using an ArrayAdapter (or a subclass of it), the problem may be caused by that the adapter updates the list when you clean it before adding the new items:
adapter.clear();
adapter.addAll(...);
You can fix it by wrapping the code that modifies the adapter like this:
adapter.setNotifyOnChange(false); // Disable calling notifyDatasetChanged() on modification
adapter.clear();
adapter.addAll(...); // Notify the adapter about that data has changed. Note: it will re-enable notifyOnChange
adapter.notifyDataSetChanged();

Categories

Resources