how to refresh and load data from a json feed in android? - android

I have a json feed from this URL which contains 20 fields and I parse all the datas..but again I need to load more data from the json feed after showing the 20 fields in listview.
I have created a AsyncTask and loaded the json in listview. this is my class
public void onCreate(Bundle savedInstanceState) {
new DoInBackgrd().execute();
}
private class DoInBackgrd extends AsyncTask<Void, Void, Void> implements
DialogInterface.OnCancelListener {
private ProgressDialog processDialog;
#Override
protected void onPreExecute() {
processDialog = ProgressDialog.show(List.this, "",
getString(R.string.loading), true);
processDialog.setCancelable(true);
}
public void onCancel(DialogInterface arg0) {
// TODO Auto-generated method stub
if (processDialog.isShowing()) {
processDialog.dismiss();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
Jsonfunctions jParser = new Jsonfunctions();
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
results = json.getJSONArray(TAG_RESULTS);
// looping through All Contacts
for (int i = 0; i < results.length(); i++) {
JSONObject c = results.getJSONObject(i);
id = c.getString(TAG_ID);
name = c.getString(TAG_NAME);
adress = c.getString(TAG_ADRRESS);
latitude = c.getString(TAG_LATITUDE);
latitudeAry.add(c.getString(TAG_LATITUDE).toString());
longitude = c.getString(TAG_lONGITUDE);
latitudeAry.add(c.getString(TAG_lONGITUDE).toString());
distance = c.getString(TAG_DISTANCE);
image = c.getString(TAG_IMAGE);
phone = c.getString(TAG_TELEPHONE);
telphonenumberAry
.add(c.getString(TAG_TELEPHONE).toString());
NameAry.add(c.getString(TAG_NAME).toString());
resourceAry.add(new ResourceClass(point, id, name, adress,
distance, latitude, longitude, phone));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
if (processDialog.isShowing()) {
processDialog.dismiss();
}
listView.setAdapter(new ASyncAdapter());
listView.setDividerHeight(2);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long id) {
Intent details = new Intent(List.this, Details.class);
details.putExtra("position", position + 1);
details.putExtra("name", resourceAry.get(position)
.getName());
details.putExtra("adress", resourceAry.get(position)
.getAdress());
details.putExtra("phone", resourceAry.get(position)
.getTelephone());
details.putExtra("latitudes", latitude);
details.putExtra("longitudes", longitude);
startActivity(details);
}
});
}
}
Thanks in advance

I had just finished working on similar kind of requirement(issue faced on is specified in)
Hence I'm hoping to provide you proper solution that is helpful to you and saves ur time.
If I'm not wrong you need to populate same ListView with next 20(i.e. 21 - 40) fields obtained in response for server api.
In that case u need to call server api again and again for that u need an event. Say u add a 'Next' button and on its click u retrive next 20 fields(21 - 40).
Currently in ur code in 'DoInBackgrd', you are binding/setting Adapter(ASyncAdapter) each time you need to bind new records/fields to ListView. This is not a good practice, also it at a instance it will not refresh fields of newly assigned adapter in listView.
Hence you should :
Just retrieve/parse new fileds from JSon and set them in adapter. Adapter will notify your listView about data change and listView will refresh its view.
Considering that 'ASyncAdapter' is your custom adapter that implements ArrayAdapter, just add following(change Variable type from Restaurant to as per your requirement) method to it.
public void reSet(ArrayList<Resturant> resturantsCache) {
//This will clear your current fields/records in adpter
clear();
//This will new fields/records in adpter from provided resturantsCache ArrayList.
for (Resturant resturant : resturantsCache) {
add(resturant);
}
}
Hope you will be able to replace variable types in provided method and use it as per you requirements, In case you need more help please provide ASyncAdapter code.
Thanks.

Related

Android: Refresh ListView every minute

I've been reading all day threads regarding this issue I came up with a strategy but can't make it work
I have a listview fetching json data from a sql server
this listview already has a on swipe refresh function
I need this listview to refresh automatically only when new row was inserted in the data base.
So I wrote a php file fetching number of rows and echoing it witha 3 second refresh (on the php itself) so every time I enter the php file I get the realtime row numbers of my table.
I'm trying to build a function inside my MainActivity:
int OldNumberOfRows = data from the php file
while(true){
int newNumberOfRows = fetch data again using that php
if(both arent equal) execute refresh command.
}
Note: I got no idea how to extract the string from my asynctask to start manipulating my code with it.
That's it in general, Iv'e added the main activity , the "outer class" (FetchNumRowAsync) calling that php the swipe class and the php itself
MainActivity:
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private String TAG = MainActivity.class.getSimpleName();
private String URL = "http://troyka.esy.es/troyka/orders.php";
private SwipeRefreshLayout swipeRefreshLayout;
private ListView listView;
private SwipeListAdapter adapter;
private List<Order> orderList;
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new FetchRowNumAsync(this).execute("http://troyka.esy.es/numberofrows.php");
listView = (ListView) findViewById(R.id.listView);
//RelativeLayout.LayoutParams layout_description = new RelativeLayout.LayoutParams(50,10);
//Rl.setLayoutParams(layout_description);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
orderList = new ArrayList<>();
adapter = new SwipeListAdapter(this, orderList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
/**
* Showing Swipe Refresh animation on activity create
* As animation won't start on onCreate, post runnable is used
*/
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchOrders();
}
}
);
}
/**
* This method is called when swipe refresh is pulled down
*/
#Override
public void onRefresh() {
fetchOrders();
}
/**
* Fetching movies json by making http call
*/
private void fetchOrders() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to order list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject orderObj = response.getJSONObject(i);
int rank = orderObj.getInt("rank");
String title = orderObj.getString("title");
Order m = new Order(rank, title);
orderList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(req);
}
}
FetchRowNumAsync:
public class FetchRowNumAsync extends AsyncTask<String, Void, String> {
private Context mContext;
public FetchRowNumAsync(Context ctx){
this.mContext = ctx;
}
protected String doInBackground(String... urls)
{
String fullString = "";
try{
URL url = new URL(urls[0]);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
fullString += line;
}
reader.close();
}catch(Exception e ){
e.getMessage();
}
return fullString;
}
#Override
protected void onPostExecute(String value){
try{
((OnValueFetchedListener) mContext).onValueFetched(value);
}catch(ClassCastException e){}
}
public interface OnValueFetchedListener{
void onValueFetched(String columns);
}
}
SwipeListAdapter:
public class SwipeListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Order> orderList;
private String[] bgColors;
public SwipeListAdapter(Activity activity, List<Order> orderList) {
this.activity = activity;
this.orderList = orderList;
bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
}
#Override
public int getCount() {
return orderList.size();
}
#Override
public Object getItem(int location) {
return orderList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
TextView serial = (TextView) convertView.findViewById(R.id.serial);
TextView title = (TextView) convertView.findViewById(R.id.title);
serial.setText(String.valueOf(orderList.get(position).id));
title.setText(orderList.get(position).title);
String color = bgColors[position % bgColors.length];
serial.setBackgroundColor(Color.parseColor(color));
return convertView;
}
}
PHP
<?php
header("refresh: 3;");
$mysqli = new mysqli("irrelevant","irrelevant","irrelevant","irrelevant");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT COUNT(*) FROM orders";
$result = mysqli_query($mysqli,$query);
$rows = mysqli_fetch_row($result);
echo ($rows[0]);
$result->close();
$mysqli->close();
?>
Try this approach:
Create an endpoint in your server like the following:
//http://somesite.com/api/data/pull/check
Then, you can easily check this endpoint that returns some value like true or false depending on whether there is new data inserted into the db.
From the result you receive, you can then decide on whether to refresh your data on the phone by making another HTTP request or not. You always want to avoid making unnecessary requests to the server - remember users spend money every time they use their data plan (service).
I, like in the comments above, recommend having a column with a timestamp that you can check so that you only get the newly added data instead of everything!
I hope this gives you a simple idea on how to approach this issue! Good luck!
android app will not know when you have added/updated data in your table on the server until and unless you call script from app and fetch the data and update in your device.
only if your app has implemented these feature's
push notification- call Script every time you receive notification.
XMPP service- used for chat apps(which is not probably answer for
your question right now)
here is my suggestion for you
From server side:
create timestamp field in your table on server. update it with
current timestamp value every time you do changes(i.e update/add) in
the table.and when when that script is called send it across in json
and make your app save it in sqlite along with data.
server will compare for timestamp posted by app everytime with the
saved timestamp in the server for new data.
from client side:
for fist time timestamp from app will be 0. server will check it and
send the whole data along with the timestamp saved during changes in
table. save the data along with time stamp . second time when the
script is called App will be sending the timestamp that was last
saved.
with all this your app will not come to know still if new data is added until you call script and check. but atleast it will come to know if new data is received or not and whether to refresh ur screen
now comes script calling part from client side that is executing of assynch task, do it using handler to execute assynch class every minute
final Handler timerHandler = new Handler();
Runnable timerRunnable;
timerRunnable = new Runnable() {
#Override
public void run() {
new FetchRowNumAsync(context).execute(url);
timerHandler.postDelayed(timerRunnable, 60000); // run every minute
}
};
and unregister it in onDestroy()
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
timerHandler.removeCallbacks(timerRunnable);
}

json search bar in android appthat searches a json file from an api server

i want to have a search bar that searches a number that has been typed in (for example: 115048) and put that in a listview. the json file looks like this http://api.ccapp.it/v1/student/115048/schedule/11
hope someone can help me, the code that i use right now to search a link is like this but it doesnt have a search bar:
public class RoosterviewMd extends ListActivity {
Button mButton;
EditText mEdit;
private ProgressDialog pDialog;
// URL to get contacts JSON
//private static String id = null;
//private static String url = "http://api.ccapp.it/v1/student/" + id + "/schedule/11";
private static String url = "http://api.ccapp.it/v1/student/115048/schedule/12";
// JSON Node names
private static final String TAG_LESSON = "class";
private static final String TAG_ROOM = "room";
private static final String TAG_TEACHER = "teacher";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.roosterviewmd);
//Number input
final EditText input = (EditText) findViewById(R.id.editText2);
//buttons for all the days
Button btn2 = (Button) findViewById(R.id.button29);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Toast.makeText(getBaseContext(), "Je ziet je rooster voor maandag al" , Toast.LENGTH_SHORT ).show();
}
});
Button btnOne = (Button)findViewById(R.id.button30);
btnOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewDi.class);
startActivity(intent);
}
});
Button btnTwo = (Button)findViewById(R.id.button31);
btnTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewWo.class);
startActivity(intent);
}
});
Button btnThree = (Button)findViewById(R.id.button32);
btnThree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewDo.class);
startActivity(intent);
}
});
Button btnFour = (Button)findViewById(R.id.button33);
btnFour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewVr.class);
startActivity(intent);
}
});
//Buttons end here
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String lesson = ((TextView) view.findViewById(R.id.lesson))
.getText().toString();
String teacher = ((TextView) view.findViewById(R.id.teacher))
.getText().toString();
String room = ((TextView) view.findViewById(R.id.room))
.getText().toString();
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(RoosterviewMd.this);
pDialog.setMessage("Give me a second please");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray arr1 = jsonObj.getJSONArray("lessons");
JSONArray arr2 = arr1.getJSONArray(0); //Dag
for (int b = 0; b < arr2.length(); b++) {
JSONObject c = arr2.getJSONObject(b);
String lesson = c.getString(TAG_LESSON);
String teacher = c.getString(TAG_TEACHER);
String room = c.getString(TAG_ROOM);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_LESSON, lesson);
contact.put(TAG_TEACHER, teacher);
contact.put(TAG_ROOM, room);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("CCApp", "Couldn't get any data from the url");
Toast.makeText(getBaseContext(),"We are aware of this error and are working on it, in the mean time eat a cookie", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(RoosterviewMd.this, contactList,
R.layout.list_item, new String[] {TAG_LESSON, TAG_TEACHER,
TAG_ROOM }, new int[] { R.id.lesson,
R.id.teacher, R.id.room });
setListAdapter(adapter);
}
}
}
i hope someone can help me with this
Check out this answer: Get text from web page to string
Basically, you can simply get the text from the page and pass it into a string, and search the string application side for the contents of your edit text.
If you're looking for more functionality with the data from the web site, I would pull the Json into an array of Jsonobjects using something like Gson. You'd then be able to use the data from the web page in a bit more of a structured manner.
Edit: Now to actually answer your question.
You can include an edit text and button in your xml in order to search using a basic search bar kinda thing.
To set a listener on the button, you would do something like:
findViewById(R.id.button).setOnClickListener(new OnClickListener(){
#Override
protected void onClick(View v){
//Here, we can control what the response to the button press is, and grab the text in the edit text field.
String editTextString = findViewById(R.id.edittext).getEditableText().toString();
//Now we have a string used to parse the json or whatever else you need to do.
//May want to add a case here if editTextString is null to prevent runtime errors.
}
}
(Forgive me if there's any minor syntatic errors, just wrote that up quick here in the browser, no API to check on it. :))

Application contacting web service more than necessary

I have an listview that contacts a web service whenever it is called and this is what it looks like
public class ListView extends ListActivity {
ArrayList<HashMap<String, String>> questionList;
final String TAG_DATA_WEB = "data";
private String stringxxx;
ProgressDialog pDialog;
LoadAllData mTask;
JSONArray question = null;
android.widget.ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.listview);
stringxxx = getIntent().getStringExtra("TAG_SEARCH");
questionList = new ArrayList<HashMap<String, String>>();
mTask = new LoadAllData();
mTask.execute();
}
#Override
protected void onListItemClick(android.widget.ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
HashMap<String, String> item = questionList.get(pos);
Intent i = new Intent(ListView.this, SingleListItem.class);
i.putExtra(TAG_DATA_WEB, item.get(TAG_DATA_WEB));
startActivity(i);
}
#Override
public void onBackPressed()
{
/** If user Pressed BackButton While Running Asynctask
this will close the ASynctask.
*/
if (mTask != null && mTask.getStatus() != AsyncTask.Status.FINISHED)
{
mTask.cancel(true);
}
super.onBackPressed();
Intent i = new Intent(ListView.this, PREV.class);
startActivity(i);
finish();
}
#Override
protected void onDestroy() {
if (mTask != null && mTask.getStatus() != AsyncTask.Status.FINISHED)
{
mTask.cancel(true);
}
super.onDestroy();
}
#Override
protected void onPause() {
if (pDialog != null)
{
if(pDialog.isShowing())
{
pDialog.dismiss();
}
super.onPause();
}
}
class LoadAllData extends AsyncTask<String, Void, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListView.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
pDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
public void onCancel(DialogInterface dialog) {
mTask.cancel(true);
Intent i = new Intent(ListView.this, PREV.class);
startActivity(i);
finish();
}
});
JSONObject json = new JSONObject();
try {
String query = URLEncoder.encode(searchTerm, "utf-8");
String URL = "http://example.com";
JSONParsser jParser = new JSONParsser();
json = jParser.readJSONFeed(URL);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
JSONArray questions = json.getJSONObject("all").getJSONArray("questions");
for(int i = 0; i < DT.length(); i++) {
JSONObject question = DT.getJSONObject(i);
String data = question.getString(TAG_DATA_WEB);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_DATA_WEB, data);
questionList.add(map);
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(getBaseContext(), questionList,
R.layout.listelements,
new String[] { TAG_DATA_WEB }, new int[] {
R.id.Subject,});
setListAdapter(adapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The problem I have is that when I click on an item on the listview to go to the next activity, it does as its suppose too with no problem its just when I pressed the back button to go back the listview, the listview activity restarts and it also contacts the web service again to retrieve the information like as if I put finish(); after startArtivity(I); in the onItemClick part of the code. Now normally this wouldn't be a problem if you web service didn't have a search limit but the one i am using does. So basically what Im saying is that when the user clicks on an listview item to go to the next activity and when they press the onBack button, I want the information to still be there instead of the application contacting the web service again to retrieve information and the end result will be the search limit being reached. Can anybody help me with this?
I have used XML parsing so I can probably give you help logically.
You can use bean class with get and set methods and store the results
you get from web service.
Use Set methods to store the values where you have written the
parsing code.
Use get methods in your activity's adapter code to retrieve those
values.
This way web service won't be called again when you reach that
activity using back button.
But remember, if you launch that activity with service again from its parent, web service will be called again.
You would have several options:
Replace the AsyncTask data loading with an AsyncTaskLoader data loading. Check the Loader developer article first. I dropped using AsyncTasks for data loading long time ago...
The scond option is to store the data you receive and don't call the webservice next time. For this, store the data somehow in onSaveInstanceState and in onCreate check if Bundle parameter is not null and if you have data set there for th same key you used in onSaveInstanceState. If true, you already have the data. If false, query.
Depending on data importance and volatility you could save it once in some kind of app persistence (shared preference or sqlite) once you downloaded it and use it every time the activity recreates or creates itself.

Managing the background thread within Android application

I currently have this class below which parses json urls and loads images and texts into a listview with the help of the Lazy Adapter Class and background thread.
Each list item consists of an image view and 2 text views.
I want to create pop up boxes (alert dialog) for each of the generated list items. The alert dialog will have options which will call other applications.
My question :
Would it be wise to code this alert dialog functionality in this class? I'm worried that there is a lot of stuff currently being done in the background and it might affect the app's functionality.
If not could anyone suggest another way to do it. thanks.
Json Activity Class :
public class JsonActivity extends SherlockActivity{
private ProgressDialog progressDialog;
// JSON Node names
static final String TAG_NAME = "name";
static final String TAG_IMAGEURL = "imageurl";
ListView list;
LazyAdapter adapter;
String chartUrl;
String[] urlNames = new String[] {
"urls..."
};
// chartItemList is the array list that holds the chart items
ArrayList<HashMap<String, String>> chartItemList = new ArrayList<HashMap<String,
String>>();
//Holds imageurls
ArrayList<String> imageurls = new ArrayList<String>();
JsonParser Parser = new JsonParser();
// JSONArray
JSONArray chartItems = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chart);
//Get the bundle
Bundle bundle = getIntent().getExtras();
//Extract the data from the bundle
int chartIndex = bundle.getInt("chartIndex");
String chartUrl = urlNames[chartIndex];
setTitle(bundle.getString("chartname"));
//url from where the JSON has to be retrieved
String url = chartUrl;
//Check if the user has a connection
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
if (!info.isConnected()) {
Toast.makeText(this, "Please check your connection and try again.",
Toast.LENGTH_SHORT).show();
}
//if positive, fetch the articles in background
else new getChartItems().execute(chartUrl);
}
//else show toast
else {
Toast.makeText(this, "Please check your connection and try again.",
Toast.LENGTH_SHORT).show();
}
}
class getChartItems extends AsyncTask<String, String, String> {
// Shows a progress dialog while setting up the background task
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(JsonActivity.this);
progressDialog.setMessage("Loading chart...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
//Gets the json data for chart items data and presents it in a list view
#Override
protected String doInBackground(String... args) {
String json = Parser.getJSONFromUrl(args[0]);
String imageurl;
String rank;
String name;
String url;
try{
chartItems = new JSONArray(json);
JSONObject json_data=null;
for(int i=0;i<chartItems.length();i++){
json_data = chartItems.getJSONObject(i);
//Retrieves the value of the name from the json object
name=json_data.getString("name");
//Retrieves the image url for that object and adds it to an arraylist
imageurl=json_data.getString("imageurl");
//imageurls.add(imageurl);
HashMap<String, String> hashMap = new HashMap<String, String>();
// adding each child node to HashMap key => value
//hashMap.put(TAG_RANK, rank);
hashMap.put(TAG_NAME, name);
hashMap.put(TAG_IMAGEURL, imageurl);
// adding HashMap to ArrayList
chartItemList.add(hashMap);
}
;
}
catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter = new LazyAdapter(JsonActivity.this, chartItemList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
});
return null;
}
//Removes the progress dialog when the data has been fetched
protected void onPostExecute(String args) {
progressDialog.dismiss();
}
}
}
My answer for this is Yes, it is wise enough to implement one more level network communication as far as your use case justifies it.
This depends on communication channel (EDGE/ 3G/ 4G/ WiFi) and use case of the application. Technically it is pretty much possible as far as you are doing this in background. It also depends on the size of the list which you are loading. Best way to check this is by implementing plug-able code and try it out.

How to remove an item from ListView

I am building one app having One list view showing the list of My favorites Fans. My list of Fans is this!
When i click on any item of this list then it show me complete profile of the concern Fan e.g., this
My Code is ->
public class FavouriteFansActivity extends ListActivity implements OnItemClickListener, OnLongClickListener {
ListView mFavFansListView;
JSONArray jArrayFavFans;//jArrayFavFans that contains jobjects of all fans. each jobj hv data of 1 unique fan!
JSONObject jFavFan_Data;//contain data of an indivisual fan
LazyAdapter adapter;
ArrayList<Object> favFansList;
ArrayList<String> mfavFansImgs;
ItemBean bean;
String favFans;
//String url="http://XXXXX/ManU/";//Live
String url="http://XXXXX/ManU/";//Local
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.on_favourite_fan_list);
prepareFavFanArrayLits();//method that prepare list of my favorite fans....
mFavFansListView = (ListView) findViewById(android.R.id.list);
adapter = new LazyAdapter(this, mfavFansImgs, favFansList);
mFavFansListView.setAdapter(adapter);
mFavFansListView.setOnItemClickListener(this);
mFavFansListView.setOnLongClickListener(this);
/** I am still not getting that when to call onPause(), onResume(), onRestart()... etc ??? */
}
/* .........onItemClick......... */
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
ItemBean bean = (ItemBean) adapter.getItem(position);
/**from here-> I am going to start one activity that show the complete profile of a
* particular Fan... According to the unique id received from clicking on ListItem!
*/
Intent in= new Intent(getParent(), FavFanProfile.class);
TabGroupActivity prnt = (TabGroupActivity) getParent();
Bundle fBundle= new Bundle();
fBundle.putString("fanId", bean.getUid());
in.putExtras(fBundle);
prnt.startChildActivity("FavFanProfile", in);
}
/* .........onLongClick......... */
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(FavouriteFansActivity.this, "To remove...Clk", Toast.LENGTH_SHORT).show();
return false;
}
/** Method used to prepare the List of Favorite Fans
* #author Rupesh */
public void prepareFavFanArrayLits() {
/* return me array containing data of all favFans */
Boolean mkFavFansList=false;
SharedPreferences favFansData = getSharedPreferences("jArrayFavFansPref", MODE_WORLD_WRITEABLE);
favFans=favFansData.getString("favFansData", "");
Log.i("FavFans_List->", "FavFans_DATA readed from prefs:"+favFans.toString());
if(!favFans.equals("")){
try {
mkFavFansList=true;
jArrayFavFans=new JSONArray(favFans);
favFansList = new ArrayList<Object>();
mfavFansImgs = new ArrayList<String>();
Log.i("fav_fansONfav", jArrayFavFans.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else {
Log.i("else_favList_img", "list & image are initialized");
favFansList = new ArrayList<Object>();
mfavFansImgs = new ArrayList<String>();
}
// ++++++++
if(mkFavFansList){
try {
for (int i = 0; i < jArrayFavFans.length(); i++) {
// will return the data of each row fetched from JSONArray returned by location1.php
String data_of_each_user = jArrayFavFans.get(i).toString();
Log.i("Data Of User at index " + i + " is", data_of_each_user);
// I put the object at index "i" into JSONObject & retrieve data from name-value pair
jFavFan_Data = jArrayFavFans.getJSONObject(i);// data of User at index i
// in array
AddObjectToList(jFavFan_Data.getString("uniqid").toString(), jFavFan_Data.getString("name"),
jFavFan_Data.getString("distance"));
//Log.i("URL", url+"images/"+jFavFan_Data.get("uniqid").toString()+".png");
mfavFansImgs.add(url+"images/"+jFavFan_Data.get("uniqid").toString()+".png");
Log.i("IMG_URL", url+"images/"+jFavFan_Data.get("uniqid").toString()+".png");
String nm = jFavFan_Data.get("name").toString();
String uid = jFavFan_Data.get("uniqid").toString();
String dis = jFavFan_Data.get("distance").toString();
//System.out.println("Your Name: " + nm);
System.out.println("Your Unique Id: " + uid);
//System.out.println("Your Distance: " + dis);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
} else {
Log.i("NO_FAVORITE_FANS", "No Favorite Fans are added in favorites List!");
Toast.makeText(FavouriteFansActivity.this, "No Fans in Favorite List!", Toast.LENGTH_SHORT).show();
}
// ++++++++++
}
//**********************setting vales in bean*************************
public void AddObjectToList(String uid, String title, String desc) {
bean = new ItemBean();
bean.setUid(uid);
bean.setDescription(desc);
bean.setTitle(title);
favFansList.add(bean);
}
//***********************************************
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.i("favFansData_FavoriteFansActivity.java", "hi...on resume"+favFans);
prepareFavFanArrayLits();
setContentView(R.layout.on_favourite_fan_list);
mFavFansListView = (ListView) findViewById(android.R.id.list);
adapter = new LazyAdapter(this, mfavFansImgs, favFansList);
mFavFansListView.setAdapter(adapter);// come null pointer exception when no fan data is returned! hendle it...
mFavFansListView.setOnItemClickListener(this);
}
}
I stuck at the point -> That, how to remove one Item(one Fan) from this list(favorite_fans_list) ...???
I try to do something on onLongClick Listener but it doesn`t work.... I pleased to have any pointer or some sample which help me to overcome from this problem!!!
One way would be to modify the content in the adapter and then notify the listview has changed.
Your adapter holds an ArrayList for the data backing it.
You need to remove the object from the list. Then notify the adapter that the set has changed as follows.
favFansList.remove(index);
adapter.notifyDataSetChanged()

Categories

Resources