Implementation of Async Task - android

I am trying to implement Async Task in this class but the thing is that I am calling getInputStream function in my program which is returning a value and I am not sure Where to put it. Where should I define getInputStream in my async task?
I am getting the below exception
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity com.sparkplug.xxxx}: java.lang.NullPointerException
Below is my main class:
public class abcreaderextends ListActivity {
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
parsing p=new parsing();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_awsreader);
((PullToRefreshListView) getListView())
.setOnRefreshListener(new OnRefreshListener() {
public void onRefresh() {
// Do work to refresh the list here.
new GetDataTask().execute();
}
});
InputStreamOperation in= new InputStreamOperation();
in.execute();
//p.parse();
for (int i = 0; i < p.headlines.size(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("title", p.headlines.get(i));
map.put("dcdate", p.lstDate.get(i));
map.put("description", p.description.get(i));
// adding HashList to ArrayList
menuItems.add(map);
}
ListAdapter rssFeedSection = new SimpleAdapter(this, menuItems,
R.layout.list_item, new String[] { "title", "dcdate",
"description" }, new int[] { R.id.name, R.id.date1,
R.id.desc });
setListAdapter(rssFeedSection);
}
class GetDataTask extends AsyncTask<Void, Void, String[]> {
#Override
protected void onPostExecute(String[] result) {
// **menuItems.addFirst("Added after refresh...");
// Call onRefreshComplete when the list has been refreshed.
((PullToRefreshListView) getListView()).onRefreshComplete();
super.onPostExecute(result);
}
#Override
protected String[] doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Uri uri = Uri.parse((String) p.links.get(position));
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
This is my parsing class:
public class parsing {
List headlines;
List links;
List description;
List lstDate;
List newDate;
//String a,b,c,d;
public InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
public HashMap<String, ArrayList<String>> parse() {
// Initializing instance variables
headlines = new ArrayList<String>();
links = new ArrayList<String>();
description = new ArrayList<String>();
lstDate = new ArrayList<String>();
try {
URL url = new URL(
"http://feeds.feedburner.com/xxxx");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
// We will get the XML from an input stream
xpp.setInput(getInputStream(url), "UTF_8");
int i = 0;
boolean insideItem = false;
// Returns the type of current event: START_TAG, END_TAG, etc..
int eventType = xpp.getEventType();
int k = 0;
while (eventType != XmlPullParser.END_DOCUMENT) {
i++;
// Log.i("Tag : ",xpp.getName().toString());
// Log.i("Text : ",xpp.nextText().toString());
if (eventType == XmlPullParser.START_TAG) {
Log.i("Tag : ", xpp.getName().toString());
// Log.i("Text : ",xpp.nextText().toString());
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem) {
String var = xpp.nextText().toString();
headlines.add(var); // extract the description of
// article
Log.i("Title : ", var);
// Log.i("Count : ",i+"");
}
} else if (xpp.getName().equalsIgnoreCase("description")) {
if (insideItem) {
String desc = xpp.nextText().toString();
description.add(desc); // extract the description of
// article
Log.i("Desc : ", desc);
}
} else if (xpp.getName().equalsIgnoreCase("dc:date")) {
if (insideItem) {
String strDate = xpp.nextText().toString();
System.out.println("rahul"+strDate.substring(0,10));
//lstDate = Arrays.asList(arr[k].substring(0,10));
lstDate.add(strDate.substring(0,10));
System.out.println("lstDate"+lstDate);
k = k+1;
Log.i("Date : ", strDate);
}
} else if (xpp.getName().equalsIgnoreCase("link")) {
if (insideItem)
links.add(xpp.nextText()); // extract the link of
// article
}
} else if (eventType == XmlPullParser.END_TAG
&& xpp.getName().equalsIgnoreCase("item")) {
insideItem = false;
}
eventType = xpp.next(); // move to next element
}// While end
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
HashMap<String, ArrayList<String>> alllists =
new HashMap<String, ArrayList<String>>();
alllists.put("headlines",(ArrayList<String>) headlines);
alllists.put("links",(ArrayList<String>) links);
alllists.put("description",(ArrayList<String>) description);
alllists.put("lstDate",(ArrayList<String>) lstDate);
return alllists;
}
}
and this one is my InputStreamOperation class:
public class InputStreamOperation extends AsyncTask>> {
#Override
protected void onPreExecute() {
// show progress bar here(have not used any progress bar)
}
#Override
protected HashMap<String, ArrayList<String>>
doInBackground(Void... params) {
//call parse() method here
parsing parsingobj=new parsing();
HashMap<String, ArrayList<String>> alllists=parsingobj.parse();
return alllists; //<<< retun final result from here
}
#Override
protected void onPostExecute(HashMap<String, ArrayList<String>> result) {
// update UI here
}
}

Try like this..
class Search AsyncTask<String, Void, ArrayList<Movie>>() {
#Override
protected void onPreExecute() {
progressDialog= ProgressDialog.show(context, "Please Wait","Searching movies", true);
}
#Override
protected ArrayList<Movie> doInBackground(String... params) {
String moviesJson = retrieveStream[params[0]];
JSONObject moviesJson = new JSONObject(moviesJson);
ArrayList<Movie> movies = new ArrayList<Movie>();
/*
* Do your code to process the JSON and create an ArrayList of films.
* It's just a suggestion how to store the data.
*/
return movies;
}
protected void onPostExecute(ArrayList<Movie> result) {
progressDialog.dismiss();
//create a method to set an ArrayList in your adapter and set it here.
sampleActivity.mListAdapter.setMovies(result);
sampleActivity.mListAdapter.notifyDataSetChanged();
}
}
For more information..
Android issues with AsyncTask and InputStream

you will need to call getInputStream inside doInBackground method of AsyncTask as:
First Change parse method return type to HashMap<String, String> as :
public HashMap<String, ArrayList<String>> parse() {
///your code here...
HashMap<String, ArrayList<String>> alllists =
new HashMap<String, ArrayList<String>>();
alllists.put("headlines",headlines);
alllists.put("links",links);
alllists.put("description",description);
alllists.put("lstDate",lstDate);
return alllists;
}
and Create AsyncTask class as :
private class InputStreamOperation extends
AsyncTask<String, Void, HashMap<String, ArrayList<String>>> {
#Override
protected void onPreExecute() {
// show progress bar here
}
#Override
protected HashMap<String, ArrayList<String>>
doInBackground(String... params) {
//call parse() method here
parsing parsingobj=new parsing();
HashMap<String, ArrayList<String>> alllists=parsingobj.parse();
return alllists; //<<< retun final result from here
}
#Override
protected void onPostExecute(HashMap<String, ArrayList<String>> result) {
// update UI here
}
}

It should be written in the doInBackground() method.
Due to formatting problems i am not able to upload the exact code
1 create a class extending asyncTask with
2 Write getInputStream in doInBackground
3 Call the asynctask to get InputStream

Related

Android: ListView from MySQL only display the last element

I'm trying to retrieve data from MySql database and put it on a ListView, everything works fine, I even put that data into textviews(dynamically) and it works fine. But when I used a ListView, only the last element was displayed, I think that means every new element is overwritten the old one, right?
What can I do to solve this? here's my code tell what's wrong??
public class MakeAppointementActivity extends AppCompatActivity {
public List<AvailabilityList> customList;
public ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_appointement);
lv=(ListView)findViewById(R.id.listView);
Intent intent=getIntent();
new RetrieveTask().execute();
}
private class RetrieveTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String strUrl = "availableAppointments1.php";
URL url;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line;
while( (line = reader.readLine()) != null){
sb.append(line);
}
reader.close();
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new ParserTask().execute(result);
}
}
// Background thread to parse the JSON data retrieved from MySQL server
private class ParserTask extends AsyncTask<String, Void, List<HashMap<String, String>>> {
#Override
protected List<HashMap<String, String>> doInBackground(String... params) {
AppointementJSONParser appointementParser = new AppointementJSONParser();
JSONObject json = null;
try {
json = new JSONObject(params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
return appointementParser.parse(json);
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
customList=new ArrayList<>(); / move it to here
for (int i = 0; i < result.size(); i++) {
HashMap<String, String> appointement = result.get(i);
String fromT = appointement.get("fromT");
String toT = appointement.get("toT");
String date = appointement.get("date");
addAvailableAppoint(fromT,toT,date);
}
updateListView(); // update listview when you add all data to arraylist
}
}
private void addAvailableAppoint(final String fromT, final String toT, final String date) {
customList.add(new AvailabilityList(fromT));
}
// split new function for update listview
private updateListView(){
ArrayAdapter adapter=new DoctorAvailabilityAdapter(MakeAppointementActivity.this,R.layout.list_items,customList);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MakeAppointementActivity.this, AppointementActivity.class);
intent.putExtra("fromT", fromT);
intent.putExtra("toT", toT);
intent.putExtra("date", date);
startActivity(intent);
}
});
}
}
Try this code
.....// your above code
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
customList=new ArrayList<>(); / move it to here
for (int i = 0; i < result.size(); i++) {
HashMap<String, String> appointement = result.get(i);
String fromT = appointement.get("fromT");
String toT = appointement.get("toT");
String date = appointement.get("date");
addAvailableAppoint(fromT,toT,date);
}
updateListView(); // update listview when you add all data to arraylist
}
}
private void addAvailableAppoint(final String fromT, final String toT, final String date) {
customList.add(new AvailabilityList(fromT));
}
// split new function for update listview
private updateListView(){
ArrayAdapter adapter=new DoctorAvailabilityAdapter(MakeAppointementActivity.this,R.layout.list_items,customList);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MakeAppointementActivity.this, AppointementActivity.class);
// intent.putExtra("fromT", fromT); // change it to
intent.putExtra("fromT", customList.get(position).getFromT());
intent.putExtra("toT", toT);
intent.putExtra("date", date);
startActivity(intent);
}
});
}
}
Hope this help
You create new ArrayList for every item customList=new ArrayList<>();
Create list only once in OnCreate for example.
Also you create new Adapter every time you add an item, adapter should also be created only once in OnCreate then you should update data with adapter.NotifyDataSetChanged()

Empty listView in listFragment

I have a list fragment. When I run the app, I see an empty listView.
I don't know what the problem is. Maybe I should use a library?
public class MyEmployeFragment extends ListFragment {
private static final String ATTRIBUTE_ID = "p_id";
private static final String ATTRIBUTE_NAME = "p_name";
private static final String ATTRIBUTE_LAST_NAME = "p_last_name";
ArrayList<spr_item> ret_data;
MyTask task;
SimpleAdapter sAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
task = new MyTask();
task.execute();
return inflater.inflate(R.layout.my_employe, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ret_data = new ArrayList<spr_item>();
ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>(
ret_data.size());
Map<String, Object> m;
for (int i = 0; i < ret_data.size(); i++) {
m = new HashMap<String, Object>();
m.put(ATTRIBUTE_ID, ret_data.get(i).getId());
m.put(ATTRIBUTE_NAME, ret_data.get(i).getName());
m.put(ATTRIBUTE_LAST_NAME, ret_data.get(i).getLastName());
data.add(m);
}
// массив имен атрибутов, из которых будут читаться данные
String[] from = {ATTRIBUTE_ID, ATTRIBUTE_NAME, ATTRIBUTE_LAST_NAME};
// массив ID View-компонентов, в которые будут вставлять данные
int[] to = {R.id.tw_employe_id, R.id.tw_employe_name, R.id.tw_employe_last_name};
// создаем адаптер
sAdapter = new SimpleAdapter(getActivity(), data, R.layout.list_item_employee,
from, to);
// определяем список и присваиваем ему адаптер
ListView lvSimple = (ListView) getView().findViewById(android.R.id.list);
lvSimple.setAdapter(sAdapter);
}
class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
String s = "5ACACEC6-752B-4EFF-AA50-EEBE58A52113";
// String user_guid = myPrefs.getString("guid", "");
HttpActivity _http = new HttpActivity("192.168.10.11", "80");
_http.set_addr_protocol("/WebSite/P/spr/spr.aspx/");
_http.add_param("query", "spr_employee_get");
// _http.add_param("p_guid", user_guid.toString().trim());
_http.add_param("p_guid", s);
_http.send();
List<spr_item> tempList = _http.getArrayParamValue();
for(int i = 0; i < tempList.size(); i++)
ret_data.add(tempList.get(i));
//employer_name = _http.getArrayParamValue("p_name");
//employer_id = _http.getArrayParamValue("p_id");
//employer_last_name = _http.getArrayParamValue("p_last_name");
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
sAdapter.notifyDataSetChanged();
}
}
}
With the above code apart from the Empty list you may have the null pointer exception too if the task is too quick to load. Here onCreate is called first onCreateView next and onActvityCreated next. So it is better to initialise adapter in onCreate set the adapter to listView in onCreateView and set listView listeners in onActvityCreated using getListView() method.
Apart from this if you are using local database to retrieve data you need to use cursorADapter to fetch the data
The adapter's data references (ArrayList, array, etc.), tend to get lost pretty easily. In that case the notfiyDataSetChanged() method will not work. If you are adamant on using this method I suggest you check the references to the adapter's source again. If that is not the case this is the approach I've used in my project. A small warning in advance, the formatting and the closing of brackets is poorly executed, but the approach is still clear enough.
public class MyFragment extends ListFragment {
// For populating the list view.
SomeAdapter adapter;
public MyFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] parameters = {"url for request"};
new GetRequestTask().execute(parameters);
}
// The async task to make the HTTP GET requests.
class GetRequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
Log.e("GetRequestTask", "Client protocol exception.");
e.printStackTrace();
} catch (IOException e) {
Log.e("GetRequestTask", "IO exception.");
e.printStackTrace();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Update UI with the new response.
new UpdateUITask().execute(result);
}
}
}
// The async task to update the UI.
class UpdateUITask extends AsyncTask<String, String, ArrayList<Something>>{
#Override
protected ArrayList<Something> doInBackground(String... input) {
ArrayList<Something> someArray = new ArrayList<Something>();
try{
// Do some JSON magic to parse the data.
}
catch(JSONException je){
Log.e("UpdateUITask", "JSON parsing error occured.");
je.printStackTrace();
}
return someArray;
}
#Override
protected void onPostExecute(ArrayList<Something> result) {
super.onPostExecute(result);
Log.i("UpdateUITask", "Updating UI.");
adapter = new SomeAdapter(getActivity(), R.layout.some_list_item, restOfTheParameters);
setListAdapter(adapter);
}
}
}
}

Working with cursor objects in android

SplashActivity.java {Updated}
public class SplashActivity extends Activity {
/** Called when the activity is first created. */
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<HashMap<String, String>> arraylist;
private String Content;
DatabaseAdapter db;
TextView txtSplashTitle,txtSplashDesc;
DatabaseAdapter databaseHelper;
Cursor cursor;
//#InjectView(R.id.txtSplashDesc) TextView txtSplashDesc=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
//ButterKnife.inject(this);//using ButterKnife library for viewInjection
txtSplashDesc=(TextView) findViewById(R.id.txtSplashDesc);
String serverURL = "";
db = new DatabaseAdapter(this);
new LongOperation().execute(serverURL);
freeMemory();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
//Setting fonts for textviews
setCustomFontForTextViews();
}
private void setCustomFontForTextViews() {
Typeface typeFace = Typeface.createFromAsset(getAssets(), "royalacid.ttf");
txtSplashDesc.setTypeface(typeFace);
}
// Class with extends AsyncTask class
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(SplashActivity.this);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
Dialog.setMessage("Downloading source..");
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
try {
// NOTE: Don't call UI Element here.
HttpGet httpget = new HttpGet("http://10.0.2.2:3009/findmybuffet/?storedproc=get_app_tables&flag=sudhakar");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
jsonobject = new JSONObject(Content);
jsonobject = jsonobject.getJSONObject("findmybuffet");
jsonarray = jsonobject.getJSONArray("buffets");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("buf_off_id", jsonobject.getString("buf_off_id"));
map.put("from_time", jsonobject.getString("from_time"));
map.put("to_time", jsonobject.getString("to_time"));
map.put("online_price", jsonobject.getString("online_price"));
map.put("reserved_price", jsonobject.getString("reserved_price"));
map.put("buf_image", jsonobject.getString("buf_image"));
map.put("res_name", jsonobject.getString("res_name"));
map.put("rating", jsonobject.getString("rating"));
map.put("latitude", jsonobject.getString("latitude"));
map.put("longitude", jsonobject.getString("longitude"));
map.put("buf_type_name", jsonobject.getString("buf_type_name"));
map.put("from_date", jsonobject.getString("from_date"));
map.put("to_date", jsonobject.getString("to_date"));
map.put("city_id", jsonobject.getString("city_id"));
map.put("city_name", jsonobject.getString("city_name"));
map.put("meal_type_id", jsonobject.getString("meal_type_id"));
map.put("meal_type_name", jsonobject.getString("meal_type_name"));
map.put("buf_desc", jsonobject.getString("buf_desc"));
map.put("distance", jsonobject.getString("distance"));
Log.d("----$$$----", map.toString());
//Calling database
db.addContact(map);
try {
Cursor cursor = (Cursor) databaseHelper.getAllContacts();
cursor.moveToFirst();
if(cursor.moveToFirst()){
do{
String refDestLatitude=cursor.getString(cursor.getColumnIndex(cursor.getColumnName(7)));
Log.d("---#*#*#*#*#*#----", refDestLatitude+"");
}while(cursor.moveToNext());
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("ThrownException", e.toString());
e.printStackTrace();
}
//cursor.close();
}
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
} catch (IOException|JSONException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
// Close progress dialog
Dialog.dismiss();
Intent intent=new Intent(SplashActivity.this,MainActivitySherlock.class);
startActivity(intent);
}
}
private void freeMemory() {
jsonobject=null;
jsonarray=null;
arraylist=null;
Content=null;
}
}
When i debugged the app i found as below
I am having problem in the line ::
String refDestLatitude=cursor.getString(cursor.getColumnIndex(cursor.getColumnName(7)));
Cursor is able to get the value
cursor.getColumnIndex(cursor.getColumnName(7))
But exception popps up when
cursor.getString(cursor.getColumnIndex(cursor.getColumnName(4)));
is evaluated
Note:: This line was working when i was handling in adapter ..... but its not working here. do i need to cast a reference or something ?
try like this :
if(c.moveToFirst()){
do{
String refDestLatitude=cursor.getString(cursor.getColumnIndex(cursor.getColumnName(7)));
}while(c.moveToNext())
}
cursor.getString(cursor.getColumnIndex(cursor.getColumnName(7)));
You get an error because there is no column 7.
I have to ask why all the drama when you could just get the data from the column?
if (getColumnCount() > 11) { // 4+7 = 11 fail
cursor.getString(7);
}

How to implement a progress bar while loading a listview? - android

I've an activity where the RSS feeds are loaded from a website and get displayed in a list view. The thing is it takes few seconds to load stuffs into listview. And i want to implement a progressbar to notify the user about the loading of data.
Below is the code of displaying the RSS feeds..
public class RSS extends ListActivity {
List<String> headlines;
List<String> links;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rss);
// Initializing instance variables
headlines = new ArrayList<String>();
links = new ArrayList<String>();
try {
URL url = new URL("http://feeds.pcworld.com/pcworld/latestnews");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
// We will get the XML from an input stream
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
// Returns the type of current event: START_TAG, END_TAG, etc..
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem)
headlines.add(xpp.nextText()); //extract the headline
} else if (xpp.getName().equalsIgnoreCase("link")) {
if (insideItem)
links.add(xpp.nextText()); //extract the link of article
}
}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem=false;
}
eventType = xpp.next(); //move to next element
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Binding data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
}
private InputStream getInputStream(URL url) {
// TODO Auto-generated method stub
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
Uri uri = Uri.parse((String) links.get(position));
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
So can someone help me out in implementing a simple progressbar when loading the data? :)
You should use an AsyncTask to perform all of you downloading stuff. Then in the AsyncTask's onProgessUpdate method, refresh the adapter to the listview.
class LoadingTask extends AsyncTask<URL, Integer, Integer> {
ProgressDialog mDialog;
BaseAdapter mAdapter
public LoadingTask(Context context, BaseAdapter adapter) {
mDialog = new ProgressDialog(context);
mAdapter = adapter;
// Do your dialog stuff here
}
#Override
public Integer doInBackground(URL... urls) {
int result = 0; // number of loaded entities
while (needsToDownload) {
// Do your downloading here
updateProgress(result / urls.length);
}
return result;
}
#Override
public void onProgressUpdate(Integer... ints) {
mDialog.setProgress(ints[0]);
mAdapter.notifyDatasetChanged()
}
public void onPostExecute(Integer result) {
mDialog.dismiss()
Toast.makeToast(context, "Loaded " + result + " urls...", 1).show();
}
}
You should use Async Task for this.

Show ProgressDialog Android

I have an EditText which takes a String from the user and a searchButton.
When the searchButton is clicked, it will search through the XML file and display it in the ListView.
I am able to take input from the user, search through the XML file and display the usersearched value in the ListView also.
What I want is to display a ProgressDialog after the searchButton is clicked like "PLEASE WAIT...RETRIEVING DATA..." or something like that and dismiss it when the data is shown.
public class Tab1Activity extends ListActivity {
private Button okButton;
private Button searchButton;
Toast toast;
String xml;
private TextView searchText;
private String searchTextString;
HashMap<String, String> o;
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab1);
searchButton = (Button) findViewById(R.id.search_button);
searchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.print("hello");
searchText = (TextView) findViewById(R.id.search_text);
searchTextString = searchText.getText().toString();
readXml(searchTextString);
}
});
}
private void readXml(String searchTextString1) {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String xml = XMLfunctions.getXML();
//Here XMLfunctions is class name which parse xml
Document doc = XMLfunctions.XMLfromString(xml);
int numResults = XMLfunctions.numResults(doc);
if ((numResults <= 0)) {
Toast.makeText(Tab1Activity.this, "Testing xmlparser",
Toast.LENGTH_LONG).show();
finish();
}
NodeList nodes = doc.getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nodes.item(i);
String nameMapString = XMLfunctions.getValue(e, "name");
if ( nameMapString.toLowerCase().indexOf(searchTextString1.toLowerCase()) != -1 ) // != -1 means string is present in the search string
{
map.put("id", XMLfunctions.getValue(e, "id"));
map.put("name", XMLfunctions.getValue(e, "name"));
map.put("Score", XMLfunctions.getValue(e, "score"));
mylist.add(map);
}
}
ListAdapter adapter = new SimpleAdapter(this, mylist,
R.layout.parsexml, new String[] { "name", "Score" }, new int[] {
R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
Toast.makeText(Tab1Activity.this,
"Name "+o.get("name")+" Clicked", Toast.LENGTH_LONG)
.show();
}
});
}
Declare your progress dialog:
ProgressDialog progress;
When you're ready to start the progress dialog:
progress = ProgressDialog.show(this, "dialog title",
"dialog message", true);
and to make it go away when you're done:
progress.dismiss();
Here's a little thread example for you:
// Note: declare ProgressDialog progress as a field in your class.
progress = ProgressDialog.show(this, "dialog title",
"dialog message", true);
new Thread(new Runnable() {
#Override
public void run()
{
// do the thing that takes a long time
runOnUiThread(new Runnable() {
#Override
public void run()
{
progress.dismiss();
}
});
}
}).start();
I am using the following code in one of my current projects where i download data from the internet. It is all inside my activity class.
// ---------------------------- START DownloadFileAsync // -----------------------//
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// DIALOG_DOWNLOAD_PROGRESS is defined as 0 at start of class
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... urls) {
try {
String xmlUrl = urls[0];
URL u = new URL(xmlUrl);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lengthOfFile = c.getContentLength();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; // total = total + len1
publishProgress("" + (int) ((total * 100) / lengthOfFile));
xmlContent += buffer;
}
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Retrieving latest announcements...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
While creating the object for the progressbar check the following.
This fails:
dialog = new ProgressDialog(getApplicationContext());
While adding the activities context works..
dialog = new ProgressDialog(MainActivity.this);
You should not execute resource intensive tasks in the main thread. It will make the UI unresponsive and you will get an ANR. It seems like you will be doing resource intensive stuff and want the user to see the ProgressDialog. You can take a look at http://developer.android.com/reference/android/os/AsyncTask.html to do resource intensive tasks. It also shows you how to use a ProgressDialog.
I am using the following code in one of my current projects where i download data from the internet. It is all inside my activity class.
private class GetData extends AsyncTask<String, Void, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(Calendar.this,
"", "");
}
#Override
protected JSONObject doInBackground(String... params) {
String response;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse responce = httpclient.execute(httppost);
HttpEntity httpEntity = responce.getEntity();
response = EntityUtils.toString(httpEntity);
Log.d("response is", response);
return new JSONObject(response);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
progressDialog.dismiss();
if(result != null)
{
try
{
JSONObject jobj = result.getJSONObject("result");
String status = jobj.getString("status");
if(status.equals("true"))
{
JSONArray array = jobj.getJSONArray("data");
for(int x = 0; x < array.length(); x++)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", array.getJSONObject(x).getString("name"));
map.put("date", array.getJSONObject(x).getString("date"));
map.put("description", array.getJSONObject(x).getString("description"));
list.add(map);
}
CalendarAdapter adapter = new CalendarAdapter(Calendar.this, list);
list_of_calendar.setAdapter(adapter);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(Calendar.this, "Network Problem", Toast.LENGTH_LONG).show();
}
}
}
and execute it in OnCreate Method like new GetData().execute();
where Calendar is my calendarActivity and i have also created a CalendarAdapter to set these values to a list view.

Categories

Resources