Android 3.0 Honeycomb problem in parsing RSS feed - android

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

Related

Android Async Task Freezes UI Completely

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.

How to view the Intents a BroadcastReceiver is receiving?

I have an infinite loop somewhere in my code, indicative of my group messaging BroadcastReceiver continually accepting only the first message in the database, over and over again, until I stop running the application. Note that the repeating of the message only occurs in the client app and not in the server database.
Is there way to trace what intent the BroadcastReceiver is receiving? ie. be able to view the intents the BroadcastReceiver is acting on to locate the source of these actions?
My code for both sending and receiving a group message if it helps: (BroadcastReceiver is near the bottom)
public class GroupMessaging extends Activity {
private static final int MESSAGE_CANNOT_BE_SENT = 0;
public String username;
public String groupname;
private EditText messageText;
private EditText messageHistoryText;
private Button sendMessageButton;
private Manager imService;
private InfoOfGroup group = new InfoOfGroup();
private StorageManipulater localstoragehandler;
private Cursor dbCursor;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((MessagingService.IMBinder) service).getService();
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(GroupMessaging.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.message); // messaging_screen);
messageHistoryText = (EditText) findViewById(R.id.messageHistory);
messageText = (EditText) findViewById(R.id.message);
messageText.requestFocus();
sendMessageButton = (Button) findViewById(R.id.sendMessageButton);
Bundle extras = this.getIntent().getExtras();
group.groupName = extras.getString(InfoOfGroup.GROUPNAME);
group.groupId = extras.getString(InfoOfGroup.GROUPID);
String msg = extras.getString(InfoOfGroupMessage.GROUP_MESSAGE_TEXT);
setTitle("Group: " + group.groupName);
// Retrieve the information
localstoragehandler = new StorageManipulater(this);
dbCursor = localstoragehandler.groupGet(group.groupId);
if (dbCursor.getCount() > 0) {
int noOfScorer = 0;
dbCursor.moveToFirst();
while ((!dbCursor.isAfterLast())
&& noOfScorer < dbCursor.getCount()) {
noOfScorer++;
// String 2: Username
// String 3: Message
this.appendToMessageHistory(dbCursor.getString(2),
dbCursor.getString(3));
dbCursor.moveToNext();
}
}
localstoragehandler.close();
if (msg != null) {
// Then friends username and message, not equal to null
this.appendToMessageHistory(group.groupId, msg);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
.cancel((group.groupId + msg).hashCode());
}
// The send button
sendMessageButton.setOnClickListener(new OnClickListener() {
CharSequence message;
Handler handler = new Handler();
public void onClick(View arg0) {
message = messageText.getText();
if (message.length() > 0) {
appendToMessageHistory(imService.getUsername(),
message.toString());
// *****************PROBLEM MAY BE
// HERE******************************
localstoragehandler.groupInsert(imService.getUsername(),
group.groupId, message.toString());
messageText.setText("");
Thread thread = new Thread() {
public void run() {
try {
if (imService.sendGroupMessage(group.groupId,
group.groupName, message.toString()) == null) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(
getApplicationContext(),
R.string.message_cannot_be_sent,
Toast.LENGTH_LONG).show();
// showDialog(MESSAGE_CANNOT_BE_SENT);
}
});
}
} catch (UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(),
R.string.message_cannot_be_sent,
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
};
thread.start();
}
}
});
messageText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == 66) {
sendMessageButton.performClick();
return true;
}
return false;
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
int message = -1;
switch (id) {
case MESSAGE_CANNOT_BE_SENT:
message = R.string.message_cannot_be_sent;
break;
}
if (message == -1) {
return null;
} else {
return new AlertDialog.Builder(GroupMessaging.this)
.setMessage(message)
.setPositiveButton(R.string.OK,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
/* User clicked OK so do some stuff */
}
}).create();
}
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(groupMessageReceiver);
unbindService(mConnection);
ControllerOfGroup.setActiveGroup(null);
}
#Override
protected void onResume() {
super.onResume();
bindService(new Intent(GroupMessaging.this, MessagingService.class),
mConnection, Context.BIND_AUTO_CREATE);
IntentFilter i = new IntentFilter();
i.addAction(MessagingService.TAKE_GROUP_MESSAGE);
registerReceiver(groupMessageReceiver, i);
ControllerOfGroup.setActiveGroup(group.groupName);
}
// For receiving messages from other users...
public class GroupMessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extra = intent.getExtras();
String username = extra.getString(InfoOfGroupMessage.FROM_USER);
String groupId = extra.getString(InfoOfGroupMessage.TO_GROUP_ID);
String message = extra
.getString(InfoOfGroupMessage.GROUP_MESSAGE_TEXT);
// *************************OR HERE******************************
if (username != null && message != null) {
if (group.groupId.equals(groupId)) {
appendToMessageHistory(username, message);
localstoragehandler.groupInsert(username, groupId, message);
} else {
if (message.length() > 15) {
message = message.substring(0, 15);
}
Toast.makeText(GroupMessaging.this,
username + " says '" + message + "'",
Toast.LENGTH_SHORT).show();
}
}
}
};
// Build receiver object to accept messages
private GroupMessageReceiver groupMessageReceiver = new GroupMessageReceiver();
// Setting username and message to the message box
public void appendToMessageHistory(String username, String message) {
if (username != null && message != null) {
messageHistoryText.append(username + ":\n");
messageHistoryText.append(message + "\n");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (localstoragehandler != null) {
localstoragehandler.close();
}
if (dbCursor != null) {
dbCursor.close();
}
}
}
MessagingService Class:
public class MessagingService extends Service implements Manager, Updater {
// private NotificationManager mNM;
public static String USERNAME;
public static final String TAKE_MESSAGE = "Take_Message";
public static final String FRIEND_LIST_UPDATED = "Take Friend List";
public static final String MESSAGE_LIST_UPDATED = "Take Message List";
public static final String TAKE_GROUP_MESSAGE = "Take_Group_Message";
public static final String GROUP_LIST_UPDATED = "Take Group List";
public static final String GROUP_MESSAGE_LIST_UPDATED = "Take Group Message List";
public ConnectivityManager conManager = null;
private final int UPDATE_TIME_PERIOD = 15000;
private String rawFriendList = new String();
private String rawMessageList = new String();
private String rawGroupList = new String();
private String rawGroupMessageList = new String();
SocketerInterface socketOperator = new Socketer(this);
private final IBinder mBinder = new IMBinder();
private String username;
private String password;
private String groupname;
private boolean authenticatedUser = false;
// timer to take the updated data from server
private Timer timer;
private StorageManipulater localstoragehandler;
private NotificationManager mNM;
public class IMBinder extends Binder {
public Manager getService() {
return MessagingService.this;
}
}
#Override
public void onCreate() {
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
localstoragehandler = new StorageManipulater(this);
conManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
new StorageManipulater(this);
// Timer is used to take the friendList info every UPDATE_TIME_PERIOD;
timer = new Timer();
Thread thread = new Thread() {
#Override
public void run() {
Random random = new Random();
int tryCount = 0;
while (socketOperator.startListening(10000 + random
.nextInt(20000)) == 0) {
tryCount++;
if (tryCount > 10) {
// if it can't listen a port after trying 10 times, give
// up...
break;
}
}
}
};
thread.start();
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private void showNotification(String username, String msg) {
// Set the icon, scrolling text and TIMESTAMP
String title = "AndroidIM: You got a new Message! (" + username + ")";
String text = username + ": "
+ ((msg.length() < 5) ? msg : msg.substring(0, 5) + "...");
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.notification)
.setContentTitle(title).setContentText(text);
Intent i = new Intent(this, IndividualMessaging.class);
i.putExtra(InfoOfFriend.USERNAME, username);
i.putExtra(InfoOfMessage.MESSAGETEXT, msg);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 0);
mBuilder.setContentIntent(contentIntent);
mBuilder.setContentText("New message from " + username + ": " + msg);
// Send the notification.
// We use a layout id because it is a unique number. We use it later to
// cancel.
mNM.notify((username + msg).hashCode(), mBuilder.build());
}
public String getUsername() {
return this.username;
}
public String sendMessage(String username, String tousername, String message)
throws UnsupportedEncodingException {
String params = "username=" + URLEncoder.encode(this.username, "UTF-8")
+ "&password=" + URLEncoder.encode(this.password, "UTF-8")
+ "&to=" + URLEncoder.encode(tousername, "UTF-8") + "&message="
+ URLEncoder.encode(message, "UTF-8") + "&action="
+ URLEncoder.encode("sendMessage", "UTF-8") + "&";
Log.i("PARAMS", params);
return socketOperator.sendHttpRequest(params);
}
private String getFriendList() throws UnsupportedEncodingException {
// after authentication, server replies with friendList xml
// Has the friend and group and message(s) xml
rawFriendList = socketOperator
.sendHttpRequest(getAuthenticateUserParams(username, password));
if (rawFriendList != null) {
this.parseFriendInfo(rawFriendList);
}
return rawFriendList;
}
private String getMessageList() throws UnsupportedEncodingException {
rawMessageList = socketOperator
.sendHttpRequest(getAuthenticateUserParams(username, password));
if (rawMessageList != null) {
this.parseMessageInfo(rawMessageList);
}
return rawMessageList;
}
private String getGroupList() throws UnsupportedEncodingException {
rawGroupList = socketOperator
.sendHttpRequest(getAuthenticateUserParams(username, password));
if (rawGroupList != null) {
this.parseGroupInfo(rawGroupList);
}
return rawGroupList;
}
private String getGroupMessageList() throws UnsupportedEncodingException {
rawGroupMessageList = socketOperator
.sendHttpRequest(getAuthenticateUserParams(username, password));
if (rawGroupMessageList != null) {
this.parseGroupInfo(rawGroupMessageList);
}
return rawGroupMessageList;
}
public String authenticateUser(String usernameText, String passwordText)
throws UnsupportedEncodingException {
this.username = usernameText;
this.password = passwordText;
this.authenticatedUser = false;
String result = null;
result = this.getFriendList(); // socketOperator.sendHttpRequest(getAuthenticateUserParams(username,
// password));
if (result != null && !result.equals(LoggingIn.AUTHENTICATION_FAILED)) {
// if user is authenticated then return string from server is not
// equal to AUTHENTICATION_FAILED
this.authenticatedUser = true;
rawFriendList = result;
USERNAME = this.username;
// For Friends
Intent i = new Intent(FRIEND_LIST_UPDATED);
i.putExtra(InfoOfFriend.FRIEND_LIST, rawFriendList);
sendBroadcast(i);
// For Groups
Intent iG = new Intent(GROUP_LIST_UPDATED);
i.putExtra(InfoOfGroup.GROUP_LIST, rawGroupList);
sendBroadcast(iG);
timer.schedule(new TimerTask() {
public void run() {
try {
// rawFriendList = IMService.this.getFriendList();
// sending friend list
Intent i = new Intent(FRIEND_LIST_UPDATED);
Intent i2 = new Intent(MESSAGE_LIST_UPDATED);
Intent i3 = new Intent(GROUP_LIST_UPDATED);
Intent i4 = new Intent(GROUP_MESSAGE_LIST_UPDATED);
String tmp = MessagingService.this.getFriendList();
String tmp2 = MessagingService.this.getMessageList();
String tmp3 = MessagingService.this.getGroupList();
String tmp4 = MessagingService.this
.getGroupMessageList();
// For friends
if (tmp != null) {
i.putExtra(InfoOfFriend.FRIEND_LIST, tmp);
sendBroadcast(i);
Log.i("friend list broadcast sent ", "");
if (tmp2 != null) {
i2.putExtra(InfoOfMessage.MESSAGE_LIST, tmp2);
sendBroadcast(i2);
Log.i("friend list broadcast sent ", "");
}
} else {
Log.i("friend list returned null", "");
}
// Changed to i3 and i4 for the intents created...
if (tmp3 != null) {
i3.putExtra(InfoOfGroup.GROUP_LIST, tmp3);
sendBroadcast(i3);
Log.i("group list broadcast sent ", "");
if (tmp4 != null) {
i4.putExtra(
InfoOfGroupMessage.GROUP_MESSAGE_LIST,
tmp4);
sendBroadcast(i4);
Log.i("group list broadcast sent ", "");
}
} else {
Log.i("group list returned null", "");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, UPDATE_TIME_PERIOD, UPDATE_TIME_PERIOD);
}
return result;
}
public void messageReceived(String username, String message) {
// FriendInfo friend = FriendController.getFriendInfo(username);
InfoOfMessage msg = IndividualMessageController.checkMessage(username);
if (msg != null) {
Intent i = new Intent(TAKE_MESSAGE);
i.putExtra(InfoOfMessage.USERID, msg.userid);
i.putExtra(InfoOfMessage.MESSAGETEXT, msg.messagetext);
sendBroadcast(i);
String activeFriend = ControllerOfFriend.getActiveFriend();
if (activeFriend == null || activeFriend.equals(username) == false) {
localstoragehandler.insert(username, this.getUsername(),
message.toString());
showNotification(username, message);
}
Log.i("TAKE_MESSAGE broadcast sent by im service", "");
}
}
#Override
public void groupMessageReceived(String username, String groupId,
String message) {
// FriendInfo friend = FriendController.getFriendInfo(username);
InfoOfGroupMessage msg = GroupMessageController.checkMessage(username);
if (msg != null) {
Intent i = new Intent(TAKE_GROUP_MESSAGE);
i.putExtra(InfoOfGroupMessage.FROM_USER, msg.fromUser);
i.putExtra(InfoOfGroupMessage.TO_GROUP_ID, msg.toGroupId);
i.putExtra(InfoOfGroupMessage.GROUP_MESSAGE_TEXT, msg.messageText);
sendBroadcast(i);
}
Log.i("TAKE_GROUP_MESSAGE broadcast sent by im service", "");
}
private String getAuthenticateUserParams(String usernameText,
String passwordText) throws UnsupportedEncodingException {
String params = "username="
+ URLEncoder.encode(usernameText, "UTF-8")
+ "&password="
+ URLEncoder.encode(passwordText, "UTF-8")
+ "&action="
+ URLEncoder.encode("authenticateUser", "UTF-8")
+ "&port="
+ URLEncoder.encode(
Integer.toString(socketOperator.getListeningPort()),
"UTF-8") + "&";
return params;
}
public void setUserKey(String value) {
}
public boolean isNetworkConnected() {
return conManager.getActiveNetworkInfo().isConnected();
}
public boolean isUserAuthenticated() {
return authenticatedUser;
}
public String getLastRawFriendList() {
return this.rawFriendList;
}
#Override
public void onDestroy() {
Log.i("IMService is being destroyed", "...");
super.onDestroy();
}
public void exit() {
timer.cancel();
socketOperator.exit();
socketOperator = null;
this.stopSelf();
}
public String signUpUser(String usernameText, String passwordText,
String emailText) {
String params = "username=" + usernameText + "&password="
+ passwordText + "&action=" + "signUpUser" + "&email="
+ emailText + "&";
String result = socketOperator.sendHttpRequest(params);
// This is the output of the datastream from the server ie. <data>
// (bunch of data...etc) </data>
return result;
}
public String addNewFriendRequest(String friendUsername) {
String params = "username=" + this.username + "&password="
+ this.password + "&action=" + "addNewFriend"
+ "&friendUserName=" + friendUsername + "&";
String result = socketOperator.sendHttpRequest(params);
return result;
}
public String sendFriendsReqsResponse(String approvedFriendNames,
String discardedFriendNames) {
String params = "username=" + this.username + "&password="
+ this.password + "&action=" + "responseOfFriendReqs"
+ "&approvedFriends=" + approvedFriendNames
+ "&discardedFriends=" + discardedFriendNames + "&";
String result = socketOperator.sendHttpRequest(params);
return result;
}
private void parseFriendInfo(String xml) {
try {
SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
sp.parse(new ByteArrayInputStream(xml.getBytes()), new HandlerXML(
MessagingService.this));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void parseMessageInfo(String xml) {
try {
SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
sp.parse(new ByteArrayInputStream(xml.getBytes()), new HandlerXML(
MessagingService.this));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void parseGroupInfo(String xml) {
try {
SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
sp.parse(new ByteArrayInputStream(xml.getBytes()), new HandlerXML(
MessagingService.this));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void parseGroupMessageInfo(String xml) {
try {
SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
sp.parse(new ByteArrayInputStream(xml.getBytes()), new HandlerXML(
MessagingService.this));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void updateData(InfoOfMessage[] messages, InfoOfFriend[] friends,
InfoOfGroup[] groups, InfoOfGroupMessage[] groupMessages,
InfoOfFriend[] unApprovedFriends, String userKey) {
this.setUserKey(userKey);
// FriendController.
IndividualMessageController.setMessagesInfo(messages);
// Log.i("MESSAGEIMSERVICE","messages.length="+messages.length);
GroupMessageController.setMessagesInfo(groupMessages);
int i = 0;
while (i < messages.length) {
messageReceived(messages[i].userid, messages[i].messagetext);
i++;
}
int j = 0;
while (j < groupMessages.length) {
groupMessageReceived(groupMessages[i].fromUser,
groupMessages[i].toGroupId, groupMessages[i].messageText);
j++;
}
// For individual chat
ControllerOfFriend.setFriendsInfo(friends);
ControllerOfFriend.setUnapprovedFriendsInfo(unApprovedFriends);
// For group chat
ControllerOfGroup.setGroupsInfo(groups);
// ControllerOfGroup.setUnapprovedGroupsInfo(unapprovedGroups);
}
// ************GENERAL METHODS FOR THE GROUP CHAT************
#Override
public String createNewGroup(String userName, String groupName)
throws UnsupportedEncodingException {
String params = "username=" + URLEncoder.encode(this.username, "UTF-8")
+ "&password=" + URLEncoder.encode(this.password, "UTF-8")
+ "&action=" + "createGroup" + "&groupName=" + groupName + "&";
String result = socketOperator.sendHttpRequest(params);
return result;
}
#Override
public String addGroupMember() {
// TODO Auto-generated method stub
return null;
}
#Override
public String sendGroupMessage(String toGroupId, String toGroupName,
String messageText) throws UnsupportedEncodingException {
String params = "username=" + URLEncoder.encode(this.username, "UTF-8")
+ "&password=" + URLEncoder.encode(this.password, "UTF-8")
+ "&toGroupId=" + URLEncoder.encode(toGroupId, "UTF-8")
+ "&messageText=" + URLEncoder.encode(messageText, "UTF-8")
+ "&action=" + URLEncoder.encode("sendGroupMessage", "UTF-8")
+ "&";
Log.i("PARAMS", params);
return socketOperator.sendHttpRequest(params);
}
#Override
public String getGroupName() {
// TODO Auto-generated method stub
return this.groupname;
}
}
Websocket Class
public class Socketer implements SocketerInterface
{
Global ipAddress = new Global();
private final String AUTHENTICATION_SERVER_ADDRESS = "http://" + ipAddress.getIpAddress() + ":PRIVATE"; // change to your WebAPI Address
private int listeningPort = 0;
private static final String HTTP_REQUEST_FAILED = null;
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket)
{
this.clientSocket = socket;
Socketer.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if (inputLine.equals("exit") == false) // as long as have noted exited yet, will continuing reading in
{
//appManager.messageReceived(inputLine);
}
else
{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
Socketer.this.sockets.remove(clientSocket.getInetAddress());
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ","");
}
}
}
public Socketer(Manager appManager) {
}
public String sendHttpRequest(String params)
{
URL url;
String result = new String();
try
{
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
// This is the output of the datastream from the server ie. <data> (bunch of data...etc) </data>
return result;
}
public int startListening(int portNo)
{
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
//e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
//e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket", "Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening()
{
this.listening = false;
}
public void exit()
{
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator.hasNext();)
{
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e)
{
}
}
sockets.clear();
this.stopListening();
}
public int getListeningPort() {
return this.listeningPort;
}
}

how to parse two lines of text and image in android

I have a feed I'm parsing and wondering how to parse two lines of information and an image. I can successfully parse one line of text but haven't figured out how to pull image from it and second line of text i want. Here is a picture of what i want to accomplish
here is the code for my parser
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("Trey's Blog::PullFeedParser", e.getMessage(), e);
throw new RuntimeException(e);
}
return messages;
}
}
my list activity
public class MessageList extends ListActivity {
private List<Message> messages;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
loadFeed(ParserType.XML_PULL);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent viewMessage = new Intent(Intent.ACTION_VIEW,
Uri.parse(messages.get(position).getLink().toExternalForm()));
this.startActivity(viewMessage);
}
private void loadFeed(ParserType type){
try{
Log.i("Trey's Blog", "ParserType="+type.name());
FeedParser parser = FeedParserFactory.getParser(type);
long start = System.currentTimeMillis();
messages = parser.parse();
long duration = System.currentTimeMillis() - start;
Log.i("Trey's Blog", "Parser duration=" + duration);
String xml = writeXml();
Log.i("Trey's Blog", xml);
List<String> titles = new ArrayList<String>(messages.size());
for (Message msg : messages){
titles.add(msg.getTitle());
}
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(this, R.layout.row,titles);
this.setListAdapter(adapter);
} catch (Throwable t){
Log.e("Trey's Blog",t.getMessage(),t);
}
}
private String writeXml(){
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", true);
serializer.startTag("", "messages");
serializer.attribute("", "number", String.valueOf(messages.size()));
for (Message msg: messages){
serializer.startTag("", "message");
serializer.attribute("", "date", msg.getDate());
serializer.startTag("", "title");
serializer.text(msg.getTitle());
serializer.endTag("", "title");
serializer.startTag("", "url");
serializer.text(msg.getLink().toExternalForm());
serializer.endTag("", "url");
serializer.startTag("", "body");
serializer.text(msg.getDescription());
serializer.endTag("", "body");
serializer.endTag("", "message");
}
serializer.endTag("", "messages");
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
my feed parser
public abstract class FeedParserFactory {
static String feedUrl = "http://treymorgan.net/feed";
public static FeedParser getParser(){
return getParser(ParserType.ANDROID_SAX);
}
public static FeedParser getParser(ParserType type){
switch (type){
case SAX:
return new SaxFeedParser(feedUrl);
case DOM:
return new DomFeedParser(feedUrl);
case ANDROID_SAX:
return new AndroidSaxFeedParser(feedUrl);
case XML_PULL:
return new XmlPullFeedParser(feedUrl);
default: return null;
}
}
}
and message activity
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;
public String getTitle() {
return title;
}
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;
return copy;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Title: ");
sb.append(title);
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;
return true;
}
public int compareTo(Message another) {
if (another == null) return 1;
// sort descending, most recent first
return another.date.compareTo(date);
}
}
I have been researching this for a while and havn't found anything that works on this. Any information anyone can give would be greatly appreciated. Pretty new to parsing so trying to learn this as i go. Thanks again.
Found a great Tutorial to help me achive the view i wanted to do and here is the link for it.
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
Hope this will help someone
You're using the ArrayAdapter this adapts an array of strings and shows one string on each list item.
You'll need to:
create a custom adapter
extend BaseAdapter
pass it a custom layout that represents one list item
pass it your List of Message's
in the getView() method retrieve one Message and set the title description and image
This is your culprit code:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.row, titles);
this.setListAdapter(adapter);

Taking data from rss feed using xml and then storing in an ArrayList

I am making an android application to get data from an rss feed https://spreadsheets.google.com/feeds/list/0AgSdFM6D0vX4dE5iQ0FfMGVWWGpieDZJY2lHX3I1S3c/od6/private/full
Can anyone please suggest an idea to take values gsx:brand from the xml and store it in an Arraylist
This is an example what I had done, you can look at this and work accordingly,
MainRSSDemo.java
public class MainRSSDemo extends Activity {
private List<Message> messages;
static String feedUrl = "http://rss.news.yahoo.com/rss/terrorism";
static final String RSS = "rss";
static final String CHANNEL = "channel";
static final String ITEM = "item";
static final String PUB_DATE = "pubDate";
static final String DESCRIPTION = "description";
static final String LINK = "link";
static final String TITLE = "title";
static final String URL = "url";
static final String MEDIA = "content";
private InputStream is;
private URL feed_Url = null;
private ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv =(ListView)findViewById(R.id.ListView01);
try {
feed_Url = new URL(feedUrl);
is = feed_Url.openConnection().getInputStream();
messages = parse();
is.close();
} catch (Exception e) {
Log.i("err", e.toString());
e.printStackTrace();
}
final List<String> titles = new ArrayList<String>(messages.size());
for (Message msg : messages){
titles.add(msg.getTitle());
}
lv.setAdapter(new ArrayAdapter<String>(this,R.layout.row,titles));
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getBaseContext(),titles.get(position), Toast.LENGTH_LONG).show();
}
});
}
public List<Message> parse() {
List<Message> messages = null;
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(is, 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)) {
String parse = parser.nextText().toString();
if (parse.contains("</a>")) {
parse = parse.substring(parse.indexOf("</a>") + 4, parse.lastIndexOf("</p>"));
currentMessage.setDescription(parse.toString());
} else {
currentMessage.setDescription(parse);
}
} else if (name.equalsIgnoreCase(PUB_DATE)) {
currentMessage.setDate(parser.nextText());
} else if (name.equalsIgnoreCase(TITLE)) {
currentMessage.setTitle(parser.nextText());
} else if (name.equalsIgnoreCase(MEDIA)) {
currentMessage.setImageUrl(parser.getAttributeValue(0));
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;
}
}
Message.java
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 image_url;
public void setImageUrl(String ImageUrl) {
image_url = ImageUrl;
}
public String getImageUrl() {
return image_url;
}
public String getTitle() {
return title;
}
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;
return copy;
}
public int compareTo(Message another) {
if (another == null)
return 1;
// sort descending, most recent first
return another.date.compareTo(date);
}
}

How to Build a RSS reader for Android?

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;
}
}

Categories

Resources