Exception in Using LocationClient with a service - Java for Android App Development

Hello there. I write a service that should work with LocationClient (Google Play Services). I have an IntentService and an AlarmReceiver (to get location periodically). I have an exception that I cannot catch. Please help!
AlarmReceiver.java
Code:
package com.afusionlocation;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
public class AlarmReceiver extends BroadcastReceiver implements GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,LocationListener {
private LocationClient locationclient;
private LocationRequest locationrequest;
private Intent mIntentService;
private PendingIntent mPendingIntent;
@Override
public void onReceive(Context context, Intent intent) {
mIntentService = new Intent(context,MyLocationService.class);
mPendingIntent = PendingIntent.getService(context, 1, mIntentService, 0);
int resp = -1;
try{
resp = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
}
catch (Exception ex)
{
Log.d("Error","onReceive(): exception: " +ex.toString());
}
if(resp == ConnectionResult.SUCCESS){
locationclient = new LocationClient(context,this,this);
locationclient.connect();
}
else{
Log.e("Error","Google Play Service Error: resp="+resp);
}
}
@Override
public void onLocationChanged(Location arg0) {
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
}
@Override
public void onConnected(Bundle arg0) {
locationrequest = LocationRequest.create();
locationrequest.setInterval(10000);
try{
locationclient.requestLocationUpdates(locationrequest, mPendingIntent); //HERE EXCEPTION that I cannot catch
}
catch(Exception ex)
{
Log.e("Error","Exception: "+ex.toString());
}
}
@Override
public void onDisconnected() {
}
}
MyLocationService.java
Code:
package com.afusionlocation;
import com.google.android.gms.location.LocationClient;
import android.app.IntentService;
import android.content.Intent;
import android.location.Location;
import android.util.Log;
public class MyLocationService extends IntentService {
public MyLocationService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
Location location = intent.getParcelableExtra(LocationClient.KEY_LOCATION_CHANGED);
if(location !=null){
Log.i("Error", "onHandleIntent " + location.getLatitude() + "," + location.getLongitude());
}
}
}

Related

Problems with RSS Reader

Hi Guys,
a friend of mine told me to ask the question here, I hope this is the right category.
I startet an android application project with an integrated RSS Reader.
I programmed it with a tutorial from a website ( I can't post the link because I'm new, sorry).
It went all good, no Errors or something like that. When I installed the .apk file on my device (Samsung S3, with standard ROM) and started it
the Rss news won't be shown. :-/
These are the files for my Rss Reader:
RssReader.java
Code:
package com.android.simplerssreader.util;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import com.android.simplerssreader.data.RssItem;
public class RssReader {
private String rssUrl;
public RssReader(String rssUrl){
this.rssUrl = rssUrl;
}
public List<RssItem> getItems() throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
RssParseHandler handler = new RssParseHandler();
saxParser.parse (rssUrl, handler);
return handler.getItems();
}
}
RssParseHandler
Code:
package com.android.simplerssreader.util;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.android.simplerssreader.data.RssItem;
public class RssParseHandler extends DefaultHandler {
private List<RssItem> rssItems;
private RssItem currentItem;
private boolean parsingTitle;
private boolean parsingLink;
public RssParseHandler(){
rssItems = new ArrayList<RssItem>();
}
public List<RssItem> getItems(){
return rssItems;
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException{
if ("content-item".equals(qName)){
currentItem = new RssItem();
} else if ("title".equals(qName)){
parsingTitle=true;
} else if ("url".equals(qName)){
parsingLink = true;
}
};
@Override
public void endElement (String uri, String localName, String qName)
throws SAXException{
if ("content-item".equals(qName)){
rssItems.add(currentItem);
currentItem = null;
} else if ("title".equals(qName)){
parsingTitle = false;
} else if ("url".equals(qName)){
parsingLink = false;
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (parsingTitle) {
if (currentItem !=null)
currentItem.setTitle(new String(ch,start, length));
} else if (parsingLink) {
if(currentItem !=null){
currentItem.setLink(new String(ch, start, length));
parsingLink = false;
}
}
}
}
ListListener
Code:
package com.example.brueckenkopf_onlineapp;
import java.util.List;
import com.android.simplerssreader.data.*;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
public class ListListener implements OnItemClickListener {
List<RssItem> listItems;
Activity activity;
public ListListener(List<RssItem> listItems, Activity activity) {
this.listItems = listItems;
this.activity = activity;
}
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
Intent i = new Intent (Intent.ACTION_VIEW);
i.setData(Uri.parse(listItems.get(pos).getLink()));
activity.startActivity(i);
}
}
RssItem
Code:
package com.android.simplerssreader.data;
public class RssItem {
private String title;
private String link;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
MainActivity
Code:
package com.example.brueckenkopf_onlineapp;
import com.android.simplerssreader.data.RssItem;
import com.android.simplerssreader.util.RssReader;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
RssReader rssReader =new RssReader("Here comes the RSS Link, which I also can't post here");
ListView Items = (ListView)findViewById(R.id.listView1);
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(this,android.R.layout.simple_list_item_1,rssReader.getItems());
Items.setAdapter(adapter);
Items.setOnItemClickListener(new ListListener(rssReader.getItems(), this)); } catch (Exception e){
Log.e("SimpleRssReader", e.getMessage());
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
The LogCat says it cannot open the RSS Link. But the Link is not wrong (I also tried it with an RSS Link of another website). Both don't work.
I hope you can help me

[Q] JDBC in android fragment not working

I am working on an android application that modifies an external MySQL database. I know I can use an intermediate PHP/JSON service to do it, but I rather use JBDC because connection is faster and my project teachers want me to do it this way.
As it's my first app, I started with a simple button and an action(create a database), which actually works (in fact two buttons, the first one doesn't work on skd higher than 9, AsyncTask has to be used in them):
Code:
package com.example.prova;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.sql.*;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button1 = (Button) findViewById(R.id.btconn1);
final Button button2 = (Button) findViewById(R.id.btconn2);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try
{
String URL = "jdbc:mysql://" + "192.168.1.200" + ":" + "3306";
String USER = "app";
String PASS = "android";
Toast.makeText(getApplicationContext(),
"Conectando a servidor MySQL",
Toast.LENGTH_SHORT).show();
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(URL, USER, PASS);
Toast.makeText(getApplicationContext(),
"Conectado Servidor MySQL",
Toast.LENGTH_LONG).show();
Statement stmt = conn.createStatement();
String SQL = "CREATE DATABASE SYNC";
stmt.executeUpdate(SQL);
conn.close();
}
catch (ClassNotFoundException e)
{
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
catch (SQLException e)
{
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new LED13ON().execute();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class LED13ON extends AsyncTask<Void, Integer, Void> {
@Override
protected void onPostExecute(Void result){
SystemClock.sleep(2000);
}
@Override
protected void onPreExecute(){
SystemClock.sleep(2100);
}
@Override
protected void onProgressUpdate(Integer... values){
SystemClock.sleep(100);
}
@Override
protected Void doInBackground(Void... arg0){
try
{
String URL = "jdbc:mysql://" + "192.168.1.200" + ":" + "3306";
String USER = "app";
String PASS = "android";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(URL, USER, PASS);
Statement stmt = conn.createStatement();
String SQL = "CREATE DATABASE aSYNC";
stmt.executeUpdate(SQL);
conn.close();
}
catch (ClassNotFoundException e)
{
}
catch (SQLException e)
{
}
catch (Exception e)
{
}
return null;
}
}
}
The problem is when I try to use fragments, eclipse returns no errors but JDBC code is not working (logcat gives me no errors too). I know that's only the JDBC code which is not working because it gets inside the LED13ON and makes the SystemClock.sleep(2000), because the button is marked for two seconds. This is the code I have for the fragment in a new class:
Code:
package com.example.smarthome;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Locale;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class Fragment_main extends Fragment {
public Fragment_main() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main,container, false);
Button btn = (Button) rootView.findViewById(R.id.btconn1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick (View v) {
new LED13ON().execute();
}
});
return rootView;
}
public class LED13ON extends AsyncTask<Void, Integer, Void> {
@Override
protected void onPostExecute(Void result){
SystemClock.sleep(2000);
}
@Override
protected void onPreExecute(){
SystemClock.sleep(2100);
}
@Override
protected void onProgressUpdate(Integer... values){
SystemClock.sleep(100);
}
@Override
protected Void doInBackground(Void... arg0){
try
{
String URL = "jdbc:mysql://" + "192.168.1.200" + ":" + "3306";
String USER = "app";
String PASS = "android";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(URL, USER, PASS);
Statement stmt = conn.createStatement();
String SQL = "CREATE DATABASE aSYNC";
stmt.executeUpdate(SQL);
conn.close();
}
catch (ClassNotFoundException e)
{
}
catch (SQLException e)
{
}
catch (Exception e)
{
}
return null;
}
}
}
So I don't understand why being the same code it's not working for the second app, having changed the setOnClickListener to work in the fragment. Can anyone help me? I would really like to use the swipe views for my app as I think it fits more the android Holo style.
Thank you for your time!
EDIT:
I found the solution to my problem:
I logged the exceptions, it gave me the error:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Click to expand...
Click to collapse
The solution was to add newInstance in the Class.forName:
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Click to expand...
Click to collapse
So that's all, now my app is working as I intended. Thanks for everything!

Load Image from RSS Enclosure tag???

Hello everyone.
I am trying to load the Images in an listview that the RSS provides me.
http://www.nutech.nl/rss is the rss i use.
i want to load the image in listview from these tags
<enclosure> </enclosure (
Code:
<enclosure url="http://media.nu.nl/m/m1nx89taa599_sqr256.jpg" length="None" type="image/jpeg"></enclosure>
)
Now i have tried several things i found on google but none worked or werent explaining enough.
Here is some of my main Codes
RSSreader.java
Code:
package com.thedutch.technews;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.os.StrictMode;
public class RSSReader {
DefaultHttpClient httpClient = new DefaultHttpClient();
public Document getRSSFromServer(String url) {
Document response = null;
response = getDomFromXMLString(getFeedFromServer(url));
return response;
}
private String getFeedFromServer(String url) {
String xml = null;
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
try {
HttpGet httpget =new HttpGet(url);
//HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpget);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (Exception e) {
e.printStackTrace();
}
return xml;
}
private Document getDomFromXMLString(String xml) {
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (Exception e) {
}
return doc;
}
public String getValue(Element item, String key) {
NodeList nodeList = item.getElementsByTagName(key);
return this.getElementValue(nodeList.item(0));
}
public final String getElementValue(Node node) {
Node child;
if (node != null) {
if (node.hasChildNodes()) {
for (child = node.getFirstChild(); child != null; child = child
.getNextSibling()) {
if (child.getNodeType() == Node.TEXT_NODE) {
return child.getNodeValue();
}
}
}
}
return "";
}
}
Nutech.java
Code:
package com.thedutch.technews;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.faizmalkani.floatingactionbutton.FloatingActionButton;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Nutech extends Fragment implements OnClickListener{
String key_items = "item";
String key_title = "title";
String key_description = "description";
String key_link = "link";
String key_date = "pubDate";
ListView lstPost = null;
List<HashMap<String, Object>> post_lists = new ArrayList<HashMap<String, Object>>();
List<String> lists = new ArrayList<String>();
ArrayAdapter<String> adapter23 = null;
RSSReader rssfeed = new RSSReader();
FloatingActionButton mFab;
public static Fragment newInstance(Context context) {
Nutech f = new Nutech();
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(
R.layout.activity_main4, container, false);
((MainActivity) getActivity())
.setActionBarTitle("Nutech");
mFab = (FloatingActionButton) view.findViewById(R.id.fabbutton);
mFab.setOnClickListener(this);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Appstatus.getInstance(getActivity()).isOnline()) {
lstPost = (ListView) getView().findViewById(R.id.lstPosts);
mFab = (FloatingActionButton) getView().findViewById(R.id.fabbutton);
mFab.listenTo(lstPost);
adapter23 = new ArrayAdapter<String>(getActivity(),
R.layout.feed_list_item, R.id.title, lists) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView txt1 = (TextView) view
.findViewById(R.id.title);
TextView txt2 = (TextView) view
.findViewById(R.id.desc);
TextView txt3 = (TextView) view
.findViewById(R.id.date);
HashMap<String, Object> data = post_lists.get(position);
txt1.setText(data.get(key_title).toString());
txt2.setText(data.get(key_description).toString());
txt3.setText(data.get(key_date).toString());
return view;
}
};
Document xmlFeed = rssfeed
.getRSSFromServer("http://www.nutech.nl/rss");
NodeList nodes = xmlFeed.getElementsByTagName("item");
for (int i = 0; i < nodes.getLength(); i++) {
Element item = (Element) nodes.item(i);
HashMap<String, Object> feed = new HashMap<String, Object>();
feed.put(key_title, rssfeed.getValue(item, key_title));
feed.put(key_description, rssfeed.getValue(item, key_description));
feed.put(key_link, rssfeed.getValue(item, key_link));
feed.put(key_date, rssfeed.getValue(item, key_date));
post_lists.add(feed);
lists.add(feed.get(key_title).toString());
}
lstPost.setAdapter(adapter23);
lstPost.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
if (Appstatus.getInstance(getActivity()).isOnline()) {
Document xmlFeed = rssfeed
.getRSSFromServer("http://www.nutech.nl/rss");
NodeList nodes = xmlFeed.getElementsByTagName("item");
Element item = (Element) nodes.item(position);
Intent indisplay = new Intent(getActivity(),PostViewActivity.class);
indisplay.putExtra("link", rssfeed.getValue(item, key_link));
startActivity(indisplay);
} else {
getActivity().setContentView(R.layout.activity_main3);
Thread background = new Thread() {
public void run() {
try {
sleep(5*1100);
getActivity().finish();
} catch (Exception e) {
}
}
};
background.start();
}
}
});
lstPost.setLongClickable(true);
lstPost.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
if (Appstatus.getInstance(getActivity()).isOnline()) {
Document xmlFeed = rssfeed
.getRSSFromServer("http://www.nutech.nl/rss");
NodeList nodes = xmlFeed.getElementsByTagName("item");
Element item = (Element) nodes.item(position);
final Intent wintent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse(rssfeed.getValue(item, key_link)));
startActivity(wintent);
return true;
} else {
getActivity().setContentView(R.layout.activity_main3);
Thread background = new Thread() {
public void run() {
try {
sleep(5*1100);
getActivity().finish();
} catch (Exception e) {
}
}
};
background.start();
}
return true;
}
});
} else {
getActivity().setContentView(R.layout.activity_main3);
Thread background = new Thread() {
public void run() {
try {
sleep(5*1100);
getActivity().finish();
} catch (Exception e) {
}
}
};
background.start();
}
}
public void fabClicked(View view) {
adapter23.notifyDataSetChanged();
}
@Override
public void onClick(View v) {
adapter23.notifyDataSetChanged();
this.adapter23.notifyDataSetChanged();
lstPost.invalidateViews();
lstPost.refreshDrawableState();
Toast.makeText(this.getActivity(),
"Refreshed Nutech News!", Toast.LENGTH_LONG).show();
}
public void hideFab(View view) {
mFab.hide(true);
//getActionBar().hide();
}
public void showFab(View view) {
mFab.hide(false);
//getActionBar().show();
}
}
MainActivity.java
Code:
package com.thedutch.technews;
import java.util.ArrayList;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.MapBuilder;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private EasyTracker easyTracker = null;
private Toolbar mToolbar;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private ListView mDrawerList;
private ArrayList<ListMenuModel> mListMenu;
private ListMenuAdapter mListMenuAdapter;
final String[] data ={"Nutech","Tweakers","Hardware Info"};
final String[] fragmentos ={
"com.thedutch.technews.Nutech",
"com.thedutch.technews.Tweakers",
"com.thedutch.technews.Hardwareinfo"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
easyTracker = EasyTracker.getInstance(MainActivity.this);
mToolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(mToolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mListMenu = new ArrayList<ListMenuModel>();
mListMenu.add(new ListMenuModel("Nutech", "Nutech", R.drawable.ic_nu));
mListMenu.add(new ListMenuModel("Tweakers", "Tweakers", R.drawable.ic_tweakers));
mListMenu.add(new ListMenuModel("Hardware Info", "Hardware Info", R.drawable.ic_hardwareinfo));
mListMenuAdapter = new ListMenuAdapter(getApplicationContext(),
mListMenu);
mDrawerList.setAdapter(mListMenuAdapter);
mDrawerList.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
mDrawerToggle.syncState();
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.content_frame, Fragment.instantiate(MainActivity.this, fragmentos[pos]));
tx.commit();
mDrawerList.setSelection(pos);
easyTracker.send(MapBuilder.createEvent("Nav Drawer",
"Opened Navigation Drawer", "Navigation Drawer", null).build());
mDrawerLayout.closeDrawer(mDrawerList);
}
});
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.content_frame,Fragment.instantiate(MainActivity.this, fragmentos[0]));
tx.commit();
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
mToolbar,
R.string.drawer_open,
R.string.drawer_close){
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
syncState();
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
mToolbar.setClickable(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.about:
Intent intent = new Intent(this, AboutActivity.class);
this.startActivity(intent);
easyTracker.send(MapBuilder.createEvent("AboutActivity",
"Entered About Page", "about", null).build());
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
@Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(Gravity.START|Gravity.LEFT)){
mDrawerLayout.closeDrawers();
return;
}
super.onBackPressed();
}
public void fabClicked(View view) {
Toast.makeText(this, "Refreshed.", Toast.LENGTH_LONG).show();
}
@Override
public void onStart() {
super.onStart();
EasyTracker.getInstance(this).activityStart(this);
}
@Override
public void onStop() {
super.onStop();
EasyTracker.getInstance(this).activityStop(this);
}
}
is there someone who could help me ?
thank you
After few months i still havent found a solution or idea.
anyone here has ?
Use a RSS parsing library
Use my AndroidWithoutStupid Java library. It is on GitHub. There is also an article about the usage on CodeProject.
Enclosure tag is usually used for mp3 files but it doesn't matter.
After getting the enclosure value using the MvNewsFeed class, you need to download it. Use MvAsyncDownload for that. Then, use BitmapFactory.decodeFile() or a similar method to display the image in an ImageView.
SpaceCaker said:
After few months i still havent found a solution or idea.
anyone here has ?
Click to expand...
Click to collapse

Radio app into a service

Hi I was looking for tutorials to make a radio app so I followed this one but the problem is that as soon as the app closes the music stops, how do I turn it into a service. Thanks
Code:
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class myMain extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("stream url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
@Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
benpaterson said:
Hi I was looking for tutorials to make a radio app so I followed this one but the problem is that as soon as the app closes the music stops, how do I turn it into a service. Thanks
Code:
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class myMain extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("stream url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
@Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
Click to expand...
Click to collapse
You'll have to learn about Android Service and extend that, instead of Activity.

[App]Notification notified on Emulator but not visible on Phone

Hi Everyone! I was working on an app, which needed to give a remainder on a certain time, by triggering a notification. The app seemed to work fine on the emulator. But, the notification never shows up on a real phone.
The service which sends the broadcast.
Code:
package com.example.tanmay.yourdiary;
import android.annotation.TargetApi;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* Created by Tanmay on 22-01-2016.
*/
public class MyService extends IntentService {
public MyService() {
super("com.example.tanmay.yourdiary");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final Context context = this;
final Intent i = new Intent("com.example.tanmay.yourdiary.MyReceiver");
i.setAction("com.example.tanmay.yourdiary.MyReceiver");
new Thread(new Runnable(){
public void run(){
while(true){
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String g="";
g=sdf.format(c.getTime());
Log.i("dd",g);
if(g.equals("05:23")){
Log.i("d3d",g);
LocalBroadcastManager.getInstance(context).sendBroadcast(i);
try {
Thread.sleep(24*60*60*1000);
stopSelf();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
protected void onHandleIntent(Intent intent) {
}
}
The receiver
Code:
package com.example.tanmay.yourdiary;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Log.i("dfdfg", "bc rec");
NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_launcher).setContentTitle("Reminder").setContentText("Time to write your thoughts!");
TaskStackBuilder taskstackbuilder = TaskStackBuilder.create(context);
taskstackbuilder.addParentStack(MainActivity.class);
Intent i = new Intent(context,Writing.class);
taskstackbuilder.addNextIntent(i);
PendingIntent ip = taskstackbuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(ip);
NotificationManager manager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1,builder.build());
}
}
Try this code to see if it works on your phone or not
Code:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext)
.setSmallIcon(R.drawable.ic_launcher).setContentTitle("Title").setContentText("Description text");
Intent resultIntent = new Intent(mContext, MainActivity.class);
resultIntent.putExtra(AN_ADITIONAL_EXTRA, "User clicked on the notification");
// Because clicking the notification opens a new ("special") activity, there's no need to create an artificial back stack.
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setAutoCancel(true);
// Sets an ID for the notification
int mNotificationId = 10; // give it an ID you recognize within your application
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
And in your MainActivity.class under onNewIntent / onCreate
if(getIntent.getExtras() != null){
if(intent.hasExtra(AN_ADITIONAL_EXTRA)){
// User clicked on the notification, do something
}
}

Categories

Resources