Pass an object from Fragment to ASyncTask onPostExecute - java

I am trying to use a simple object class that gets passed around in my application. First, I use it to execute an AsyncTask. In the onPostExecute method of the AsyncTask, I would like to get this same object class to use some of its setters again. How can I pass this data object to both the AsyncTask's doInBackground and the onPostExecute?
Code:
TravelPlanner.java
// Put departure & arrival into model class
data = new ReisData();
data.setDeparture(departureStation);
data.setArrival(arrivalStation);
// Start AsyncTask
GetInfo asyncTask = new GetInfo(this);
asyncTask.execute(data);
GetInfo.java
public class GetInfo extends AsyncTask<ReisData, Integer, String> {
Reisplanner reisPlanner;
View view;
public GetInfo(Reisplanner main) {
this.reisPlanner = main;
view = reisPlanner.getView();
}
#Override
protected void onPreExecute() {
ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected String doInBackground(ReisData... params) {
try {
// Return XML as string with route options
return HttpRequestHelper.downloadFromServer(params);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
DocumentBuilder builder;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = null;
try {
builder = factory.newDocumentBuilder();
doc = builder.parse(new InputSource(new StringReader(result)));
} catch (Exception e) {
e.printStackTrace();
}
// TODO: Get 'ReisData' object
if (doc != null) {
XMLParser.parse(doc);
}
// Start Reisadvies with ReisData class
Fragment fragment = new Reisadvies();
// TODO: Put ReisData class into Bundle
this.reisPlanner.startFragment(fragment);
}

You can pass in Contructor of AsyncTask
TravelPlanner.java
// Put departure & arrival into model class
data = new ReisData();
data.setDeparture(departureStation);
data.setArrival(arrivalStation);
// Start AsyncTask
GetInfo asyncTask = new GetInfo(this,data); // here is
asyncTask.execute(data);
GetInfo.java
public class GetInfo extends AsyncTask<ReisData, Integer, String> {
ReisData data;
Reisplanner reisPlanner;
View view;
public GetInfo(Reisplanner main,ReisData data) {
this.data=data;// you can use this
this.reisPlanner = main;
view = reisPlanner.getView();
}
#Override
protected void onPreExecute() {
ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected String doInBackground(ReisData... params) {
try {
// Return XML as string with route options
return HttpRequestHelper.downloadFromServer(params);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
DocumentBuilder builder;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = null;
try {
builder = factory.newDocumentBuilder();
doc = builder.parse(new InputSource(new StringReader(result)));
} catch (Exception e) {
e.printStackTrace();
}
// TODO: Get 'ReisData' object
if (doc != null) {
XMLParser.parse(doc);
}
// Start Reisadvies with ReisData class
Fragment fragment = new Reisadvies();
// TODO: Put ReisData class into Bundle
this.reisPlanner.startFragment(fragment);
}

Related

I'm having problem while scraping data from this website. My code is below:

I want to fecth the data(Marked in the picture)from this URL using Jsoup that I used in my code below.
But I'm having error while doing this. I don't get any value in my String description.
In the MainActivity I declared and intialized the class's object,
description_webscrape dw = new description_webscrape();
dw.execute();
Here's my code of another class.
public class description_webscrape extends AsyncTask<Void,Void,Void>
{
String url = "https://www.ebay.com/sch/i.html?_from=R40&_nkw=shoes&_sacat=0&rt=nc&LH_Sold=1&LH_Complete=1";
description_webscrape(){};
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
org.jsoup.nodes.Document document = null;
try {
document = Jsoup.connect(url).get();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "doInBackground: errorrr---"+e);
}
org.jsoup.select.Elements elements = document.getElementsByClass("srp-controls__count-
heading");
//description is String type and declared globally
description = elements.text();
return null;
}
#Override
protected void onPostExecute(Void unused) {
textView.setText(description+"");
}
}

ArrayList doesn't display value outside of method where the data storing happens

I have this class where it process XML and store it inside an ArrayList<FeedItem>. I can display the array content in the method where I store the data but when I try to display the array in another method it did not pass the if checking indicating that the ArrayList is empty. Because of this, I can't create a ListView because it'll return the same error. I hope someone can briefly explain to me what is wrong.
ReadRSS.java
public class ReadRSS extends AsyncTask<Void, Void, Void> {
//Initialize progress dialog
Context context;
String address;
ProgressDialog progressDialog;
XmlPullParserFactory xmlPullParserFactory;
volatile boolean parsingComplete = true;
ArrayList<FeedItem> feedItems;
ListView listView;
public ReadRSS(Context context, ListView listView, String retrieveAddress) {
//Create a new progress dialog
this.listView = listView;
this.address = retrieveAddress;
this.context = context;
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Loading....");
}
// Runs in UI before background thread is called
#Override
protected void onPreExecute() {
//Display progress dialog
progressDialog.show();
super.onPreExecute();
}
// This is run in a background thread
#Override
protected Void doInBackground(Void... voids) {
fetchXML();
return null;
}
// This is called from background thread but runs in UI
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
// This runs in UI when background thread finishes
#Override
protected void onPostExecute(Void aVoid) {
//Dismiss progress dialog
super.onPostExecute(aVoid);
progressDialog.dismiss();
/*if(listView != null) {
CustomAdapter customAdapter = new CustomAdapter(context, R.layout.activity_listview, feedItems);
listView.setAdapter(customAdapter);
}*/
if(feedItems != null){
//Gives error
for(int i = 0; i < feedItems.size(); i++) {
Log.d("Title", feedItems.get(i).getTitle());
Log.d("Date", feedItems.get(i).getPubDate());
}
}
}
//New Build
public void parseXMLAndStoreIt(XmlPullParser myParser) {
int event;
String text;
String title = null;
String date = null;
feedItems = new ArrayList<FeedItem>();
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String tagName = myParser.getName();
switch (event){
case XmlPullParser.START_TAG:
if(tagName.equalsIgnoreCase("item")){
int eventChild = myParser.next();
//int innerLoop = 1;
String tagNameChild = "";
while(eventChild != XmlPullParser.END_DOCUMENT){
if(eventChild == XmlPullParser.START_TAG){
tagNameChild = myParser.getName();
// Output Test
//Log.d("Tag ", tagNameChild);
}
else if (eventChild == XmlPullParser.TEXT){
text = myParser.getText();
// Output Test
//Log.d("Test ", text);
if(tagNameChild.equalsIgnoreCase("title")){
title = text;
// Output Test
//Log.d("Title ", myParser.getText());
}
else if(tagNameChild.equalsIgnoreCase("pubDate")){
date = text;
// Output Test
//Log.d("PubDate ", myParser.getText());
}
}
else if (eventChild == XmlPullParser.END_TAG){
if(myParser.getName().equalsIgnoreCase("item")){
feedItems.add(new FeedItem(title,date));
// Output Test
//Log.d("Test ", title);
}
tagNameChild = "";
}
eventChild = myParser.next();
//innerLoop++;
}
//Output Test
/*for(int i = 0; i < feedItems.size(); i++) {
Log.d("Title", feedItems.get(i).getTitle());
Log.d("Date", feedItems.get(i).getPubDate());
}*/
}
break;
case XmlPullParser.TEXT:
break;
case XmlPullParser.END_TAG:
break;
}
event = myParser.next();
}
parsingComplete = false;
}
catch (Exception e) {
e.printStackTrace();
}
}
public void fetchXML(){
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 );
conn.setConnectTimeout(15000 );
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
xmlPullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlPullParserFactory.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
myparser.setInput(stream, null);
parseXMLAndStoreIt(myparser);
stream.close();
}
catch (Exception e) {
}
}
});
thread.start();
}
}
You are calling fetchXML() from doInBackground, but fetchXML() starts a new thread and then immediately returns. Then doInBackground() immediately returns and onPostExecute() is called. However, at that point, the thread launched by fetchXML() has not had time to finish, so feedItems has not been properly set.
That's the wrong way to use an AsyncTask. Instead, you should do the fetching directly in the doInBackground() thread. Just rewrite fetchXML() to do the fetching itself, rather than launch a separate thread to do the fetching.

android update custom view in asynctask

Ok, I have a custom view which plays gifs from the internet. Therefor I need to add an url to my view to download the gif. But I can't seem to update my custom view inside my asynctask. I need to add an url string to my custom view gifView.setUrl(). It works in the onCreate Class but it gives me null in asynctask.
Oncreate class
GifView gifView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
id = extras.getInt("id");
String idStr = String.valueOf(id);
String extension = extras.getString("extension");
if(extension.equals(".gif")){
setContentView(R.layout.activity_post_gif);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
gifView = (GifView)findViewById(R.id.gifview);
titleStr = (TextView)findViewById(R.id.titleTXT);
postInfo = (TextView)findViewById(R.id.infoTXT);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
//the url
new getJsonInfoGif().execute("http://www.website.com/jsonApi");
}else{
Asynctask
public class getJsonInfoGif extends AsyncTask<String, Void, String>{
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("loading post...");
progressDialog.show();
}
#Override
protected String doInBackground(String... strings) {
return GET(strings[0]);
}
#Override
protected void onPostExecute(String res) {
try {
JSONObject jsonObject = new JSONObject("{'postinfo':[" + res + "]}");
JSONArray jsonArray = jsonObject.getJSONArray("postinfo");
JSONObject obj = jsonArray.getJSONObject(0);
//post title
titleStr.setText(obj.getString("name"));
//category and maker full name
//large image
JSONObject imgObj = obj.getJSONObject("thumbnails");
gifView.setUrl("http://www.website.com/my.gif");
} catch (JSONException e) {
e.printStackTrace();
}
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
GifView.java
public void setUrl(String urlStr){
this.urlStr = urlStr;
invalidate();
requestLayout();
}
public String getUrl(){
return this.urlStr;
}
public void init(final Context context)throws IOException{
setFocusable(true);
movie = null;
movieWidth = 0;
movieHeight = 0;
movieDuration = 0;
final Thread thread = new Thread(new Runnable() {
#Override
public void run(){
try{
Log.d("DEBUG", "URL" + urlStr);
URL url = new URL(urlStr);
try {
HttpURLConnection http = (HttpURLConnection) url.openConnection();
inputStream = http.getInputStream();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
movie = Movie.decodeStream(inputStream);
movieWidth = movie.width();
movieHeight = movie.height();
movieDuration = movie.duration();
((PostActivity) context).runOnUiThread(new Runnable() {
#Override
public void run() {
invalidate();
requestLayout();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}catch (Exception e){
e.printStackTrace();
}
}
});
thread.start();
}
Here is the Log from the url, it gives me null if I add the url inside my asynctask in Activity.
11-07 14:41:58.821 5674-6076/svenmobile.tools.showcase D/DEBUGļ¹• URLnull
What I want to know is what the problem is and how to solve it if possible.
Thanks in advance, Sven
Maybe you called init() before setUrl().
You can pass it the url in the contructor, or public void init(final Context context, String urlStr)throws IOException{
I also suggest you to move all that network code to doInBackground

Android Get some data from XML to Layout

After much research, I can't manage to layout some XML data in my android app.
There is my MainActivity.java :
public class MainActivity extends Activity {
TextView textview1;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetXmlTask task = new GetXmlTask(textview1 , "http://www.3pi.tf/test.xml"); // get the XML
Log.i("TAG", "test1");
task.execute(); // execute the task
Log.i("TAG","test2");
textview1 = (TextView) findViewById(R.id.textview1);
Log.i("TAG", "test4");
}
}
And there is my GetXmlTask.java :
public class GetXmlTask extends AsyncTask<Void, Void, String>{
public WeakReference<TextView> textViewReference;
public String url;
public GetXmlTask(TextView textview, String url) {
this.textViewReference = new WeakReference<TextView>(textview);
this.url = url;
}
public String THEXML = null;
public String doInBackground(Void... sUrl) {
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://3pi.tf/test.xml");
Log.i("TAG2",""+request);
HttpResponse response = httpclient.execute(request);
Log.i("TAG2",""+response);
HttpEntity resEntity = response.getEntity();
Log.i("TAG2",""+resEntity);
THEXML = EntityUtils.toString(resEntity);
Log.i("DONNEES XML",""+THEXML);
}
catch(Exception e){ e.printStackTrace(); }
return THEXML;
}
public Document getDomElement(String task) {
Log.i("TAG2","test01");
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try{
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(task));
doc = db.parse(is);
}
catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
}
catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
}
catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
//Retrieve each element child element value by using node name of element.
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
As you can see, I put some logcat in to see how it passes through.
I can see all my XML in the logcat with the variable "THEXML" but I can't layout to my mobile app... I did all the method in an AsyncTask because that was highly recommended..
Please help me
Thank you
Use a interface as a callback to the activity
GetXmlTask task = new GetXmlTask(ActivityName.this, "http://www.3pi.tf/test.xml");
Then in GetXmlTask
ReturnData mCallback;
public GetXmlTask(Context context, String url) { // Constructor in asynctask
this.url = url;
mCallback = (ReturnData)context;
}
Then
public interface ReturnData
{
public void Returnxml(String xml);
}
In doInbackground you return THEXML
return THEXML;
In onPostExecute
#Override
public void onPostExecute(String result)
{
super.onPostExecute(result);
if(mCallback!=null)
{
mCallback.Returnxml(result);
}
}
In MainActivity implement the interface
public class MainActivity extends Activity implements ReturnData {
Then
public void Retunxml(String data)
{
textView1.setText(data);
}
You should overwrite the onPostExecute method of AsynckTask and handle there the operation over your downloaded file if it is different from null. In you case something like this:
protected void onPostExecute(Void result) {
if(THEXML !=null)
{
//do something
}
}

Trouble upgrading my RSS feed reader app, from AsycTask to AsyncTaskLoader behavior

Hello I implemented a simple RSS Feed reader using an AsyncTask, and It works perfectly.
I am trying upgrade my little APP to work with an ASYNCTASKLOADER, to learn how to use Loaders.
Notice the two lines of code on the:
public void onCreate(Bundle savedInstanceState){
of the RSSMain class...
new getRSSFeeds().execute();
getLoaderManager().initLoader(0, null, callBacks1);
By un/commenting these two lines I decide which mode to try my app with.
When I attempt to read RSS Feeds with getLoaderManager, all I get is a blank Activity.
My code is attached. I must have some conceptual mistake on my code, since I am new to all these things. Does somebody now how to solve it?
Take into account I started programming for Android 3 weeks ago, and my code
may be far from perfect, so any comments towards improvement are welcome!
public class RSSMain extends ListActivity {
private ArrayList<rssentry> itemlist2 = null; //LIST OF ALL RSS FEEDS
private RSSListAdaptor2 rssadaptor2 = null; //A SINGLE RSS POST
private String sourceurl=null;
public final static String EXTRA_MESSAGE = "com.example.rssjosh.MESSAGE"; //DECLARE PAYLOAD MESSAGE FOR THE ACTIVITY-CALLING INTENT
private static final int LENGTH_SHORT = 0;
private static final int LENGTH_LONG = 1;
String toastxt="empty...";
Toast toast;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//LoaderManager lmanager = getLoaderManager().initLoader(0, null, new RSSLoaderCallback, getBaseContext());
//getLoaderManager().initLoader(0, savedInstanceState, new RSSLoader(null));
sourceurl="http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest";
itemlist2 = new ArrayList<rssentry>();
getLoaderManager().initLoader(0, null, callBacks1); //CREATES AND INITS. LOADER (ASYNCTASKLOADER MODE)
//new getRSSFeeds().execute();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String s=null;
rssentry data = itemlist2.get(position); //GET THE RSSENTRY THAT WAS TOUCHED BY THE USER
//TEMPORARY TOAST TO CHECK CORRECT STRING FORMATION
//String toastxt="XD!";
//int duration = Toast.LENGTH_LONG; //toastxt=toastxt+data.title+"\n"+data.published+"\n"+data.link+"\n"+data.summary.substring(30,140)+"\n";
//FORM THE HTML TEXT TO BE SENT TO THE SIGLE-RSSFEED DISPLAY ACTIVITY
StringBuilder htmlString = new StringBuilder();
htmlString.append(data.title+"$");
htmlString.append("Published on: "+data.published+"$");
htmlString.append(data.summary+"$");
htmlString.append("URL: "+data.link+"$");
Intent intent = new Intent(this,Rssactivity.class);
//LOADS THE INTENT WITH THE <HTML> PAYLOAD
intent.putExtra(EXTRA_MESSAGE, htmlString.toString()); ///public final static String EXTRA_MESSAGE = "com.example.rssjosh.MESSAGE"; DECLARED ABOVE
startActivity(intent); //LAUNCHES INTENT
}
//SERVICE METHOD TO private String retrieveRSSFeed2(String urlToRssFeed)
// _URLstring -> INPUT_STREAM
private InputStream downloadUrl(String urlString) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// STARTS QUERYING THE STREAM
conn.connect();
InputStream stream = conn.getInputStream();
return stream;
}
//URL -> (INPUT_STREAM) -> List<rssentry> entries
//THIS VARIANT OF THE RETRIEVERSSFEED2 METHOD, RETURNS RESULT IN A STRING FORMAT (OPTIONAL METHOD)
private ArrayList<rssentry> retrieveRSSFeed2Str(String urlToRssFeed) throws XmlPullParserException, IOException
{
ArrayList<rssentry> itemlist = new ArrayList<rssentry>();
//INSTANTIATES A NEW PARSER "parsero", AND AN EMPTY RSSENTRY ARRAYLIST
InputStream stream = null;
//List<rssentry> entries = null; UPGRADED TO PUBLIC CLASS ATTRIBUTE
xmlparser parsero = new xmlparser();
//This Try does URL->Stream
try {
stream = downloadUrl(urlToRssFeed); //OBTAIN A CHARACTER STREAM FROM THE rssURL
itemlist = parsero.parse(stream); //PARSE STREAM AND STORE rssENTRIES IN THE "ENTRIES" ARRAYLIST <rssentry>
} finally {
if (stream != null) {
stream.close(); //CLOSE STREAM AFTER USING IT
}
}
return itemlist;
}
//GETS RSS FEED IN ASYNCHRONOUS MODE
class ATLgetfeeds extends AsyncTaskLoader <ArrayList<rssentry>>{
private ArrayList<rssentry> rsslist=null;
private ProgressDialog progress = null;
public ATLgetfeeds(Context context) {
super(context);
}
#Override
protected void onStartLoading() {
if (rsslist != null)
deliverResult(rsslist); // Use the cache
else
forceLoad();
}
#Override
public ArrayList<rssentry> loadInBackground() {
try {
itemlist2 = null; //<=THIS LIST IS TO BE LOADED WITH THE RSS URL BELOW
rsslist = retrieveRSSFeed2Str("http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest"); //SETS ITEMLIST2
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//LOADS DATA INTO RSSADAPTER (PARSER2)
rssadaptor2 = new RSSListAdaptor2(RSSMain.this, R.layout.rssitemview,rsslist);
return null;
}
#Override
public void deliverResult(ArrayList<rssentry> data) {
rsslist = data; // Caching
super.deliverResult(data);
}
#Override
protected void onReset() {
super.onReset();
// Stop the loader if it is currently running
onStopLoading();
rsslist = null;
}
#Override
public void onCanceled(ArrayList<rssentry> data) {
// Attempt to cancel the current async load
super.onCanceled(data);
rsslist = null;
}
protected void onPreExecute() {
progress = ProgressDialog.show( RSSMain.this, null, "RSSJosh Loading..."); //LOADING MESSAGE
// super.onPreExecute();
}
protected void onPostExecute(Void result) {
itemlist2=rsslist;
setListAdapter(rssadaptor2);
progress.dismiss(); //Dismisses loading progress dialog
//s super.onPostExecute(result);
}
}
//GETS RSS FEED IN ASYNCHRONOUS MODE
private class getRSSFeeds extends AsyncTask<Void, Void, Void>
{
private ProgressDialog progress = null;
ArrayList<rssentry> atlist = new ArrayList<rssentry>();
#Override
protected Void doInBackground(Void... params) {
try {
itemlist2 = null; //<=THIS LIST IS TO BE LOADED WITH THE RSS URL BELOW
atlist = retrieveRSSFeed2Str("http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest");
} catch (XmlPullParserException e) {
e.printStackTrace(); // TODO Auto-generated catch block
} catch (IOException e) {
e.printStackTrace(); // TODO Auto-generated catch block
}
//LOADS DATA INTO UI RSSADAPTER (PARSER2)
rssadaptor2 = new RSSListAdaptor2(RSSMain.this, R.layout.rssitemview,atlist);
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show( RSSMain.this, null, "RSSJosh Loading..."); //LOADING MESSAGE
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
setListAdapter(rssadaptor2);
itemlist2=atlist;
progress.dismiss(); //Dismisses loading progress dialog
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
//RSS ADAPTER (TYPE2) FOR STACK-OVERFLOW RSSFEEDS
private class RSSListAdaptor2 extends ArrayAdapter<rssentry>{
private List<rssentry> objects = null;
public RSSListAdaptor2(Context context, int textviewid, List<rssentry> objects) {
super(context, textviewid, objects);
this.objects = objects;
}
#Override
public int getCount() {
return ((null != objects) ? objects.size() : 0);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public rssentry getItem(int position) {
return ((null != objects) ? objects.get(position) : null);
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(null == view)
{
LayoutInflater vi = (LayoutInflater)RSSMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.rssitemview, null);
}
rssentry data = objects.get(position);
if(null != data)
{ //CREATE TEXTVIEW OBJECTS FORTITLE, DATE AND DESCRIPTION DATA
TextView title = (TextView)view.findViewById(R.id.txtTitle);
TextView date = (TextView)view.findViewById(R.id.txtDate);
TextView description = (TextView)view.findViewById(R.id.txtDescription);
//PUT TEXT ON TITLE AND DATE VIEWS
title.setText(data.title);
date.setText("Published on: " + data.published); //PREVIOUSLY date.setText("on " + data.date);
//PREPARE AND LOAD TEXT FOR THE SUMMARY VIEW
String txt=null;
//Clean and trim summary string before displaying
txt=data.summary.toString().substring(30,data.summary.toString().length());
if (txt.length()>=300)
txt=txt.substring(0,299)+"..."; ///DISPLAY A SUMMARY OF 300 CHARACTERS MAX, IN THE RSS HEADLINES
description.setText(txt); //PUT TEXT
}
return view;
}
}
LoaderManager.LoaderCallbacks<ArrayList<rssentry>> callBacks1 = new LoaderManager.LoaderCallbacks<ArrayList<rssentry>>() {
/* Implement the three callback methods here */
public android.content.Loader<ArrayList<rssentry>> onCreateLoader( //START LOADING
int arg0, Bundle arg1) {
// TODO Auto-generated method stub
android.content.Loader<ArrayList<rssentry>> rsslist=null;
//TEMPORARY TOAST TO DEBUG CORRECT STRING FORMATION
toastxt="Toastiee! Preparing for ATL Task";
toast = Toast.makeText(getBaseContext(), toastxt, LENGTH_SHORT);
toast.show();
ATLgetfeeds a= new ATLgetfeeds(getBaseContext());
//TEMPORARY TOAST TO DEBUG CORRECT STRING FORMATION
toastxt="Toastiee! ATL Task created";
toast = Toast.makeText(getBaseContext(), toastxt, LENGTH_SHORT);
toast.show();
return rsslist;
}
#Override
public void onLoadFinished( //START LOADING
android.content.Loader<ArrayList<rssentry>> arg0,
ArrayList<rssentry> arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoaderReset(android.content.Loader<ArrayList<rssentry>> arg0) {
// TODO Auto-generated method stub
}
};
}

Categories