I'm trying to add an animation to my ListView so text will fade into separate rows as results come in from an HTTP GET request. I know how to do the fade in effect and i already have a custom ListView adapter but the problem is that the ListView updates all the rows each time a result comes in, thus triggering the fade in effect each time for the entire list.
How would I be able to control a single row so the ListView won't animate every row on each data change?
This is the code i use to fill the ListView:
private class CustomAdapter extends ArrayAdapter<Row> {
public CustomAdapter() {
super(Results.this, R.layout.row, dataList);
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RowHolder holder = null;
if (row == null) {
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.row, parent, false);
holder = new RowHolder(row);
row.setTag(holder);
} else {
holder = (RowHolder) row.getTag();
}
try {
holder.populateRow(dataList.get(position));
} catch (NullPointerException e) {
e.printStackTrace();
}
return row;
}
}
private class RowHolder {
private TextView label = null;
private TextView count = null;
private TextView result = null;
public RowHolder(View row) {
label = (TextView) row.findViewById(R.id.list_label);
count = (TextView) row.findViewById(R.id.list_count);
result = (TextView) row.findViewById(R.id.list_result);
}
public void populateRow(Row r) {
label.setText(r.getLabel());
count.setText(r.getCount());
result.setText(r.getResult());
label.startAnimation(fadeIn);
count.startAnimation(fadeIn);
result.startAnimation(fadeIn);
}
}
Any help is appreciated, thank you in advance!
Edit 1:
My AsyncTask:
private class CheckSource extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
results.setUnixTime(getUnixTime());
results.setLabel(getString(R.string.label));
results.setCount(null);
results.setResult(null);
results.setResultLabel("");
results.setShowProgress(true);
results.setIconType(null);
results.setShowIcon(false);
results.setHasResults(false);
adapter.notifyDataSetChanged();
}
#Override
protected String doInBackground(String... params) {
String query = params[0];
String httpResults = null;
try {
httpResults = getResults(query, "source");
jsonObject = new JSONObject(httpResults);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return httpResults;
}
protected void onPostExecute(String results) {
try {
parseJSON(results);
} catch (JSONException e) {
e.printStackTrace();
results.setResultLabel("<br />"
+ getString(R.string.source_not_available) + "<br />");
}
results.setShowProgress(false);
adapter.notifyDataSetChanged();
}
// Parse the retrieved json results
private void parseJSON(String jsonResults) throws JSONException {
if (jsonResults == null) {
results.setResult(null);
results.setHasResults(false);
results.setResultLabel("<br />"
+ getString(R.string.source_not_available) + "<br />");
return;
}
jsonObject = new JSONObject(jsonResults);
String result = null;
String resultLabel = null;
switch (jsonObject.getInt("count")) {
case -1:
results.setCount(null);
results.setHasResults(false);
resultLabel = getString(R.string.no_results);
break;
case 0:
results.setCount(null);
results.setHasResults(false);
resultLabel = getString(R.string.no_results);
break;
case 1:
results.setHasResults(true);
results.setCount(jsonObject.get("count").toString() + " "
+ getString(R.string.one_result));
result = jsonObject.get("url").toString();
resultLabel = getString(R.string.hyperlink_text);
break;
default:
results.setHasResults(true);
results.setCount(jsonObject.get("count").toString() + " "
+ getString(R.string.multiple_results));
result = jsonObject.get("url").toString();
resultLabel = getString(R.string.hyperlink_text);
break;
}
results.setResult(result);
results.setResultLabel("<br />" + resultLabel + "<br />");
}
}
The method that executes the HTTP request:
private String getResults(String query, String source)
throws IllegalStateException, IOException, URISyntaxException {
/* Method variables */
StringBuilder builder = new StringBuilder();
String URL = "url";
URI uri;
String phrase = "phrase";
List<NameValuePair> params = new ArrayList<NameValuePair>();
/* HTTP variables */
HttpGet httpGet;
DefaultHttpClient httpClient;
HttpResponse httpResponse;
HttpEntity httpEntity;
HttpParams httpParams;
int socketTimeout = 10000;
int connectionTimeout = 10000;
// Set the socket and connection timeout values
httpParams = new BasicHttpParams();
HttpConnectionParams
.setConnectionTimeout(httpParams, connectionTimeout);
HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
httpClient = new DefaultHttpClient(httpParams);
// Add parameters to the GET request
params.add(new BasicNameValuePair("query", query));
params.add(new BasicNameValuePair("type", source));
String paramString = URLEncodedUtils.format(params, "utf-8");
uri = new URI(URL + paramString);
httpGet = new HttpGet(uri);
// Execute the GET request
httpResponse = httpClient.execute(httpGet);
/* Read http response if http status = 200 */
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
httpEntity = httpResponse.getEntity();
InputStream content = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
return builder.toString();
}
As Romain Guy explained a while back during the Google I/O session, the most efficient way to only update one view in a list view is something like the following (this one update the whole view data):
ListView list = getListView();
int start = list.getFirstVisiblePosition();
for(int i=start, j=list.getLastVisiblePosition();i<=j;i++)
if(target==list.getItemAtPosition(i)){
View view = list.getChildAt(i-start);
list.getAdapter().getView(i, view, list);
break;
}
Assuming target is one item of the adapter.
This code retrieve the ListView, then browse the currently shown views, compare the target item you are looking for with each displayed view items, and if your target is among those, get the enclosing view and execute the adapter getView on that view to refresh the display.
As a side note invalidate doesn't work like some people expect and will not refresh the view like getView does, notifyDataSetChanged will rebuild the whole list and end up calling getview for every displayed items and invalidateViews will also affect a bunch.
One last thing, one can also get extra performance if he only needs to change a child of a row view and not the whole row like getView does. In that case, the following code can replace list.getAdapter().getView(i, view, list); (example to change a TextView text):
((TextView)view.findViewById(R.id.myid)).setText("some new text");
In code we trust.
Method notifyDataSetChanged force to call getView method to all visible elements of the ListView. If you want update only 1 specific item of the ListView you need to path this item to the AsynhTask.
Related
I need to delete a list item from listview on clicking a delete button in android eclipse. The list values are populated from mysql database(JSON), so on deleting, I need to delete the same from database also.
Here is my main Activity; I need to delete a listitem from a listview on clicking a delete button on each item in the listview:
public class MainActivity extends Activity implements AsyncResponse2 {
private ProgressDialog dialog;
ListView l1;
//for getting count
TextView count;
private static final String TAG_COUNT = "cnt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //to hide title bar
setContentView(R.layout.activity_main);
l1=(ListView)findViewById(R.id.listView1);
/** Reference to the delete button of the layout main.xml */
Button btnDel = (Button) findViewById(R.id.deleteid);
initView();
//str for getting count
count=(TextView)findViewById(R.id.countid);
//to display count while loading(so outside buttonclick)
String key1 = "saasvaap123";
String signupid1 = "8";
String url2 = "http://gooffers.in/omowebservices/index.php/webservice/Public_User/saved_offers_list?";
//http://gooffers.in/omowebservices/index.php/webservice/Public_User/saved_offers_list?key=saasvaap123&signup_id=8
//put the below lines outside button onclick since we load the values into edittext when opening the app
CustomHttpClient2 task2 = new CustomHttpClient2();
task2.execute(url2,key1,signupid1);
task2.delegate = MainActivity.this;
//end
}
//str getting count
//str customhttp2
private class CustomHttpClient2 extends AsyncTask<String, String, String>{
public AsyncResponse2 delegate=null;
private String msg;
#Override
protected void onPostExecute(String result2) {
// TODO Auto-generated method stub
super.onPostExecute(result2);
delegate.processFinish2(result2);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
if(params == null) return null;
// get url from params
String url2 = params[0];
String key1 = params[1];
String signupid1 = params[2];
ArrayList<NameValuePair> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key",key1));
postParameters.add(new BasicNameValuePair("signup_id",signupid1));
try {
// create http connection
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url2);
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// connect
HttpResponse response = client.execute(httppost);
// get response
HttpEntity entity = response.getEntity();
if(entity != null){
return EntityUtils.toString(entity);
}
else{
return "No string.";
}
}
catch(Exception e){
return "Network problem";
}
}
}
public void processFinish2 (String output2){
Toast.makeText(MainActivity.this,output2, Toast.LENGTH_SHORT).show();
try{
//str
JSONObject jsonResponse = new JSONObject(output2);
JSONArray aJson = jsonResponse.getJSONArray("gen_off");
// create apps list
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
//end
//str
String strCount = json.getString(TAG_COUNT);
count.setText(strCount);//setting name to original name text
//end
}
}catch (JSONException e) {
Toast.makeText(MainActivity.this,"Exception caught!", Toast.LENGTH_SHORT).show();
}
}
//end getting count
private void initView() {
// show progress dialog
// dialog = ProgressDialog.show(this, "", "Loading...");
String key="saasvaap123";
String signup_id="8";
String url = "http://gooffers.in/omowebservices/index.php/webservice/Public_User/saved_offers_list?";
FetchDataTask task = new FetchDataTask();
task.execute(url,key,signup_id);
}
public class FetchDataTask extends AsyncTask<String, Void, String>{
// private final FetchDataListener listener;
private String msg;
#Override
protected String doInBackground(String... params) {
if(params == null) return null;
// get url from params
String url = params[0];
String key1 = params[1];
String signupid1 = params[2];
ArrayList<NameValuePair> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key",key1));
postParameters.add(new BasicNameValuePair("signup_id",signupid1));
//str
try {
// create http connection
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// connect
HttpResponse response = client.execute(httppost);
// get response
HttpEntity entity = response.getEntity();
if(entity != null){
return EntityUtils.toString(entity);
}
else{
return "No string.";
}
}
catch(Exception e){
return "Network problem";
}
}
//end
//
#Override
protected void onPostExecute(String sJson) {
try {
JSONObject jsonResponse = new JSONObject(sJson);
JSONArray aJson = jsonResponse.getJSONArray("gen_off");
Toast.makeText(MainActivity.this, aJson.toString(),Toast.LENGTH_SHORT).show();
// create apps list
List<SavedOffers> apps = new ArrayList<SavedOffers>();
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
SavedOffers app = new SavedOffers();
app.setTitle(json.getString("title"));
app.setOriginalRate(json.getString("price"));
app.setOfferRate(json.getString("off_price"));
app.setPercentage(json.getString("percent"));
app.setSavings(json.getString("savings"));
app.setUrl(json.getString("image"));
// add the app to apps list
apps.add(app);
}
SavedOffersAdapter adapter = new SavedOffersAdapter(MainActivity.this, apps);
// set the adapter to list
l1.setAdapter(adapter);
//for delete
// adapter.notifyDataSetChanged();
/** Defining a click event listener for the button "Delete" */
Button btnDel = (Button) findViewById(R.id.deleteid);
OnClickListener listenerDel = new OnClickListener() {
#Override
public void onClick(View v) {
/** Getting the checked items from the listview */
SparseBooleanArray checkedItemPositions = l1.getCheckedItemPositions();
int itemCount = l1.getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
adapter.remove(l1.get(i));
}
}
checkedItemPositions.clear();
adapter.notifyDataSetChanged();
}
};
/** Setting the event listener for the delete button */
btnDel.setOnClickListener(listenerDel);
/** Setting the adapter to the ListView */
l1.setAdapter(adapter); //end delete
//notify the activity that fetch data has been complete
// if(listener != null) listener.onFetchComplete(apps);
} catch (JSONException e) {
// msg = "Invalid response";
// if(listener != null) listener.onFetchFailure(msg);
// return;
}
}
/**
* This function will convert response stream into json string
* #param is respons string
* #return json string
* #throws IOException
*/
public String streamToString(final InputStream is) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch (IOException e) {
throw e;
}
finally {
try {
is.close();
}
catch (IOException e) {
throw e;
}
}
return sb.toString();
}
}
}
// this is my adapter class , I think change is only needed in main activity
// , I need to delete a specific list item from listview on clicking the delete button
public class SavedOffersAdapter extends ArrayAdapter<SavedOffers>{
private List<SavedOffers> items;
Bitmap bitmap;
ImageView image;
public SavedOffersAdapter(Context context, List<SavedOffers> items) {
super(context, R.layout.app_custom_list, items);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
private class ViewHolder {
//TextView laptopTxt;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// ViewHolder holder;//added
View v = convertView;
if(v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.app_custom_list, null);
}
SavedOffers app = items.get(position);
if(app != null) {
TextView productName = (TextView)v.findViewById(R.id.nameid);
TextView originalRate = (TextView)v.findViewById(R.id.originalid);
originalRate.setPaintFlags(originalRate.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
TextView offerRate = (TextView)v.findViewById(R.id.offerid);
TextView percentage = (TextView)v.findViewById(R.id.discountid);
TextView savings = (TextView)v.findViewById(R.id.savingsid);
image =(ImageView)v.findViewById(R.id.prctimgid);
if(productName != null) productName.setText(app.getTitle());
if(originalRate != null) originalRate.setText(app.getOriginalRate());
if(offerRate != null) offerRate.setText(app. getOfferRate());
if(percentage != null) percentage.setText(app. getPercentage());
if(savings != null) savings.setText(app. getSavings());
if(image!=null){
new DownloadImageTask(image).execute(app.getUrl());
}
}
return v;
}
In your listviews adapter's getView method you link to the button on the layout your inflating and just attach a setOnClickListener... to the button and have it remove that item from your list or array that your adapter uses and then notifyDataHasChanged.
Delete that item from items in that position.
So 1. you want to delete the item from the ListView
2. you want to delete the item from the SQL DB.
The first one is very easy, but you kind of need to know the underlining adapter and how it serves data to your ListView. When you instantiate a BaseAdapter for the ListView you pass in a List or an array. This array will be the data your BaseAdapter serves to your ListView, each view in the listview will be showing an element from the array (done in getView()). If you dynamically delete one of those items, then adjust your array (or just use a List and it's .remove(), and finally notifyDataSetChanged(); your BaseAdapter will refresh your list without that View (or rather that View will be replaced with the new one). So for instance below I pass in a List<WeatherLocation> (WeatherLocation is a containing class that has weather stuff for a particular area (city, zipcode, degree"Biddeford", 04005, 72) to my BaseAdapter.
// Instantiate ListView
ListView lvLocations = (ListView) findViewById(R.id.lvLocations);
// Instantiate our BaseAdapter (pass in the List<WeatherLocation>)
WeatherLocationAdapter mWeatherLocationAdapter = new WeatherLocationAdapter(savedList, this, R.layout.view_weather_location);
lvLocations.setAdapter(mWeatherLocationAdapter);
This is an example of a regular ListView setting an Adapter to a custom BaseAdapter.
The BaseAdapter is so simple, that really the only method you care about (majorly) is the getView() method.
R.layout.view_weather_location is just a `LinearLayout` I made, it has 3 TextViews in it that I tie (show) my data with, by attaching data to those TextViews in the `getView()` method of the `BaseAdapter`. You would put a `Button there and tie it to what you want (to delete the data item)`.
public class WeatherLocationAdapter extends BaseAdapter{
private List <WeatherLocation> mLocations;
private Context mContext;
private int rowForLocationToInflate;
private LayoutInflater inflater;
public WeatherLocationAdapter(List<WeatherLocation> mLocations, Context mContext, int rowForLocationToInflate) {
this.mLocations = mLocations;
this.mContext = mContext;
this.rowForLocationToInflate = rowForLocationToInflate;
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//TODO just built up layout now must tie to it.
private void addLocation(WeatherLocation newLocation){
mLocations.add(newLocation);
//TODO maybe invalidate after adding new item.
}
#Override
public int getCount() {
return mLocations.size();
}
#Override
public WeatherLocation getItem(int position) {
return mLocations.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//TODO build a viewholder
View rowView = inflater.inflate(rowForLocationToInflate, parent, false);
TextView tvZipcode = (TextView) rowView.findViewById(R.id.tvZipCode);
TextView tvCity = (TextView) rowView.findViewById(R.id.tvCity);
TextView tvTemp = (TextView) rowView.findViewById(R.id.tvDegree);
tvZipcode.setText(mLocations.get(position).getZipcode());
tvCity.setText(mLocations.get(position).getCity());
tvTemp.setText(String.valueOf(mLocations.get(position).getTemperature()));
// If you had a Button in your LinearLayout you were attaching to you that you wanted to delete that view/item with, it would look something like this in my case.
Button bDel = (Button) row.findViewById(R.id.bDel);
bDel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mLocations.remove(position);
}
});
return rowView;
}
}
In the onClick you would also remove the item from the SQL db. I can show that too, but I feel you have some coding to do as it stands.
I'm doing and app who calls the same method two times and the second time I call the method it doesn't execute the line with HttResponse.
Here is the AsyncTask where everything starts:
private class FetchSubjectsTask extends AsyncTask<String, Void, List<Subject>> {
private ProgressDialog pd;
#Override
protected List<Subject> doInBackground(String... params) {
List<Subject> subjects = null;
try {
subjects = api.getMySubjects(params[0]);
} catch (Exception e) {
e.printStackTrace();
}
return subjects;
}
#Override
protected void onPostExecute(List<Subject> result) {
printSubjects(result);
if (pd != null) {
pd.dismiss();
}
}
}
Then I get the subjects through the method getMySubjects which is:
public List<Subject> getMySubjects(String username) {
List<Subject> subjects = new ArrayList<Subject>();
java.lang.reflect.Type arrayListType = new TypeToken<ArrayList<Subject>>() {
}.getType();
String url = BASE_URL_VM + "users/" + username + "/subjects";
HttpClient httpClient = WebServiceUtils.getHttpClient();
try {
System.out.println("inside try");
HttpResponse response = httpClient.execute(new HttpGet(url));
System.out.println("response executed");
HttpEntity entity = response.getEntity();
Reader reader = new InputStreamReader(entity.getContent());
subjects = gson.fromJson(reader, arrayListType);
} catch (Exception e) {
}
System.out.println("Array lenght " +subjects.size());
return subjects;
}
That's the first time HttpResponse executes and I get the "response executed" and "Array lenght 2" which are the number of subjects that user (username) has in the database.
The problem is when in onPostExecute I call the method printSubjects which is:
private void printSubjects(List<Subject> subjects){
adapter = new SubjectAdapter(this,(ArrayList<Subject>)subjects, (String) getIntent().getExtras().get("username"));
setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
This calls the SubjectAdapter which prints the Subjects in a ListView:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.subject_detail, null);
viewHolder = new ViewHolder();
viewHolder.tvsubject = (TextView) convertView
.findViewById(R.id.tvsubject);
boolean match = api.checkMySubjects(username, data.get(position).getId());
Button addButton = (Button) convertView.findViewById(R.id.bAdd);
if(match){
addButton.setText("Delete");
}else{
addButton.setText("Add");
}
String content = data.get(position).getName();
viewHolder.tvsubject.setText(content);
}
return convertView;
}
private static class ViewHolder {
TextView tvsubject;
TextView tvauthor;
}
There I call the method checkMySubjects which calls again getMySubjects to compare.
public boolean checkMySubjects(String username, String id) {
List<Subject> mySubjects = getMySubjects(username);
boolean match = false;
for (Subject s1 : mySubjects) {
if (s1.getId().equals(id)) {
match = true;
}
}
return match;
}
But now the method getMySubjects doesn't arrive until "Response executed" and the Array lenght is 0. It only shows "Inside try".
Why? I'm calling the same method with the same URL but first time I get the 2 subjects in the array and the second time I get nothing because HttResponse doesn't execute.
Thank you!
It's hard to say what's happening, but I'd like to point out what I think it's wrong. First, let's state the fact thatgetMySubjects performs a network operation, now, the first time you call it, it is called from within an AsyncTask on a thread other than the UI thread. This is perfectly fine
Then you call printSubjects in onPostExecute which populates a ListView with the results...
private void printSubjects(List<Subject> subjects){
adapter = new SubjectAdapter(this,(ArrayList<Subject>)subjects, (String) getIntent().getExtras().get("username"));
setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
Now, the problem is in your getView implementation of the adapter. More specifically here...
boolean match = api.checkMySubjects(username, data.get(position).getId());
this is terribly bad because you are making a network connection on the UI thread everytime you inflate a ListView item, so if you had ten items you will be making a network connection ten times (plus everytime you you scroll up and/or down the list).
Moreover, Android complains with a FATAL exception if you attempt to make a network connection on the UI thread. You're not even noticing because you are not doing anything with this exception...
try {
System.out.println("inside try");
HttpResponse response = httpClient.execute(new HttpGet(url));
System.out.println("response executed");
HttpEntity entity = response.getEntity();
Reader reader = new InputStreamReader(entity.getContent());
subjects = gson.fromJson(reader, arrayListType);
} catch (Exception e) {
}
the catch block is empty, if you print it to the LogCat you'll see the details
Suggestion
Don't make a network connection on the UI thread...you can't
On getView instead of making a network connection for every single iteration, eagerly load the data in memory before you set the ListView
Again, the offending line of code is...
boolean match = api.checkMySubjects(username, data.get(position).getId());
in getView
i Am creating an app where one of my activities will be making use of fragments. In each fragment view, I am going to be pulling from a data base using three files, three adapters in each view. The first fragment works as expected. However, when I add my json parser code to the second swipe view, I see it tries to fire as soon as the activity is loaded ( i make the second swipe view toast) and The json parser will not load any data into my second view. Should I attach the JSON to the main activity and switch the adapters and URL's as i switch views or should i try to load the JSON from every fragment (which is what I am doing now). Any insight would be greatly appreciated thank you
public class chatfragment extends Fragment {
ListView l;
List<chatitem> listItem;
ChatListAdapter adapter;
String category = "430";
chatitem item;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.chatfragment, container, false);
l = (ListView) rootView.findViewById(R.id.chatlist);
listItem = new ArrayList<chatitem>();
adapter = new ChatListAdapter(getActivity(),R.layout.chatfragment, listItem);
l.setAdapter(adapter);
new ReadWeatherJSONFeedTask().execute("myurl");
return rootView;
}
public String readJSONFeed (String URL){
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try{
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if(statusCode == 200){
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) !=null){
stringBuilder.append(line);
}
inputStream.close();
}else{
Log.d("readJSONFeed", "Failed to download file");
}
}catch (Exception e){
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
private class ReadWeatherJSONFeedTask extends AsyncTask<String, Void, String>{
protected String doInBackground(String...urls){
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result){
try{
JSONObject jsonObject = new JSONObject(result);
JSONArray subcat = new
JSONArray(jsonObject.getString("results"));
for(int i = 0; i < subcat.length(); i++){
JSONObject p = subcat.getJSONObject(i);
item = new chatitem(p.getString("hubusername"),p.getString("picture"),p.getString("timeadjust"),p.getString("comment"));
listItem.add(item);
// Toast.makeText(getApplicationContext(), p.getString("subcategory"), Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
}
}catch (Exception e){
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
// Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show();
};
}
}
Well you can do a lot of things. I'd recommend preparing the data (download from Web etc.) in the activity and then loading it into the fragments.
ViewPager prepares not only the current fragment but also the next fragment in the list. If you have an issue with this behaviour you'll have to use the pageChangeListener and updating the fragments when they are active.
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();
I'm having a JSON file which is populated to a listview.First, I'm wondering how to make my list view is clickable and lead to another activity.
The second, I wanna make the list view dynamic. That means, I only need one Activity for the click action on the list I have. And the source of the content (picture,title,description) which is populated to the Activity comes from a JSON file on the web.
For example, I have 13 projects on the list, whenever I click to one of them it goes to ONE activity containing different picture,title,and description depends on the item I click.
I need somebody to improve the codes I provide below.
Projects.java
public class Projects {
public String title;
public String keyword;
public String description;
public String smallImageUrl;
public String bigImageUrl;
public int cost;
#Override
public String toString()
{
return "Title: "+title+ " Keyword: "+keyword+ " Image: "+smallImageUrl;
}
}
ProjectsAdapter.java
Public class ProjectsAdapter extends ArrayAdapter<Projects> {
int resource;
String response;
Context context;
//Initialize adapter
public ProjectsAdapter(Context context, int resource, List<Projects> items) {
super(context, resource, items);
this.resource=resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LinearLayout projectView;
//Get the current alert object
Projects pro = getItem(position);
//Inflate the view
if(convertView==null)
{
projectView = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi;
vi = (LayoutInflater)getContext().getSystemService(inflater);
vi.inflate(resource, projectView, true);
}
else
{
projectView = (LinearLayout) convertView;
}
TextView Title =(TextView)projectView.findViewById(R.id.title);
try {
ImageView i = (ImageView)projectView.findViewById(R.id.image);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(pro.smallImageUrl).getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Assign the appropriate data from our alert object above
//Image.setImageDrawable(pro.smallImageUrl);
Title.setText(pro.title);
return projectView;
}
}
Main.java
public class Main extends Activity {
/** Called when the activity is first created. */
//ListView that will hold our items references back to main.xml
ListView lstTest;
//Array Adapter that will hold our ArrayList and display the items on the ListView
ProjectsAdapter arrayAdapter;
//List that will host our items and allow us to modify that array adapter
ArrayList<Projects> prjcts=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Initialize ListView
lstTest= (ListView)findViewById(R.id.lstText);
//Initialize our ArrayList
prjcts = new ArrayList<Projects>();
//Initialize our array adapter notice how it references the listitems.xml layout
arrayAdapter = new ProjectsAdapter(Main.this, R.layout.listitems,prjcts);
//Set the above adapter as the adapter of choice for our list
lstTest.setAdapter(arrayAdapter);
//Instantiate the Web Service Class with he URL of the web service not that you must pass
WebService webService = new WebService("http://pre.spendino.de/test/android/projects.json");
//Pass the parameters if needed , if not then pass dummy one as follows
Map<String, String> params = new HashMap<String, String>();
params.put("var", "");
//Get JSON response from server the "" are where the method name would normally go if needed example
// webService.webGet("getMoreAllerts", params);
String response = webService.webGet("", params);
try
{
//Parse Response into our object
Type collectionType = new TypeToken<ArrayList<Projects>>(){}.getType();
//JSON expects an list so can't use our ArrayList from the lstart
List<Projects> lst= new Gson().fromJson(response, collectionType);
//Now that we have that list lets add it to the ArrayList which will hold our items.
for(Projects l : lst)
{
prjcts.add(l);
}
//Since we've modified the arrayList we now need to notify the adapter that
//its data has changed so that it updates the UI
arrayAdapter.notifyDataSetChanged();
}
catch(Exception e)
{
Log.d("Error: ", e.getMessage());
}
}
}
WebService.java (I don't think we need to edit this one)
public class WebService{
DefaultHttpClient httpClient;
HttpContext localContext;
private String ret;
HttpResponse response1 = null;
HttpPost httpPost = null;
HttpGet httpGet = null;
String webServiceUrl;
//The serviceName should be the name of the Service you are going to be using.
public WebService(String serviceName){
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
httpClient = new DefaultHttpClient(myParams);
localContext = new BasicHttpContext();
webServiceUrl = serviceName;
}
//Use this method to do a HttpPost\WebInvoke on a Web Service
public String webInvoke(String methodName, Map<String, Object> params) {
JSONObject jsonObject = new JSONObject();
for (Map.Entry<String, Object> param : params.entrySet()){
try {
jsonObject.put(param.getKey(), param.getValue());
}
catch (JSONException e) {
Log.e("Groshie", "JSONException : "+e);
}
}
return webInvoke(methodName, jsonObject.toString(), "application/json");
}
private String webInvoke(String methodName, String data, String contentType) {
ret = null;
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpPost = new HttpPost(webServiceUrl + methodName);
response1 = null;
StringEntity tmp = null;
//httpPost.setHeader("User-Agent", "SET YOUR USER AGENT STRING HERE");
httpPost.setHeader("Accept",
"text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
if (contentType != null) {
httpPost.setHeader("Content-Type", contentType);
} else {
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
}
try {
tmp = new StringEntity(data,"UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e("Groshie", "HttpUtils : UnsupportedEncodingException : "+e);
}
httpPost.setEntity(tmp);
Log.d("Groshie", webServiceUrl + "?" + data);
try {
response1 = httpClient.execute(httpPost,localContext);
if (response1 != null) {
ret = EntityUtils.toString(response1.getEntity());
}
} catch (Exception e) {
Log.e("Groshie", "HttpUtils: " + e);
}
return ret;
}
//Use this method to do a HttpGet/WebGet on the web service
public String webGet(String methodName, Map<String, String> params) {
String getUrl = webServiceUrl + methodName;
int i = 0;
for (Map.Entry<String, String> param : params.entrySet())
{
if(i == 0){
getUrl += "?";
}
else{
getUrl += "&";
}
try {
getUrl += param.getKey() + "=" + URLEncoder.encode(param.getValue(),"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i++;
}
httpGet = new HttpGet(getUrl);
Log.e("WebGetURL: ",getUrl);
try {
response1 = httpClient.execute(httpGet);
} catch (Exception e) {
Log.e("Groshie:", e.getMessage());
}
// we assume that the response body contains the error message
try {
ret = EntityUtils.toString(response1.getEntity());
} catch (IOException e) {
Log.e("Groshie:", e.getMessage());
}
return ret;
}
public static JSONObject Object(Object o){
try {
return new JSONObject(new Gson().toJson(o));
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public InputStream getHttpStream(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception e) {
throw new IOException("Error connecting");
} // end try-catch
return in;
}
public void clearCookies() {
httpClient.getCookieStore().clear();
}
public void abort() {
try {
if (httpClient != null) {
System.out.println("Abort.");
httpPost.abort();
}
} catch (Exception e) {
System.out.println("Your App Name Here" + e);
}
}
}
and here's the JSON file:
[{
"title": "CARE Deutschland-Luxemburg e.V.",
"keyword": "CARE",
"description": "<p><b>Das CARE-Komplett-Paket für Menschen in Not</b",
"smallImageUrl": "http://cdn.spendino.de/web/img/projects/home/1284113658.jpg",
"bigImageUrl":"http://cdn.spendino.de/web/img/projects/small/1284113658.jpg",
"cost": "5"
},
{
"title": "Brot für die Welt",
"keyword": "BROT",
"description": "<p>„Brot für die Welt“ unterstützt unter der Maßgabe 'Helfen, wo die Not am größten ist' ausgewählte Projekte weltweit.",
"smallImageUrl": "http://cdn.spendino.de/web/img/projects/home/1267454286.jpg",
"bigImageUrl":"http://cdn.spendino.de/web/img/projects/small/1267454286.jpg",
"cost": "5"
},
{
"title": "Deutsche AIDS-Stiftung",
"keyword": "HIV",
"description": "<p>Die Deutsche AIDS-Stiftung unterstützt mit ihren finanziellen Mitteln seit mehr als 20 Jahren Betroffene, die an HIV und AIDS erkrankt sind.",
"smallImageUrl": "http://cdn.spendino.de/web/img/projects/home/1258365722.jpg",
"bigImageUrl":"http://cdn.spendino.de/web/img/projects/small/1258365722.jpg",
"cost": "5"
}]
Screenshot of the list view:
If something is not clear, please let me know.
Thank you very much
Use this to implement the click:
lstTest.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
Projects p = (Projects ) lstTest.getItemAtPosition(position);
//Do your logic and open up a new Activity.
}
});
First of all, JSON isn't gonna do this for you. you'll have to implement your logic.
Consider JSON just as a huge data dump.
Here's how you should go about it:
Have the JSON
construct a suitable data structure (an Array, ArrayList, whatever you like) to hold crucial data about your list view
Use this data structure as the source for your list view
when the user clicks on any row, try to find out the position of the row in the list view, and on that position in your source data structure, look for the data needed.
create any activity which handles these data generally
open that activity with the data of the row which user clicked in step 4
Consume this data in your new activity
This way, you can add dynamics to your activity that displays the data according to the row clicked