How can I add notifications to my news App ANDROID? - java

I am working on a android news app which gets news from google news rss feed. I am currently getting news and showing it to the user in my app. But I want to show notification to the user when new news appears on google rss. I have no idea how to do it as I am new to android and could not find anything relevant on google. Thank you.
Here is my code I have done so far
internal static List<FeedItem> GetFeedItems(string url)
{
List<FeedItem> feedItemsList = new List<FeedItem>();
try
{
HttpClient wc = new HttpClient();
var html = wc.GetStringAsync(new Uri(url)).Result;
XElement xmlitems = XElement.Parse(html);
// We need to create a list of the elements
List<XElement> elements = xmlitems.Descendants("item").ToList();
// Now we're putting the informations that we got in our ListBox in the XAML code
// we have to use a foreach statment to be able to read all the elements
// Description , Link , Title are the attributes in the RSSItem class that I've already added
List<FeedItem> aux = new List<FeedItem>();
foreach (XElement rssItem in elements)
{
FeedItem rss = new FeedItem();
rss.Description = rssItem.Element("description").Value;
rss.Link = rssItem.Element("link").Value;
rss.Title = rssItem.Element("title").Value;
feedItemsList.Add(rss);
}
}
catch (Exception)
{
throw;
}
return feedItemsList;
}

Use parse's push notification,it's very easy to use and has great documents.
https://parse.com

go for push notification service. its the only way to get the notification .
follow this tutorial... http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

Notification manager is what you want here.
see this http://developer.android.com/guide/topics/ui/notifiers/notifications.html ?
A simple google search also shows tutorials for the same

Related

Pull data from different APIs

I have created a news app and I wanted to pull articles from the different APIs via newsapi.org that would show up in different activities. I created
So for example, Techcrunch and Reuters. I have similar code for each activity but i switched the API link since it needs to pull from either TechCrunch and Reuters individually. Instead, only one of the activities work and the other is blank.
If i place the same API link in both activities, it works flawlessly. Please help
private void parseJSON () {
String url = "http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=*";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray =response.getJSONArray("articles");
for (int i = 0; i< jsonArray.length(); i++){
JSONObject article = jsonArray.getJSONObject(i);
String authorName = article.getString("author");
String imageUrl = article.getString("urlToImage");
String published = article.getString("publishedAt");
String description = article.getString("content");
String headline = article.getString("title");
mNewsList.add(new newsItem(imageUrl, authorName, published,description, headline ));
}
To get articles from a particular source use this URL :
https://newsapi.org/v2/top-headlines?sources=abc-news&apiKey="yourkey"
In you blank activity, do some break points and check network call returns success data or error. If network data success, then check your json parsing code to see it parses correctly.
You may try network logging interceptor to see what things are happening to your HTTP network calls.

Creating monitored items using ua-java

I'm currently working with the OPC UA Foundation Java Stack, without any additional SDK's.
I am unable to implement subscriptions with monitored items and to get the change notifications via the publish response. I am new to Java, any help regarding this would be really helpful. Thank you.
This is C#, not Java but you should be able to translate it. I hope it helps.
if (this.subscription == null)
{
this.subscription = new Opc.Ua.Client.Subscription(this.session.DefaultSubscription)
{
PublishingInterval = this.config.ReportingInterval,
TimestampsToReturn = TimestampsToReturn.Both
};
this.session.AddSubscription(subscription);
subscription.Create();
}
item = new MonitoredItem(subscription.DefaultItem)
{
StartNodeId = new NodeId(property.Identifier, this.config.NamespaceId),
SamplingInterval = this.config.SamplingInterval,
QueueSize = this.config.QueueSize,
};
subscription.AddItem(item);
subscription.ApplyChanges()

Jsoup code that works for Eclipse but not Android Studio (httpurlconnectionimpl)

I am working on a small app for myself and I just don't understand why my code is working in Eclipse but not on my phone using Android Studio.
public static ArrayList<Link> getLinksToChoose(String searchUrl) {
ArrayList<Link> linkList = new ArrayList<Link>();
try {
System.out.println(searchUrl);
Document doc = Jsoup.connect(searchUrl).timeout(3000).userAgent("Chrome").get();
Elements links = doc.select("tr");
links.remove(0);
Elements newLinks = new Elements();
for(Element link : links) {
Link newLink = new Link(getURL(link),getName(link),getLang(link));
linkList.add(newLink);
}
} catch(IOException e){
e.printStackTrace();
}
return linkList;
}
The problem is I can't even get the Document. I always get an httpurlconnectionimpl in the line where I try to get the html doc. I have read a bit about Jsoup in Android. Some people suggest using AsyncTask but it doesn't seem like that would solve my problem.
The loading of the content must happen outside the main thread, e.g. in an AsyncTask.

What is the best way to attach multiple images?

Several of my timeline item designs require multiple images, yet I am having difficulty attaching them all reliably. The timeline.insert function only seems to allow for one attachment and inserting attachments after the timeline item is inserted sometimes results in the images not being rendered.
I also tried using setAttachments on the timeline item itself but it didn't seem to actually upload the attachments when inserting the item. Using the code below I tend to get mixed results. Sometimes it works and other times it fails to render the image. There seems to be a correlation with how long I wait to view the notification after receiving it, if I view it too quickly it never fully renders.
Does anyone have any thoughts or suggestions on how I could overcome this or see anything I'm doing wrong?
//CardFactory.java - Create TimelineItem with attachment list
public static TimelineItem getConceptCard(String conceptImage) {
TimelineItem timelineItem = new TimelineItem();
timelineItem.setHtml("<article class=\"photo\">\n <img src=\"attachment:0\" width=\"100%\" height=\"100%\">\n <div class=\"photo-overlay\"/>\n <section>\n <p class=\"text-auto-size\">Test</p>\n </section>\n</article>\n");
List<Attachment> attachments = new ArrayList<Attachment>();
Attachment img1 = new Attachment();
img1.setId("backImage");
img1.setContentType("image/jpeg");
img1.setContentUrl(WebUtil.buildStaticImgUrl("cardconcepts/" + conceptImage + ".JPG"));
attachments.add(img1);
timelineItem.setAttachments(attachments);
timelineItem.setNotification(new NotificationConfig().setLevel("DEFAULT"));
return timelineItem;
}
//MainServlet.java - Send TimelineItem on button press
} else if (req.getParameter("operation").equals("insertConceptCard")) {
TimelineItem timelineItem = CardFactory.getConceptCard(req.getParameter("conceptCard"));
MirrorClient.insertTimelineCard(credential, timelineItem);
//MirrorClient.java - Insert TimelineItem with multiple attachments
public static void insertTimelineCard(Credential credential, TimelineItem item) throws IOException {
Mirror.Timeline timeline = getMirror(credential).timeline();
TimelineItem timelineItem = timeline.insert(item).execute();
for(Attachment TAttach : item.getAttachments()){
InputStreamContent mediaContent = new InputStreamContent(TAttach.getContentType(), new URL(TAttach.getContentUrl()).openStream());
timeline.attachments().insert(timelineItem.getId(), mediaContent).execute();
}
I am not sure if it is possible given your requirements, but if the attachments are public images, you don't actually need to attach them. You can use the img tag with a normal http URL. My experience has been that these get fetched fairly quickly, are cached if you use them frequently, and render correctly even if they don't render immediately.
(Even if your requirements need to keep these more private, you may wish to use standard image fetching with some kind of nonce instead of trying to attach them. I realize this doesn't quite answer your question, but it may be a useful workaround.)

how to post in user's Streams using google plus api in java

I want to share some information in google plus wall from my application.and I am trying for moment.insert, But getting 400 error . Can somebody help me
#Override
public JSONObject getGooglePlusAddUseractivities(Object token) {
Token accessToken = (Token) token;
OAuthService service = createOAuthServiceForGooglePlus();
OAuthRequest request = new OAuthRequest(Method.POST,"https://www.googleapis.com/plus/v1/people/me/moments/vault");
request.addQuerystringParameter("alt", "json");
service.signRequest(accessToken, request);
JSONObject object=new JSONObject();
try {
object.put("kind","plus#moment");
object.put("type","http://schemas.google.com/AddActivity");
JSONObject obj1=new JSONObject();
obj1.put("kind", "plus#itemScope");
obj1.put("url","https://plus.google.com/me");
obj1.put("description","Sign up now to claim and redeem your credits while shopping! ");
obj1.put("image","http://invite.png");
obj1.put("contentUrl", "www.abcd.com");
obj1.put("thumbnailUrl", "http://logo1_favicon.png");
object.putOpt("target", obj1);;
}catch(Exception ex) {
ex.printStackTrace();
}
request.addPayload(object.toString());
request.addHeader("Content-Type", "application/json");
System.out.println("request : "+request.getBodyContents());
Response response = request.send();
String responseBody = response.getBody();
JSONObject googleJSON = null;
try {
googleJSON = new JSONObject(responseBody);
}
catch (JSONException e) {
System.out.println("can not create JSON Object");
}
getting 400 error ?? anyone can tell me..... where am wrong ..!!`
It isn't clear from the documentation, but you can't provide both the target.url and most other target metadata. This is currently opened as bug 485 in the issue tracking system - please go there and star the issue to make sure they properly prioritize a fix.
If you remove the target.url value and add a target.id value, it should work.
(As an aside, this does not post in the user's stream, but will post an App Activity in their app moment vault. They must manually share the activity if they choose.)
At this time, it is not possible to programmatically write to a user's Stream. As a developer, you have two options:
Write an AppActivity (formerly known as a Moment), which writes information to Google, but not to a Google+ Stream. These activities are visible at plus.google.com/apps, and will be used by Google in additional ways over time.
Create an Interactive Post Share button, which a user must initiate. However, you can pre-fill both the text of the post and up to 10 intended recipients. The user can make changes if they want and then perform the actual share. You can learn more at https://developers.google.com/+/web/share/interactive or by watching this Google+ Developers Live episode: http://www.youtube.com/watch?v=U4Iw28jWtAY.

Categories

Resources