Intent filter does not unregistered programatically - Java for Android App Development

I have been trying to implement the broadcast receiver programatically , but my unregister method is not working or the app is working even if it in killed state .What i'm trying to accomplish is to display a test message ,when a sms receives ,,i have two buttons in app,register and unregister .If the user presses register ,no matter whether the app is running foreground or background the app should display the toast message,but if i press unregister the app should not invoke toast message .The code is
Code:
package gates.apps.automaticmessageresponder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
SmsReceiver broadcastReceiver=new SmsReceiver();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void register(View view){
this.registerReceiver(broadcastReceiver, new IntentFilter(
"android.provider.Telephony.SMS_RECEIVED"));
Log.e("register","pressed");
}
public void unRegister(View view){
this.unregisterReceiver(broadcastReceiver);
Log.e("unregister","pressed");
}
@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;
}
}
and another class is
Code:
package gates.apps.automaticmessageresponder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class SmsReceiver extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
// Show alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + message, duration);
toast.show();
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
}
i have not modified the manifest ,except adding sms recieve permission
But the problem with above code is ,even i don't press register it's getting invoked and even if i press unregister button ,it's not stopping

Dude you haven't added a listener for on click(unless you have specified register in layout for button). Nor can I see the button defined. Plus your toast message falls in try catch block. So look for clues in that. I think it'll work once you correct the code. I'll help more if its possible.
Please give a thanks if you think this post helped you!
Sent from my Nexus 4 using XDA Premium 4 Mobile App .

Related

[Q] simple timer

Whats the easiest way to use a timer? I just want a simple timer to use as a countdown.
Thanks in advance
Here's a very basic countdown timer. You could also do it with a loop i guess, depending on what you want to do with it.
Code:
new CountdownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
source - http://developer.android.com/reference/android/os/CountDownTimer.html
It's better do not use the very simple timer. It's better to run Async or Runnable thread, but if you want timer, you can also use TimerTask.
Code:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
....
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTime(this), 1, 1000);
}
private class MyTime extends TimerTask {
DateFormat format = SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM, Locale.getDefault());
public MyTime(Context ctx) {
// create internal instance
Context ctx;
}
@Override
public void run() {
currentTime = new Date();
// output something
Toast.makeText(ctx, "Time = " + format.format(currentTime), Toast.LENGTH_LONG).show();
}
}

[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!

Android App - Java: Adding to an arrayList then updating a ListView

I have coded this android app which produces a listView containing songs which are streamed from the internet, and the user can play them by clicking them using the mediaPlayer.
What i am having trouble with is allowing the user to add a song to the arrayList that populates the ListView within MainActivity.java. I have used the settings page to add textboxes so the user can add their songs by inputting, Song Name, Artist and the Direct Link to the song. Though the code i have used for this doesn't work, it should add the Song Name, Artist and Direct Link into the array_list_music ArrayList, then update the ListView, or at least i think that is how it should be done, although after entering details and clicking the 'Add Song' button, and returning to the main page, the ListView does not that the newly added song.
I have shown my code below.
So if someone could help with this problem, that would be great, thanks.
MainActivity.java
Code:
package com.groupassignment.musicplayer;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.Toast;
public class MainActivity extends ListActivity implements OnPreparedListener, MediaController.MediaPlayerControl {
private static final String TAG = "AudioPlayer";
private ListView list;
public MainArrayAdapter adapter;
private MediaPlayer mediaPlayer;
private MediaController mediaController;
private String audioFile;
private Handler handler = new Handler();
ArrayList<String> array_list_music = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = getListView();
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaController = new MediaController(this);
//ArrayList<String> array_list_music = new ArrayList<String>();
//Used to add a song to the array list
array_list_music
.add("Jar of Hearts"
+ " ### "
+ "Christina Perri"
+ " ### "
+ "LINK");
array_list_music
.add("Save The World"
+ " ### "
+ "Swedish House Mafia feat. John Martin"
+ " ### "
+ "LINK");
array_list_music
.add("Bromance"
+ " ### "
+ "Avicii"
+ " ### "
+ "LINK");
adapter = new MainArrayAdapter(MainActivity.this, array_list_music);
setListAdapter(adapter);
//used to display toast and to play song using the URL, when clicking on a song
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Object item = getListView().getItemAtPosition(arg2);
String the_list_item = item.toString();
Toast.makeText(MainActivity.this, "You are now listening to: " + the_list_item, Toast.LENGTH_LONG).show();
String[] aux = the_list_item.split(" ### ");
String url_to_play = aux[2];
playAudio(url_to_play);//sends url from arraylist item to the playAudio method
}
});
}
//used to play audio using the android mediaPlayer
private void playAudio(String url_to_play) {
//stop & reset player
try {
mediaPlayer.stop();
mediaPlayer.reset();
} catch (Exception e) {
}
//set the url, prepare it, and then play it
try {
mediaPlayer.setDataSource(url_to_play);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
Log.e(TAG, "Could not open file " + url_to_play + ".", e);
}
}
@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 boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent i_settings = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(i_settings);
break;
}
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mediaController.show();
return false;
}
//used to hide media controller, stop the media player and to release the url.
@Override
protected void onStop() {
super.onStop();
mediaController.hide();
mediaPlayer.stop();
mediaPlayer.release();
}
@Override
public boolean canPause() {
return true;
}
@Override
public boolean canSeekBackward() {
return true;
}
@Override
public boolean canSeekForward() {
return true;
}
@Override
public int getBufferPercentage() {
return 0;
}
@Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
@Override
public int getDuration() {
return mediaPlayer.getDuration();
}
@Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
@Override
public void pause() {
mediaPlayer.pause();
}
@Override
public void seekTo(int arg0) {
mediaPlayer.seekTo(arg0);
}
@Override
public void start() {
mediaPlayer.start();
}
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "onPrepared");
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(list);
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
//------- what can you do from here -------
// implement your own media player with buttons since this one is not behaving "smart"..
// make next,previous buttons
// highlight the list item on click
// add your own server for playing music
// anything you want :)
}
MainArrayAdapter.java
Code:
package com.groupassignment.musicplayer;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.groupassignment.musicplayer.R;
public class MainArrayAdapter extends ArrayAdapter<String> implements ListAdapter {
private final Context context;
private ArrayList<String> data_array;
private List<DataSetObserver> observers = new LinkedList<DataSetObserver>();
public MainArrayAdapter(Context context, ArrayList<String> list_of_ids) {
super(context, R.layout.main_list_rowlayout, list_of_ids);
this.context = context;
this.data_array = list_of_ids;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.main_list_rowlayout, parent,
false);
TextView textView_main_row_song_name = (TextView) rowView
.findViewById(R.id.textView_main_row_song_name);
TextView textView_main_row_singer_name = (TextView) rowView
.findViewById(R.id.textView_main_row_singer_name);
try {
String[] aux = data_array.get(position).split(" ### ");
String song_name = aux[0];
String artist = aux[1];
String url = aux[2];
textView_main_row_song_name.setText(song_name);
textView_main_row_singer_name.setText(artist);
} catch (Exception e) {
// TODO: handle exception
}
return rowView;
}
public void setArray(ArrayList<String> data_array){
this.data_array = data_array;
for (DataSetObserver observer : observers){
observer.onChanged();
}
}
@Override
public void registerDataSetObserver(DataSetObserver dataSetObserver) {
((LinkedList) observers).addFirst(dataSetObserver);
}
@Override
public void unregisterDataSetObserver(DataSetObserver dataSetObserver) {
observers.remove(dataSetObserver);
}
}
SettingsActivity.java
Code:
package com.groupassignment.musicplayer;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import com.groupassignment.musicplayer.R;
public class SettingsActivity extends Activity {
public String str ="";
String songName;
String artist;
String directLink;
protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
songName = ((EditText)findViewById(R.id.editTextSongName)).toString();
artist = ((EditText)findViewById(R.id.editTextArtist)).toString();
directLink = ((EditText)findViewById(R.id.editTextDirectLink)).toString();
};
public void buttonAddSongClicked(View v)
{
addSong(songName, artist, directLink);
}
private void addSong(String artist, String songName, String directLink)
{
MainActivity main = new MainActivity();
main.array_list_music
.add( songName
+ " ### "
+ artist
+ " ### "
+ directLink);
main.adapter.notifyDataSetChanged();
main.adapter = new MainArrayAdapter(main, main.array_list_music);
}
}
The problem is that you create new instances of adapter each time, instead of updating the existing one. Easy way to solve your problem is to change attributes of array_list_music and adapter to public static in your MainActivity and modify addSong inside SettingsActivity to:
Code:
private void addSong(String artist, String songName, String directLink)
{
MainActivity.array_list_music
.add( songName
+ " ### "
+ artist
+ " ### "
+ directLink);
MainActivity.adapter.notifyDataSetChanged();
}

Data That is Fetched From The Web Server Are Appending

I have this search function for my app that fetches data from web server using json, everything works completely except that everytime I search something, the data keeps on appending on my listview. For example if I search for a data with an id number 7 then press search button, the data is fetched and placed on the listview which what I want, but then if I search again the id number 7, there are now 2 instances of data with an id number of 7 in the listview. What I want is to refresh the listview for every search so that the only data that will appear on the listview is the current searched data.
MainActivity.java
Code:
package learn2crack.listview;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.EditText;
import learn2crack.listview.library.JSONParser;
public class MainActivity extends Activity {
ListView list;
TextView title;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//JSON Node Names
private static final String TAG_NEWS = "news";
private static final String TAG_TITLE = "title";
JSONArray android = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
title = (TextView)findViewById(R.id.title);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
String url = "http://localhost/abc-news/news.php?json-request-news=";
EditText id = (EditText)findViewById(R.id.search_text);
url = url + id.getText().toString();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_NEWS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String title = c.getString(TAG_TITLE);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_TITLE }, new int[] {
R.id.title });
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I attached an image below to support this problem I'm encountering.
Code:
oslist.add(map);
you're adding to the list that drives the adapter, add does what it implies ... maybe you should go though some basics, copy and pasting code sometimes wastes more time that you think it would save in the long run.
Hope that helps
Can you explain it more clearly here?
clonedaccnt said:
Can you explain it more clearly here?
Click to expand...
Click to collapse
erm, add = add ? sorry to come across like this but not sure what you are expecting... a,b,c .add(d) == a,b,c,d
What do I need to do to my code so that the newly searched data will not append on the previous data that is fetched?
clonedaccnt said:
What do I need to do to my code so that the newly searched data will not append on the previous data that is fetched?
Click to expand...
Click to collapse
I thought that was clear, don't "add" to what you have? Are you aware of what an array is ? or a list? and an adapter? cause I think I would start there, you just keep adding to the list that powers the adapter. If you dont want to add to it just don't, either clear it or replace it.
so just to be clear, a list or map has the method .clear() <--- that clears it of all data
I've already solve the problem earlier, I was going to post that I've already solve it but found out that you've already replied on the thread, sorry. About the problem, yes I too used the .clear() of the ArrayList to clear the array before adding a new one, it's my first time to create an activity that pass the data on the same activity, I'm used to passing the data from one activity to another so I don't have a chance to encounter this kind of problem.
Anyways thanks for helping I will not have accomplished this without your help.

[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