[App]Notification notified on Emulator but not visible on Phone - Java for Android App Development

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

Related

ProgressDialog don't appear

Hy please help me!!
My full code:
Code:
package com.android.skiptvad;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.LightingColorFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.skiptvad.*;
public class Login extends Activity {
private static final int DIALOG_LOADING = 0;
/** Called when the activity is first created. */
TextView tvuser;
String sessionid;
ProgressDialog pd = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
tvuser = (TextView) findViewById(R.id.tvuser);
TextView tvpw = (TextView) findViewById(R.id.tvpw);
final EditText etuser = (EditText) findViewById(R.id.etuser);
final EditText etpw = (EditText) findViewById(R.id.etpw);
Button btlogin = (Button)findViewById(R.id.btlogin);
btlogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (etuser.getText() != null && etpw.getText()!= null)
{
pd = ProgressDialog.show(Login.this,"","Loading. Please wait...", true);
pd.show();
Thread t = new Thread() {
public void run(){
download(etuser.getText().toString(), md5(etpw.getText().toString()));
pd.dismiss();
}
};
t.run();
}
}
});
}
public void download (final String user, final String pw)
{
try{
HttpClient client = new DefaultHttpClient();
String postURL = "http://surfkid.redio.de/login";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", user));
params.add(new BasicNameValuePair("password", pw));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
final JSONObject jObject = new JSONObject(EntityUtils.toString(resEntity));
JSONObject menuObject = jObject.getJSONObject("responseData");
if (jObject.getInt("responseStatus")== 200 && jObject.get("responseDetails")!= null)
{
sessionid = menuObject.getString("session_id");
//dismissDialog(DIALOG_LOADING);
// pd.dismiss();
}
else
{
//dismissDialog(DIALOG_LOADING);
if (jObject.getInt("responseStatus")== 500)
{
throw new Exception("Server Error");
}
else if (jObject.getInt("responseStatus")== 400)
{
throw new Exception("Wrong User/Password");
}
else
{
throw new Exception();
}
}
//pd.dismiss();
} catch (Exception e) {
//dismissDialog(DIALOG_LOADING);
Toast toast ;
toast = Toast.makeText(getApplicationContext(), e.getMessage(), 500);
toast.show();
}
}
private String md5(String in) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
digest.reset();
digest.update(in.getBytes());
byte[] a = digest.digest();
int len = a.length;
StringBuilder sb = new StringBuilder(len << 1);
for (int i = 0; i < len; i++) {
sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
sb.append(Character.forDigit(a[i] & 0x0f, 16));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
return null;
}
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case DIALOG_LOADING:
dialog = new ProgressDialog(this);
((ProgressDialog) dialog).setMessage("Loading, please wait...");
break;
}
return dialog;
}
}
My Problem is that the ProgressDialog don't appear.
Please help!!

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

Exception in Using LocationClient with a service

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

How do I change text in card views list?

I'm trying to update the text in my card view. I cannot figure out how to do it. I posted the code of my recyclerAdapter class below.
When a user clicks a card view it should update the text on the card view with a specified time.
Code:
package com.teamtreehouse.oslist;
import java.util.ArrayList;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.net.Uri;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import java.util.Calendar;
import android.content.Intent;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class RecyclerAdapter extends RecyclerView.Adapter<FaucetHolder>
{
private ArrayList<Faucet> faucets;
private Context context;
private SharedPreferences sharedPref;
private String dateFormat = "h:mm a";
public RecyclerAdapter (ArrayList<Faucet> faucetsI,Context context) {
this.faucets = faucetsI;
this.context=context;
}
@Override
public FaucetHolder onCreateViewHolder(ViewGroup viewGroup, int i)
{
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view,viewGroup,false);
FaucetHolder f = new FaucetHolder(v);
return f;
}
@Override
public void onBindViewHolder(FaucetHolder f, int k)
{
final Faucet faucet = faucets.get(k);
f.titleText.setText(faucet.getName());
f.titleText.setOnClickListener(new View.OnClickListener() {
public void onClick(View btn) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(faucet.getLink()));
setRenewal(faucet);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount()
{
return faucets.size();
}
private void setRenewal(Faucet g) {
sharedPref = context.getSharedPreferences("myPref",0);
SharedPreferences.Editor edit = sharedPref.edit();
Calendar c = Calendar.getInstance();
long current = c.getTimeInMillis();
long future = current + g.getLength();
c.setTimeInMillis(future);
SimpleDateFormat df = new SimpleDateFormat(dateFormat,Locale.US);
String date = df.format(c.getTime());
edit.putString(g.getSPName(),date);
}
private void updateText(FaucetHolder f, Faucet g) {
sharedPref = context.getSharedPreferences("myPref",0);
String updatedTime = sharedPref.getString(g.getSPName(), null);
f.timeText.setText(updatedTime);
}
}
The full error text would be helpful. If you haven't done it before you can quickly check if something is wrong with your views in the adapter bei commenting them out.
Bump
Sent from my LG-F350K using Tapatalk

Custom List View Open New Activities

Hey everyone. Here is my code below. I have everything working. Got it to display the pictures and text in a list view. Only issue is that I want to be able to click on one of the list items and have it open an activity. When I added that part in, I get an error that states,
"Error44, 45) error: no suitable constructor found for Intent(<anonymous OnItemClickListener>,Class)
constructor Intent.Intent(String,Uri) is not applicable
(argument mismatch; <anonymous OnItemClickListener> cannot be converted to String)
constructor Intent.Intent(Context,Class<?>) is not applicable
(argument mismatch; <anonymous OnItemClickListener> cannot be converted to Context)"
Here is my code:
Code:
package com.example.matt.nootropicahandbook;
import android.net.Uri;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
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;
import android.content.Intent;
public class Biohack extends Activity
{
ListView list;
String[] itemname = {"Nootropics", "Supplements", "Metabolic Enhancement","Stacks", "Neuro Stimulation", "Diet", "Stay Away From",};
Integer[] imgid={R.drawable.piracetam1, R.drawable.piracetam2, R.drawable.piracetam3,
R.drawable.piracetam4, R.drawable.piracetam5, R.drawable.piracetam6, R.drawable.piracetam7,};
String[] classNames = {"Main", "Lifehack"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_biohack);
biohacksAdapter adapter=new biohacksAdapter(this, itemname, imgid, classNames);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
String openClass = classNames[position];
try{
Class selected = Class.forName("com.example.matt.nootropicahandbook."+openClass);
Intent selectedIntent = new Intent(this, selected);
startActivity(selectedIntent);
}catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
});
}
}
The error is on the line:
Code:
Intent selectedIntent = new Intent(this, selected);
And here is my adapter class for refrence
Code:
package com.example.matt.nootropicahandbook;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class biohacksAdapter extends ArrayAdapter<String>{
private final Activity context;
private final String[] itemname;
private final Integer[] imgid;
private final String[] classNames;
public biohacksAdapter(Activity context,String[] itemname, Integer[] imgid, String[] classNames) {
super(context,R.layout.custom_row, itemname);
this.context = context;
this.itemname = itemname;
this.imgid = imgid;
this.classNames = classNames;
}
public View getView(int position, View view, ViewGroup parent)
{
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.custom_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
TextView extratxt = (TextView) rowView.findViewById(R.id.textView1);
txtTitle.setText(itemname[position]);
imageView.setImageResource(imgid[position]);
extratxt.setText("Description "+itemname[position]);
return rowView;
}
}
replace
Intent selectedIntent = new Intent(this, selected);
to
Intent selectedIntent = new Intent(Biohack.this, selected);
because ...

Categories

Resources