I want to make a simple Rss Reader app and it doesn't working. More exactly, it doesn't show nothing, almost nothing. For example, for this feed http://feeds.feedburner.com/telefoane-mobilissimo, I get "https://www.mobilissimo.ro/telefoane/" and "Telefoane mobile: specificații, galerii foto, video, benchmark-uri, teste".
Here is the code:
public List<FeedModel> parseFeed(InputStream inputStream) throws XmlPullParserException,
IOException {
String title = null;
String description = null;
String link=null;
String content=null;
String pubDate=null;
Bitmap bitmap=null;
URL url;
boolean isItem = false;
List<FeedModel> items = new ArrayList<>();
try {
XmlPullParser xmlPullParser = Xml.newPullParser();
xmlPullParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
xmlPullParser.setInput(inputStream, null);
xmlPullParser.nextTag();
while (xmlPullParser.next() != XmlPullParser.END_DOCUMENT) {
int eventType = xmlPullParser.getEventType();
String name = xmlPullParser.getName();
if(name == null)
continue;
if(eventType == XmlPullParser.END_TAG) {
if(name.equalsIgnoreCase("item")) {
isItem = false;
}
continue;
}
if (eventType == XmlPullParser.START_TAG) {
if(name.equalsIgnoreCase("item")) {
isItem = true;
continue;
}
}
String result = "";
if (xmlPullParser.next() == XmlPullParser.TEXT) {
result = xmlPullParser.getText();
xmlPullParser.nextTag();
}
System.out.println(result);
System.out.println(isItem);
if (name.equalsIgnoreCase("title")) {
title = result;
} else if (name.equalsIgnoreCase("description")) {
description = result.substring(result.indexOf("<img"));
}
else if (name.equalsIgnoreCase("pubDate"))
pubDate=result;
else if (name.equalsIgnoreCase("link"))
link = result;
else if (name.equalsIgnoreCase("content:encoded"))
content=result.substring(result.indexOf("<div"),result.indexOf("]]")-1);
if (description!=null&&description.startsWith("<img"))
{
System.out.println(description.substring(10,74));
url=new URL(description.substring(10,74));
description=description.substring(description.indexOf("/>")+2);
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
}
if (title != null && description != null && bitmap!=null && link!=null) {
if(isItem) {
FeedModel item = new FeedModel(title, description, pubDate, content, bitmap, feed, link);
items.add(item);
}
title = null;
description = null;
pubDate=null;
link=null;
content=null;
bitmap=null;
isItem = false;
}
}
return items;
} finally {
inputStream.close();
}
}
public class FeedTask extends AsyncTask<Void,Void,Void>{
private String feedTask;
public FeedTask(String feed)
{
this.feedTask=feed;
}
#Override
protected void onPreExecute() {
if (anInt==1)
{
MainActivity.this.anInt=0;
centerError.animate().alpha(0f).setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime)).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
centerError.setVisibility(View.GONE);
super.onAnimationStart(animation);
}
});
}
swipeRefreshLayout.setRefreshing(true);
recyclerView.animate().alpha(0f).setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime));
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL(feedTask);
InputStream inputStream = url.openConnection().getInputStream();
feedModelList = parseFeed(inputStream);
}
catch (Exception e){}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (feedModelList!=null) {
recyclerView.setAdapter(new FeedAdapter(feedModelList, MainActivity.this));
recyclerView.animate().alpha(1f).setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime));
}
else System.out.println("heeey");
swipeRefreshLayout.setRefreshing(false);
super.onPostExecute(aVoid);
}
}
Related
I'm trying to parse XML from URL and not getting any data, when I debug I see that I'm stuck in the while() loop. The variable i came up to 160 before I gave up. I don't get why I'm stuck in the while loop and not getting into any of the if statements in the loop.
public class Task extends AsyncTask<Void,Void,Void> {
private List<Task> tasks;
public Task()
{
}
#Override
protected Void doInBackground(Void... params) {
makeTask();
return null;
}
public Task(String title){
mTitle = title;
}
private List<Task> makeTask(){
int i = 0;
tasks = new ArrayList<>();
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
URL url = new URL("http://xxx");
InputStream stream = url.openStream();
xpp.setInput(stream, null);
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_DOCUMENT) {
}
else if (eventType == XmlPullParser.END_DOCUMENT) {
}
else if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("Task")) {
tasks.add(new Task(xpp.nextText()));
Log.d("Task: ", xpp.nextText());
}
else if (eventType == XmlPullParser.END_TAG) {
}
else if (eventType == XmlPullParser.TEXT) {
}
eventType = xpp.next();
}
i++;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return tasks;
}
Edit:
This is the new while() loop and working thanks to #imsiso
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("name")) {
tasks.add(new Task(xpp.nextText()));
}
eventType = xpp.next();
}
else
eventType = xpp.next();
The line below in the code List<Task> tasks = task.getTasks(); is giving error:
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
I'm think that I'm getting that error because I'm not waiting for the AsyncTask to finish and don't know how I should do that.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/*Removed irrelevant code here*/
Task task = new Task();
new Task().execute();
List<Task> tasks = task.getTasks();
mAdapter = new TaskAdapter(tasks);
mTaskRV.setAdapter(mAdapter);
return view;
}
Here's an example TaskLoader and Callback for Loader.
private LoaderManager.LoaderCallbacks<List<TaskModel>> mLoaderCallbacks = new LoaderManager.LoaderCallbacks<List<TaskModel>>()
{
#Override
public Loader<List<TaskModel>> onCreateLoader(int id, Bundle args)
{
return new TaskLoader(getContext());
}
#Override
public void onLoadFinished(Loader<List<TaskModel>> loader, List<TaskModel> data)
{
mTaskRV.setAdapter(new TaskAdapter(data));
}
#Override
public void onLoaderReset(Loader<List<TaskModel>> loader)
{
//
}
};
And the TaskLoader.
private static class TaskLoader extends AsyncTaskLoader<List<TaskModel>>
{
private static final String TAG = TaskLoader.class.getSimpleName();
private List<TaskModel> mData = null;
public TaskLoader(Context context)
{
super(context);
}
#Override
protected void onStartLoading()
{
super.onStartLoading();
if(mData != null){
deliverResult(mData);
}
if(takeContentChanged() || mData == null){
forceLoad();
}
}
#Override
public void deliverResult(List<TaskModel> data)
{
mData = data;
super.deliverResult(data);
}
#Override
public List<TaskModel> loadInBackground()
{
try{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
URL url = new URL("http://xxx");
InputStream in = null;
try{
in = url.openStream();
xpp.setInput(in, "UTF-8");
return parseTasks(xpp);
}
finally{
if(in != null){
in.close();
}
}
}
catch(MalformedURLException e){
Log.e(TAG, "loadInBackground", e);
}
catch(XmlPullParserException e){
Log.e(TAG, "loadInBackground", e);
}
catch(IOException e){
Log.e(TAG, "loadInBackground", e);
}
return null;
}
private List<TaskModel> parseTasks(XmlPullParser xpp)
throws XmlPullParserException, IOException
{
ArrayList<TaskModel> tasks = new ArrayList<>();
int eventType = xpp.getEventType();
while(eventType != XmlPullParser.END_DOCUMENT){
if(eventType == XmlPullParser.START_TAG){
if(xpp.getName().equalsIgnoreCase("description")){
tasks.add(new TaskModel(xpp.nextText()));
}
}
eventType = xpp.next();
}
return tasks;
}
}
You should provide a listener to the async task that will be triggered when the doInBackground() completes. For instance:
public interface TaskListener{
public void onTaskDone(List<Task> results);
}
public class Task extends AsyncTask<Void,Void,Void> {
private List<Task> tasks;
private TaskListener mListener;
public Task(TaskListener listener)
{
this.mListener = listener;
}
protected Void doInBackground(Void... params) {
.... xml parsing...
if (mListener != null){
mListener.onTaskDone(tasks);
}
}
}
and when you create the task:
Task task = new Task(this);
letting the class implementing the TaskListener interface.
In this method you provide the task's result to the adapter.
public void onTaskDone(final List<Task> tasks){
runOnUiThread(new Runnable() {
#Override
public void run() {
mAdapter = new TaskAdapter(tasks);
mTaskRV.setAdapter(mAdapter);
}
});
}
First let's use this for while which is more clear. And using get text should be better cause it can avoid jumping over a tag or such in other cases.
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("name")) {
tasks.add(new Task(xpp.getText()));
}
}
eventType = xpp.next();
}
And a out that error in List<Task> tasks = task.getTasks(); This should help https://stackoverflow.com/a/218510/2226796
Also I didn't get this part :
Task task = new Task();
new Task().execute();
I have set up a activity on my app that creates a new high score then saves it and allows it to be reloaded and display through FileOutputStream and FileInputStream logic. I have been testing the app on my phone and when loading the high score back I am getting 0 returned. I believe this is because there are zero bytes within the file.
Heres all my code:
public class Course extends ActionBarActivity {
String chosenCourseValue = "";
int courseNum;
String listPars = "";
String listHoles = "";
String courseImage = "";
int[] scoreNum = new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int totalScoreNum = 0;
String collected = "test string";
public void upButtonOnClick(View imageButton)
{
int textViewId = getResources().getIdentifier((String) imageButton.getTag(), "id", getPackageName());
TextView score = (TextView) findViewById(textViewId);
totalScoreNum++;
if (score.getId() == R.id.score1)
{
scoreNum[0]++;
score.setText(String.valueOf(scoreNum[0]));
}
if (score.getId() == R.id.score2)
{
scoreNum[1]++;
score.setText(String.valueOf(scoreNum[1]));
}
if (score.getId() == R.id.score3)
{
scoreNum[2]++;
score.setText(String.valueOf(scoreNum[2]));
}
if (score.getId() == R.id.score4)
{
scoreNum[3]++;
score.setText(String.valueOf(scoreNum[3]));
}
if (score.getId() == R.id.score5)
{
scoreNum[4]++;
score.setText(String.valueOf(scoreNum[4]));
}
if (score.getId() == R.id.score6)
{
scoreNum[5]++;
score.setText(String.valueOf(scoreNum[5]));
}
if (score.getId() == R.id.score7)
{
scoreNum[6]++;
score.setText(String.valueOf(scoreNum[6]));
}
if (score.getId() == R.id.score8)
{
scoreNum[7]++;
score.setText(String.valueOf(scoreNum[7]));
}
if (score.getId() == R.id.score9)
{
scoreNum[8]++;
score.setText(String.valueOf(scoreNum[8]));
}
if (score.getId() == R.id.score10)
{
scoreNum[9]++;
score.setText(String.valueOf(scoreNum[9]));
}
if (score.getId() == R.id.score11)
{
scoreNum[10]++;
score.setText(String.valueOf(scoreNum[10]));
}
if (score.getId() == R.id.score12)
{
scoreNum[11]++;
score.setText(String.valueOf(scoreNum[11]));
}
if (score.getId() == R.id.score13)
{
scoreNum[12]++;
score.setText(String.valueOf(scoreNum[12]));
}
if (score.getId() == R.id.score14)
{
scoreNum[13]++;
score.setText(String.valueOf(scoreNum[13]));
}
if (score.getId() == R.id.score15)
{
scoreNum[14]++;
score.setText(String.valueOf(scoreNum[14]));
}
if (score.getId() == R.id.score16)
{
scoreNum[15]++;
score.setText(String.valueOf(scoreNum[15]));
}
if (score.getId() == R.id.score17)
{
scoreNum[16]++;
score.setText(String.valueOf(scoreNum[16]));
}
if (score.getId() == R.id.score18)
{
scoreNum[17]++;
score.setText(String.valueOf(scoreNum[17]));
}
}
public void downButtonOnClick(View imageButton)
{
int textViewId = getResources().getIdentifier((String) imageButton.getTag(), "id", getPackageName());
TextView score = (TextView) findViewById(textViewId);
totalScoreNum--;
if (score.getId() == R.id.score1)
{
scoreNum[0]--;
score.setText(String.valueOf(scoreNum[0]));
}
if (score.getId() == R.id.score2)
{
scoreNum[1]--;
score.setText(String.valueOf(scoreNum[1]));
}
if (score.getId() == R.id.score3)
{
scoreNum[2]--;
score.setText(String.valueOf(scoreNum[2]));
}
if (score.getId() == R.id.score4)
{
scoreNum[3]--;
score.setText(String.valueOf(scoreNum[3]));
}
if (score.getId() == R.id.score5)
{
scoreNum[4]--;
score.setText(String.valueOf(scoreNum[4]));
}
if (score.getId() == R.id.score6)
{
scoreNum[5]--;
score.setText(String.valueOf(scoreNum[5]));
}
if (score.getId() == R.id.score7)
{
scoreNum[6]--;
score.setText(String.valueOf(scoreNum[6]));
}
if (score.getId() == R.id.score8)
{
scoreNum[7]--;
score.setText(String.valueOf(scoreNum[7]));
}
if (score.getId() == R.id.score9)
{
scoreNum[8]--;
score.setText(String.valueOf(scoreNum[8]));
}
if (score.getId() == R.id.score10)
{
scoreNum[9]--;
score.setText(String.valueOf(scoreNum[9]));
}
if (score.getId() == R.id.score11)
{
scoreNum[10]--;
score.setText(String.valueOf(scoreNum[10]));
}
if (score.getId() == R.id.score12)
{
scoreNum[11]--;
score.setText(String.valueOf(scoreNum[11]));
}
if (score.getId() == R.id.score13)
{
scoreNum[12]--;
score.setText(String.valueOf(scoreNum[12]));
}
if (score.getId() == R.id.score14)
{
scoreNum[13]--;
score.setText(String.valueOf(scoreNum[13]));
}
if (score.getId() == R.id.score15)
{
scoreNum[14]--;
score.setText(String.valueOf(scoreNum[14]));
}
if (score.getId() == R.id.score16)
{
scoreNum[15]--;
score.setText(String.valueOf(scoreNum[15]));
}
if (score.getId() == R.id.score17)
{
scoreNum[16]--;
score.setText(String.valueOf(scoreNum[16]));
}
if (score.getId() == R.id.score18)
{
scoreNum[17]--;
score.setText(String.valueOf(scoreNum[17]));
}
}
class AsyncAPI extends AsyncTask<Void, Void, String>
{
#Override
protected String doInBackground(Void... arg0)
{
String JSONString = null;
try
{
//hard coded url API from website
String urlString = "http://webthree.ict.op.ac.nz/murraas1/golf.html";
//converting url string to object then sending (same as pressing return)
URL URLObject = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) URLObject.openConnection();
connection.connect();
//if it doesnt return 200 no data received. (use if statement to check in future)
int responseCode = connection.getResponseCode();
//getting inputstream from the sent object and setting up bufferreader
InputStream inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//reading the input
String responseString;
StringBuilder stringBuilder = new StringBuilder();
while ((responseString = bufferedReader.readLine()) != null)
{
stringBuilder = stringBuilder.append(responseString);
}
//getting string from stringbuilder and converting to a json string
JSONString = stringBuilder.toString();
}
catch (Exception e){e.printStackTrace();}
return JSONString;
}
protected void onPostExecute(String fetchedString)
{
String selectedCourse = "";
String totalPar = "";
if (chosenCourseValue.equals("Chisholm"))
{
courseNum = 0;
courseImage = "chisolm";
}
if (chosenCourseValue.equals("St Clair"))
{
courseNum = 1;
courseImage = "stclair";
}
if (chosenCourseValue.equals("Balmacewen"))
{
courseNum = 2;
courseImage = "balmacewen";
}
if (chosenCourseValue.equals("Taieri"))
{
courseNum = 3;
courseImage = "taieri";
}
if (chosenCourseValue.equals("Island Park"))
{
courseNum = 4;
courseImage = "islandpark";
}
try {
JSONObject root = new JSONObject(fetchedString);
JSONArray courseArray = root.getJSONArray("courses");
JSONObject courseInfo = courseArray.getJSONObject(courseNum);
selectedCourse = (courseInfo.getString("name"));
totalPar = (courseInfo.getString("course par"));
JSONArray parsInfo = courseInfo.getJSONArray("pars");
for(int i = 0; i < parsInfo.length(); i++)
{
JSONObject parsNum = parsInfo.getJSONObject(i);
listPars += ("Par " + parsNum.getString("par") + ",");
}
JSONArray holesInfo = courseInfo.getJSONArray("pars");
for(int i = 0; i < holesInfo.length(); i++)
{
JSONObject holeNum = holesInfo.getJSONObject(i);
listHoles += (holeNum.getString("hole") + ",");
}
}
catch (JSONException e) {
e.printStackTrace();
}
//Convert Pars and Holes text into usable array
String[] listParsArray = listPars.split(",");
String[] listHolesArray = listHoles.split(",");
//dumping Name into textview
TextView tv = (TextView) findViewById(R.id.courseName);
tv.setText(selectedCourse);
//dumping Total Par into textview
TextView tv1 = (TextView) findViewById(R.id.totalPar);
tv1.setText(totalPar);
//dumping Pars into textview
int[] parViewIDs = new int[] {R.id.hole1Par, R.id.hole2Par, R.id.hole3Par, R.id.hole4Par, R.id.hole5Par, R.id.hole6Par, R.id.hole7Par, R.id.hole8Par, R.id.hole9Par, R.id.hole10Par, R.id.hole11Par, R.id.hole12Par, R.id.hole13Par, R.id.hole14Par, R.id.hole15Par, R.id.hole16Par, R.id.hole17Par, R.id.hole18Par,};
for(int i = 0; i < 18; i++) {
TextView tv2 = (TextView) findViewById(parViewIDs[i]);
tv2.setText(listParsArray[i]);
}
//dumping Holes into textview
int[] holeViewIDs = new int[] {R.id.hole1, R.id.hole2, R.id.hole3, R.id.hole4, R.id.hole5, R.id.hole6, R.id.hole7, R.id.hole8, R.id.hole9, R.id.hole10, R.id.hole11, R.id.hole12, R.id.hole13, R.id.hole14, R.id.hole15, R.id.hole16, R.id.hole17, R.id.hole18,};
for(int i = 0; i < 18; i++)
{
TextView tv3 = (TextView) findViewById(holeViewIDs[i]);
tv3.setText(listHolesArray[i]);
}
int[] images = {R.drawable.chisholm, R.drawable.stclair, R.drawable.balmacewen, R.drawable.taieri, R.drawable.islandpark};
ImageView i = (ImageView) findViewById(R.id.courseImage);
i.setImageResource(images[courseNum]);
}
}
private void updateTextView() {
TextView tv3 = (TextView) findViewById(R.id.totalScore);
tv3.setText(String.valueOf(totalScoreNum));
}
public class SaveData implements View.OnClickListener
{
//String totalScoreString = String.valueOf(totalScoreNum);
#Override
public void onClick(View v) {
try {
FileOutputStream fou = openFileOutput("scoreFile.txt", Context.MODE_PRIVATE);
fou.write(totalScoreNum);
fou.close();
// Toast Confirm
Toast.makeText(Course.this, "Success", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void loadData()
{
FileInputStream fis = null;
try {
fis = openFileInput("scoreFile.txt");
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
collected = new String(dataArray);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public class LoadData implements View.OnClickListener
{
#Override
public void onClick(View v) {
TextView tv7 = (TextView) findViewById(R.id.returnScore);
tv7.setText(collected);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course);
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateTextView();
}
});
}
} catch (InterruptedException e) {
}
}
};
loadData();
t.start();
Button SaveDataBtn = (Button)findViewById(R.id.saveScore);
SaveData handler = new SaveData();
SaveDataBtn.setOnClickListener (handler);
Button LoadDataBtn = (Button)findViewById(R.id.loadScore);
LoadData handler1 = new LoadData();
LoadDataBtn.setOnClickListener (handler1);
Bundle extras = getIntent().getExtras();
if (extras != null) {
chosenCourseValue = extras.getString("passedChosenCourse");
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
AsyncAPI APIThread = new AsyncAPI();
APIThread.execute();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Heres the FileOutputStream FileInputStream where i believe the problem lies:
public class SaveData implements View.OnClickListener
{
//String totalScoreString = String.valueOf(totalScoreNum);
#Override
public void onClick(View v) {
try {
FileOutputStream fou = openFileOutput("scoreFile.txt", Context.MODE_PRIVATE);
fou.write(totalScoreNum);
fou.close();
// Toast Confirm
Toast.makeText(Course.this, "Success", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void loadData()
{
FileInputStream fis = null;
try {
fis = openFileInput("scoreFile.txt");
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
collected = new String(dataArray);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
When first running the app loading back the score will return the string "test string" which it was initially populated with, but once a actual score is loaded and saved it will return "0". Any help or explanation would be appreciated!
Have you tried supplying a full path for the input and output stream?
For example "/sdcard/Downloads/myapp/scoreFile.txt"
Also don't hardcode the path, use Environment.getExternalStorageDirectory(), I think this will return a File object or string path equal to "/sdcard/"
Don't forgot to add permissions for the external read and write
I have an Async task that loads information from the server and displays data on the UI. Suddenly the async task downloads the data and formats the JSON data fine but it would freeze the UI completely.
Here is the base download class
public class GetRawData {
private static String LOG_TAG = GetRawData.class.getSimpleName();
private String mRawURL;
private List<NameValuePair> mRawParams = null;
private String mRawData;
private DownloadStatus mDownloadStatus;
public GetRawData(String mRawURL) {
this.mRawURL = mRawURL;
this.mRawParams = null;
this.mDownloadStatus = DownloadStatus.IDLE;
}
public String getRawData() {
return mRawData;
}
public void setRawURL(String mRawURL) {
this.mRawURL = mRawURL;
}
public List<NameValuePair> getRawParams() {
return mRawParams;
}
public void setRawParams(List<NameValuePair> mParams) {
this.mRawParams = mParams;
}
public DownloadStatus getDownloadStatus() {
return mDownloadStatus;
}
public void reset() {
this.mRawURL = null;
this.mRawData = null;
this.mDownloadStatus = DownloadStatus.IDLE;
}
public void execute() {
this.mDownloadStatus = DownloadStatus.PROCESSING;
DownloadRawData mDownloadRawData = new DownloadRawData();
mDownloadRawData.execute(mRawURL);
}
public class DownloadRawData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// Create URL and Reader instances.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
//If no parameter has been provided, return null.
if (params == null)
return null;
try {
// Get URL entered by the user.
URL mURL = new URL(params[0]);
urlConnection = (HttpURLConnection) mURL.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
urlConnection.setRequestProperty("Content-Type","application/json");
//urlConnection.setRequestProperty("Host", "android.schoolportal.gr");
urlConnection.connect();
// validate and add parameters if available.
if (mRawParams != null && mRawParams.size()>0){
JSONObject jsonParam = new JSONObject();
for (NameValuePair pair : mRawParams) {
jsonParam.put(pair.getName().toString(), pair.getValue().toString());
}
String jsonparams = jsonParam.toString();
// Send POST output.
DataOutputStream printout;
printout = new DataOutputStream(urlConnection.getOutputStream());
printout.writeBytes(jsonparams);
printout.flush();
printout.close();
}
int HttpResult =urlConnection.getResponseCode();
StringBuffer buffer = new StringBuffer();
if(HttpResult ==HttpURLConnection.HTTP_OK){
InputStream inputStream = urlConnection.getInputStream();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
System.out.println(""+buffer.toString());
}else{
InputStream errorStream = urlConnection.getErrorStream();
if (errorStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(errorStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
System.out.println(urlConnection.getResponseMessage());
}
return buffer.toString();
} catch (IOException e) {
Log.d("IOException", e.toString());
return null;
} catch (JSONException j) {
Log.d("JSONException", j.toString());
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.d("IOException", "unable to close the reader");
}
}
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mRawData = result;
//Log.d("onPostExecute", result);
if (mRawData == null) {
if (mRawURL == null) {
mDownloadStatus = DownloadStatus.NOT_INITIALIZED;
} else {
mDownloadStatus = DownloadStatus.FAILED_OR_EMPTY;
}
} else {
mDownloadStatus = DownloadStatus.PROCESSED;
}
}
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
}
}
enum DownloadStatus {
IDLE,
PROCESSING,
NOT_INITIALIZED,
FAILED_OR_EMPTY,
PROCESSED
}
Here is the specific data formatting class the extends above class
public class GetJobCardJsonData extends GetRawData {
private static String LOG_TAG = GetAuthenticationJsonData.class.getSimpleName();
private static String JOBCARD_SERVICE_URL = "http://www.appservice.com/appservice/jobcardinfoservice.asmx/GetJobCardInfo";
private List<JobCard> mJobCardList;
private CarcalDownloadListener mListener;
public GetJobCardJsonData(String CurrentDate, int DealershipID) {
super(null);
List<NameValuePair> mParams = new ArrayList<NameValuePair>();
mParams.add(new BasicNameValuePair("JobCardDate", CurrentDate));
mParams.add(new BasicNameValuePair("DealershipID", String.valueOf(DealershipID)));
this.setRawParams(mParams);
}
public List<JobCard> getJobCardList() {
return mJobCardList;
}
public void getjobcards() {
super.setRawURL(JOBCARD_SERVICE_URL);
DownloadJobCardJsonData mDownloadJobCardJsonData = new DownloadJobCardJsonData();
mDownloadJobCardJsonData.execute(JOBCARD_SERVICE_URL);
}
public void setOnCarcalDownloadListener(CarcalDownloadListener onCarcalDownloadListener) {
this.mListener = onCarcalDownloadListener;
}
private void processResult() {
if (getDownloadStatus() != DownloadStatus.PROCESSED) {
Log.e(LOG_TAG, "Error Downloading the raw file.");
return;
}
if (mJobCardList == null){
mJobCardList = new ArrayList<JobCard>();
}
final String JOBCARD_JOBCARDID = "JobCardID";
final String JOBCARD_GETSTOCKNUMBER_WITH_DELIVERYTIME = "StockNumberWithDeliveryTime";
final String JOBCARD_CUSTOMERNAME = "CustomerName";
final String JOBCARD_MODELNUMBER = "ModelNumber";
final String JOBCARD_COLOR = "Color";
final String JOBCARD_SALEEXECUTIVE = "SaleExecutive";
final String JOBCARD_ORDERSTATUS = "OrderStatus";
final String JOBCARD_SHOWROOMSTATUS = "ShowRoomStatus";
try {
JSONArray jsonArray = new JSONArray(getRawData());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jobcarditem = jsonArray.optJSONObject(i);
Long JOBCARDID = jobcarditem.getLong(JOBCARD_JOBCARDID);
String STOCKWITHDELIVERY = jobcarditem.getString(JOBCARD_GETSTOCKNUMBER_WITH_DELIVERYTIME);
String CUSTOMERNAME = jobcarditem.getString(JOBCARD_CUSTOMERNAME);
String MODELNUMBER = jobcarditem.getString(JOBCARD_MODELNUMBER);
String COLOR = jobcarditem.getString(JOBCARD_COLOR);
String SALEEXECUTIVE = jobcarditem.getString(JOBCARD_SALEEXECUTIVE);
int ORDERSTATUS = jobcarditem.getInt(JOBCARD_ORDERSTATUS);
int SHOWROOMSTATUS = jobcarditem.getInt(JOBCARD_SHOWROOMSTATUS);
JobCard mJobCard = new JobCard(JOBCARDID, STOCKWITHDELIVERY, CUSTOMERNAME, MODELNUMBER, COLOR, SALEEXECUTIVE, ORDERSTATUS, SHOWROOMSTATUS);
mJobCardList.add(mJobCard);
}
} catch (JSONException jsone) {
jsone.printStackTrace();
Log.e(LOG_TAG, "Error processing json data.");
}
}
public class DownloadJobCardJsonData extends DownloadRawData {
#Override
protected String doInBackground(String... params) {
return super.doInBackground(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
processResult();
mListener.OnDownloadCompleted();
}
}
}
Here is the code that is called on the activity
private JobCardRecyclerViewAdapter mJobCardRecyclerViewAdapter;
private GetJobCardJsonData mGetJobCardJsonData;
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_job_card_calender);
activateToolbarWithHomeEnabled();
String formattedDate="";
if (session.getCurrentDate() == ""){
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
formattedDate = df.format(c.getTime());
currentDateTextView.setText(formattedDate);
}else {
formattedDate = session.getCurrentDate();
currentDateTextView.setText(formattedDate);
}
// Fetch data for current date.
mGetJobCardJsonData = new GetJobCardJsonData(formattedDate, session.getDealershipID());
mGetJobCardJsonData.getjobcards();
mGetJobCardJsonData.setOnCarcalDownloadListener(new CarcalDownloadListener() {
#Override
public void OnDownloadCompleted() {
List<JobCard> mJobCards = mGetJobCardJsonData.getJobCardList();
mJobCardRecyclerViewAdapter = new JobCardRecyclerViewAdapter(mJobCards, JobCardCalenderActivity.this);
mRecyclerView.setAdapter(mJobCardRecyclerViewAdapter);
}
});
}
Can anyone help on what i am doing wrong that is freezing the UI. It was working fine before and has started to freeze the UI suddenly.
I was able to fix the issue, the problem was not with Async task but with the layout. I accidently wrapped the recycler view with scroll view. which was causing the UI to freeze. Looks weird that a scroll view caused the whole UI thread to freeze. but here is my solution
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<view
android:id="#+id/jobCardRecyclerView"
class="android.support.v7.widget.RecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/jobCardHeader"
android:scrollbars="vertical"></view>
</ScrollView>
Changed it to
<view
android:id="#+id/jobCardRecyclerView"
class="android.support.v7.widget.RecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/jobCardHeader"
android:scrollbars="vertical"></view>
hope it will be helpful for others facing same problem.
I am trying to parse rss feed in honeycomb 3.0 but it gives error as follows.
ERROR/AndroidNews::PullFeedParser(444): android.os.NetworkOnMainThreadException
I tried same code in android lower version it works but it doesn't work in Honeycomb.
Please suggest some help
This is in main activity
try{
FeedParser parser = new XmlPullFeedParser(feedUrl);
messages = parser.parse();
titles = new ArrayList<String>(messages.size());
String description ="";//= new ArrayList<String>(messages.size());
for (Message msg : messages){
description = msg.getDescription().toString();
Log.v("Desc", description);
titles.add(description);
}
} catch (Throwable t){
Log.e("AndroidNews",t.getMessage(),t);
}
I am using XmlPullFeedParser which extends BaseFeedParser
public class XmlPullFeedParser extends BaseFeedParser {
public XmlPullFeedParser(String feedUrl) {
super(feedUrl);
}
public List<Message> parse() {
List<Message> messages = null;
XmlPullParser parser = Xml.newPullParser();
try {
// auto-detect the encoding from the stream
parser.setInput(this.getInputStream(), null);
int eventType = parser.getEventType();
Message currentMessage = null;
boolean done = false;
while (eventType != XmlPullParser.END_DOCUMENT && !done){
String name = null;
switch (eventType){
case XmlPullParser.START_DOCUMENT:
messages = new ArrayList<Message>();
break;
case XmlPullParser.START_TAG:
name = parser.getName();
if (name.equalsIgnoreCase(ITEM)){
currentMessage = new Message();
} else if (currentMessage != null){
if (name.equalsIgnoreCase(LINK)){
currentMessage.setLink(parser.nextText());
} else if (name.equalsIgnoreCase(DESCRIPTION)){
currentMessage.setDescription(parser.nextText());
} else if (name.equalsIgnoreCase(PUB_DATE)){
currentMessage.setDate(parser.nextText());
} else if (name.equalsIgnoreCase(TITLE)){
currentMessage.setTitle(parser.nextText());
}
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
if (name.equalsIgnoreCase(ITEM) && currentMessage != null){
messages.add(currentMessage);
} else if (name.equalsIgnoreCase(CHANNEL)){
done = true;
}
break;
}
eventType = parser.next();
}
} catch (Exception e) {
Log.e("AndroidNews::PullFeedParser", e.getMessage(), e);
throw new RuntimeException(e);
}
return messages;
}
}
This is BaseFeedParser:
public class BaseFeedParser implements FeedParser {
// names of the XML tags
static final String CHANNEL = "channel";
static final String PUB_DATE = "pubDate";
static final String DESCRIPTION = "description";
static final String LINK = "link";
static final String TITLE = "title";
static final String ITEM = "item";
static final String BODY = "body";
private final URL feedUrl;
protected BaseFeedParser(String feedUrl){
try {
this.feedUrl = new URL(feedUrl);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
protected InputStream getInputStream() {
try {
return feedUrl.openConnection().getInputStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public List<Message> parse() {
// TODO Auto-generated method stub
return null;
}
}
This is FeedParser:
public interface FeedParser {
List<Message> parse();
}
This is message class:
public class Message implements Comparable<Message>{
static SimpleDateFormat FORMATTER =
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
private String title;
private URL link;
private String description;
private Date date;
private String body;
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
public void setTitle(String title) {
this.title = title.trim();
}
// getters and setters omitted for brevity
public URL getLink() {
return link;
}
public void setLink(String link) {
try {
this.link = new URL(link);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description.trim();
}
public String getDate() {
return FORMATTER.format(this.date);
}
public void setDate(String date) {
// pad the date if necessary
while (!date.endsWith("00")){
date += "0";
}
try {
this.date = FORMATTER.parse(date.trim());
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
public Message copy(){
Message copy = new Message();
copy.title = title;
copy.link = link;
copy.description = description;
copy.date = date;
copy.body = body;
return copy;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Title: ");
sb.append(title);
sb.append("Body: ");
sb.append(body);
sb.append('\n');
sb.append("Date: ");
sb.append(this.getDate());
sb.append('\n');
sb.append("Link: ");
sb.append(link);
sb.append('\n');
sb.append("Description: ");
sb.append(description);
return sb.toString();
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result
+ ((description == null) ? 0 : description.hashCode());
result = prime * result + ((link == null) ? 0 : link.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Message other = (Message) obj;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (link == null) {
if (other.link != null)
return false;
} else if (!link.equals(other.link))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title)){
return false;
} else if (!body.equals(other.body))
return false;
return true;
}
public int compareTo(Message another) {
if (another == null) return 1;
// sort descending, most recent first
return another.date.compareTo(date);
}
}
The error message here pretty much tells you what is going on -- you are trying to access the network on tthe main thread. You really shouldn't do that on any version of android, because it can (read: will) cause your UI to hang while the connection is processing.
There are ways to turn the error off, but I won't get into tthem: you shouodnt do it.
instead, you want to do this work in aa background thread and post a minimal handler back to the UI thread. I don't have an example handy (on my tablet now) but let me know if you cannot find one.
..edit..
OK, here's a simple example. This requires an activity with a text view (id "text") and, of course, INTERNET permissions. Let me know if you have any questions!
public class MainActivity extends Activity {
private TextView mTextView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.text);
// start our call in a new thread
(new Thread(new Runnable() {
#Override
public void run() {
fetchPage();
}
})).start();
}
private void fetchPage() {
try {
URL url = new URL("http://stackoverflow.com/feeds");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
bos.write(buffer, 0, len1);
}
bos.close();
is.close();
// Remember, all UI things must occur back on the UI thread!
final String text = bos.toString();
this.runOnUiThread(new Runnable() {
#Override
public void run() {
mTextView.setText(text);
}
});
} catch (final IOException ioe) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, ioe.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
thanks,
--randy
I am new to android and i am trying to build a RSS reader for Android. I have built all the classes and XML files but its not giving the required output. Its just showing the message
No RSS feed available.
Please can some one suggest what should i do.
Here is the code which i took from the tutorial and tried to manipulate-
public final String RSSFEEDOFCHOICE = "http://blog.01synergy.com/feed/";
public final String tag = "RSSReader";
private RSSFeed feed = null;
/** Called when the activity is first created. */
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
// go get our feed!
feed = getFeed(RSSFEEDOFCHOICE);
// display UI
UpdateDisplay();
}
private RSSFeed getFeed(String urlToRssFeed)
{
try
{
// setup the url
URL url = new URL(urlToRssFeed);
// create the factory
SAXParserFactory factory = SAXParserFactory.newInstance();
// create a parser
SAXParser parser = factory.newSAXParser();
// create the reader (scanner)
XMLReader xmlreader = parser.getXMLReader();
// instantiate our handler
RSSHandler theRssHandler = new RSSHandler();
// assign our handler
xmlreader.setContentHandler(theRssHandler);
// get our data via the url class
InputSource is = new InputSource(url.openStream());
// perform the synchronous parse
xmlreader.parse(is);
// get the results - should be a fully populated RSSFeed instance, or null on error
return theRssHandler.getFeed();
}
catch (Exception ee)
{
// if we have a problem, simply return null
return null;
}
}
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
menu.add(0,0,0, "Choose RSS Feed");
menu.add(0,1,0, "Refresh");
Log.i(tag,"onCreateOptionsMenu");
return true;
}
public boolean onOptionsItemSelected(Menu item){
switch (((View) item).getId()) {
case 0:
Log.i(tag,"Set RSS Feed");
return true;
case 1:
Log.i(tag,"Refreshing RSS Feed");
return true;
}
return false;
}
private void UpdateDisplay()
{
TextView feedtitle = (TextView) findViewById(R.id.feedtitle);
TextView feedpubdate = (TextView) findViewById(R.id.feedpubdate);
ListView itemlist = (ListView) findViewById(R.id.itemlist);
if (feed == null)
{
feedtitle.setText("No RSS Feed Available");
return;
}
feedtitle.setText(feed.getTitle());
feedpubdate.setText(feed.getPubDate());
ArrayAdapter<RSSItem> adapter = new ArrayAdapter<RSSItem>(this,android.R.layout.simple_list_item_1,feed.getAllItems());
itemlist.setAdapter(adapter);
itemlist.setOnItemClickListener(this);
itemlist.setSelection(0);
}
public void onItemClick(AdapterView parent, View v, int position, long id)
{
Log.i(tag,"item clicked! [" + feed.getItem(position).getTitle() + "]");
Intent itemintent = new Intent(this,ShowDescription.class);
Bundle b = new Bundle();
b.putString("title", feed.getItem(position).getTitle());
b.putString("description", feed.getItem(position).getDescription());
b.putString("link", feed.getItem(position).getLink());
b.putString("pubdate", feed.getItem(position).getPubDate());
itemintent.putExtra("android.intent.extra.INTENT", b);
startSubActivity(itemintent,0);
}
private void startSubActivity(Intent itemintent, int i) {
// TODO Auto-generated method stub
}
}
This is my first approach to RSS Reader, It's no so dynamic and has boilerplate code but worked well for myself.
Usage:
RssParser parser = new RssParser(feedUrl);
Log.i("LOG", "Description: " + parser.getItem(3).description); //4th item's description
Class:
package com.uncocoder.course.app.feed_reader;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class RssParser extends DefaultHandler {
private StringBuilder content;
private boolean inChannel;
private boolean inImage;
private boolean inItem;
private ArrayList<Item> items = new ArrayList<Item>();
private Channel channel = new Channel();
private Item lastItem;
public RssParser(String url) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
URL sourceUrl = new URL(url);
xr.setContentHandler(this);
xr.parse(new InputSource(sourceUrl.openStream()));
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public class Item {
public String title;
public String description;
public String link;
public String category;
public String pubDate;
public String guid;
}
public class Channel {
public String title;
public String description;
public String link;
public String lastBuildDate;
public String generator;
public String imageUrl;
public String imageTitle;
public String imageLink;
public String imageWidth;
public String imageHeight;
public String imageDescription;
public String language;
public String copyright;
public String pubDate;
public String category;
public String ttl;
}
#Override
public void startDocument() throws SAXException {
Log.i("LOG", "StartDocument");
}
#Override
public void endDocument() throws SAXException {
Log.i("LOG", "EndDocument");
}
#Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if (localName.equalsIgnoreCase("image")) {
inImage = true;
}
if (localName.equalsIgnoreCase("channel")) {
inChannel = true;
}
if (localName.equalsIgnoreCase("item")) {
lastItem = new Item();
items.add(lastItem);
inItem = true;
}
content = new StringBuilder();
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equalsIgnoreCase("image")) {
inImage = false;
}
if (localName.equalsIgnoreCase("channel")) {
inChannel = false;
}
if (localName.equalsIgnoreCase("item")) {
inItem = false;
}
if (localName.equalsIgnoreCase("title")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.title = content.toString();
} else if (inImage) {
channel.imageTitle = content.toString();
} else if (inChannel) {
channel.title = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("description")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.description = content.toString();
} else if (inImage) {
channel.imageDescription = content.toString();
} else if (inChannel) {
channel.description = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("link")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.link = content.toString();
} else if (inImage) {
channel.imageLink = content.toString();
} else if (inChannel) {
channel.link = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("category")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.category = content.toString();
} else if (inChannel) {
channel.category = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("pubDate")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.pubDate = content.toString();
} else if (inChannel) {
channel.pubDate = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("guid")) {
if (content == null) {
return;
}
lastItem.guid = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("url")) {
if (content == null) {
return;
}
channel.imageUrl = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("width")) {
if (content == null) {
return;
}
channel.imageWidth = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("height")) {
if (content == null) {
return;
}
channel.imageHeight = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("language")) {
if (content == null) {
return;
}
channel.language = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("copyright")) {
if (content == null) {
return;
}
channel.copyright = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("ttl")) {
if (content == null) {
return;
}
channel.ttl = content.toString();
content = null;
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (content == null) {
return;
}
content.append(ch, start, length);
}
public Item getItem(int index) {
return items.get(index);
}
}
Check following link, It's open source RSS reader for Android, You can download code for reference
http://code.google.com/p/android-rss/
There is a tutorial (including complete source code) on how to build an Android RSS reder here:
part 1 (complete application)
part 2 (application updated to parse image tags from desciption)
part 3 (application update with Android 3.0)
The tutorial uses SAX parser and includes a complete Android project that accesses an RSS feed and then displays the feed in a list view.
There still seems to be a lot of people interested in this - so if you are looking for an Android 3.0+ with fragments/async tasks etc, as well as complete application code, I have updated the posts again, and they can be found here!
You can download and check my project on google-play.
This project is about some turkish sport channels feeds. Lots of channels are in one application.
You can check source code of project on github.
Parse this type of Rss Feeds easily using XmlPullParser
public class RSSParser {
public static ArrayList<Pojo> getParserData(String Data){
try {
RSSXMLTag currentTag = null;
ArrayList<Pojo> postDataList = new ArrayList<>();
XmlPullParserFactory factory = XmlPullParserFactory
.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(Data));
int eventType = xpp.getEventType();
Pojo pdData = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(
"EEEE, DD MMM yyyy ");
while (eventType != XmlPullParser.END_DOCUMENT) {
int i = 0;
if (eventType == XmlPullParser.START_DOCUMENT) {
} else if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equals("item")) {
pdData = new Pojo();
currentTag = RSSXMLTag.IGNORETAG;
} else if (xpp.getName().equals("title")) {
currentTag = RSSXMLTag.TITLE;
} else if (xpp.getName().equals("link")) {
currentTag = RSSXMLTag.LINK;
} else if (xpp.getName().equals("pubDate")) {
currentTag = RSSXMLTag.DATE;
} else if (xpp.getName().equals("creator")) {
currentTag = RSSXMLTag.CREATOR;
} else if (xpp.getName().equals("category")) {
currentTag = RSSXMLTag.CATEGORY;
} else if (xpp.getName().equals("description")) {
currentTag = RSSXMLTag.DESCRIPTION;
}
} else if (eventType == XmlPullParser.END_TAG) {
if (xpp.getName().equals("item")) {
// format the data here, otherwise format data in
// Adapter
Date postDate = dateFormat.parse(pdData.postDate);
pdData.postDate = dateFormat.format(postDate);
postDataList.add(pdData);
} else {
currentTag = RSSXMLTag.IGNORETAG;
}
} else if (eventType == XmlPullParser.TEXT) {
String content = xpp.getText();
content = content.trim();
Log.d("debug", content);
if (pdData != null) {
switch (currentTag) {
case TITLE:
if (content.length() != 0) {
if (pdData.postTitle != null) {
pdData.postTitle += content;
} else {
pdData.postTitle = content;
}
}
break;
case LINK:
if (content.length() != 0) {
if (pdData.postLink != null) {
pdData.postLink += content;
} else {
pdData.postLink = content;
}
}
break;
case DATE:
if (content.length() != 0) {
if (pdData.postDate != null) {
pdData.postDate += content;
} else {
pdData.postDate = content;
}
}
break;
case CATEGORY:
if (content.length() != 0) {
if (pdData.postCategory != null) {
i = i + 1;
if (i == 1) {
pdData.postCategory = content;
}
} else {
i = i + 1;
if (i == 1) {
pdData.postCategory = content;
}
}
}
break;
case DESCRIPTION:
if (content.length() != 0) {
if (pdData.postDescription != null) {
String s = content;
String string = s.substring(s.indexOf("src=\"") + 5, s.indexOf("\" class=\""));
pdData.postDescription += string;
} else {
String s = content;
String string = s.substring(s.indexOf("src=\"") + 5, s.indexOf("\" class=\""));
pdData.postDescription = string;
}
}
break;
case CREATOR:
if (content.length() != 0) {
if (pdData.postCreator != null) {
pdData.postCreator += content;
} else {
pdData.postCreator = content;
}
}
break;
default:
break;
}
}
}
eventType = xpp.next();
}
return postDataList;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public enum RSSXMLTag {
IGNORETAG, TITLE, LINK, DATE,CREATOR,CATEGORY, DESCRIPTION;
}
public class Pojo {
public String getPostTitle() {
return postTitle;
}
public void setPostTitle(String postTitle) {
this.postTitle = postTitle;
}
public String getPostLink() {
return postLink;
}
public void setPostLink(String postLink) {
this.postLink = postLink;
}
public String getPostDate() {
return postDate;
}
public void setPostDate(String postDate) {
this.postDate = postDate;
}
public String getPostCategory() {
return postCategory;
}
public void setPostCategory(String postCategory) {
this.postCategory = postCategory;
}
public String getPostDescription() {
return postDescription;
}
public void setPostDescription(String postDescription) {
this.postDescription = postDescription;
}
public String getPostCreator() {
return postCreator;
}
public void setPostCreator(String postCreator) {
this.postCreator = postCreator;
}
public String postTitle;
public String postLink;
public String postDate;
public String postCategory;
public String postDescription;
public String postCreator;
}
}