Android- listview, service mediaplayer, and boolean flags - android

I currently have a listview and when you click on an item it runs a service with a mediaplayer. If I click on another item in the listview the service that's running should stop and run the new service. I am using a boolean isRunning set to false and when the service is created it returns true. Then in the listview I call that flag in an if statement. However, its not exactly working. I think I may be doing this wrong. Any ideas?
This probably sounds confusing the way I described it so Here is the code to my listview and my service. I am only testing this on case 3 (so I press this item to start the service and then click on case 2 to see if it will stop it).
Listview class:
public class PlaylistActivity extends ListActivity{
private static final String TAG = PlaylistActivity.class.getSimpleName();
// Data to put in the ListAdapter
private String[] sdrPlaylistNames = new String[] {
"Best of June 2011", "Best of May 2011", "Dubstep",
"House", "Other"};
private ListAdapter sdrListAdapter;
Intent playbackServiceIntentBOJ, playbackServiceIntentBOM, playbackServiceIntentDUB;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlists_layout);
//fill the screen with the list adapter
playlistFillData();
playbackServiceIntentDUB = new Intent(this, DUBAudioService.class);
Log.d(TAG, "Made DUB Service Intent");
}
public void playlistFillData() {
//create and set up the Array adapter for the list view
ArrayAdapter sdrListAdapter = new ArrayAdapter(this, R.layout.list_item, sdrPlaylistNames);
setListAdapter(sdrListAdapter);
}
//set up the on list item Click
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//create a switch so that each list item is a different playlist
switch(position){
case 0:
Intent BOJintent = new Intent(this, BOJAudioActivity.class);
// Create the view using PlaylistGroup's LocalActivityManager
View view = PlaylistGroup.group.getLocalActivityManager()
.startActivity("show_city", BOJintent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
// Again, replace the view
PlaylistGroup.group.replaceView(view);
// playbackServiceIntentBOJ = new Intent(this, BOJAudioService.class);
Log.d(TAG, "Made BOJ Intent");
// startService(playbackServiceIntentBOJ);
Log.d(TAG, "started BOJ Service");
break;
case 1:
Intent BOMintent = new Intent(this, BOMAudioActivity.class);
// Create the view using PlaylistGroup's LocalActivityManager
View view2 = PlaylistGroup.group.getLocalActivityManager()
.startActivity("show_city", BOMintent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
// Again, replace the view
PlaylistGroup.group.replaceView(view2);
Log.d(TAG, "Replace view");
//getApplicationContext().stopService(playbackServiceIntentBOJ);
//playbackServiceIntentBOM = new Intent(this, BOJAudioService.class);
Log.d(TAG, "Made BOM Service Intent");
// startService(playbackServiceIntentBOM);
Log.d(TAG, "started BOM Service");
if(DUBAudioActivity.isRunningDUB = true){
stopService(playbackServiceIntentDUB);
Log.d(TAG, "stop service isRunningDUB");
}
//
break;
case 2:
Intent DUBIntent = new Intent (this, DUBAudioActivity.class);
View view3 = PlaylistGroup.group.getLocalActivityManager()
.startActivity("show_city", DUBIntent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
PlaylistGroup.group.replaceView(view3);
Log.d(TAG, "Replace view");
startService(playbackServiceIntentDUB);
Log.d(TAG, "started DUB service");
break;
}
}
}
Service Class:
public class DUBAudioService extends Service implements OnPreparedListener, OnCompletionListener{
Toast loadingMessage;
private static final String TAG = DUBAudioService.class.getSimpleName();
public static boolean isRunningDUB = false;
//to keep track of the playlist item
Vector<PlaylistFile> playlistItems;
MediaPlayer mediaPlayer;
String baseURL = "";
//keep track of which item from the vector we are on
int currentPlaylistltemNumber = 0;
public class DUBBackgroundAudioServiceBinder extends Binder {
DUBAudioService getService() {
return DUBAudioService.this;
}
}
private final IBinder basBinderDUB = new DUBBackgroundAudioServiceBinder();
#Override
public IBinder onBind(Intent intent) {
return basBinderDUB;
}
#Override
public void onCreate() {
Log.v("PLAYERSERVICE", "onCreate");
mediaPlayer = new MediaPlayer();
new MusicAsync().execute();
Log.d(TAG, "execute'd async");
mediaPlayer.setOnPreparedListener(this);
Log.d(TAG, "set on prepared listener");
mediaPlayer.setOnCompletionListener(this);
Log.d(TAG, "set on completion listener");
isRunningDUB = true;
Log.d(TAG, "isRunningRUB = true");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//if (!mediaPlayer.isPlaying()) {
// mediaPlayer.start();
//}
return START_STICKY;
}
class MusicAsync extends AsyncTask<Void,Void,Void>{
#Override
protected void onPreExecute(){
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
//create empty vector
playlistItems = new Vector<PlaylistFile>();
//HTTP client library
HttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet ("http://dl.dropbox.com/u/24535120/m3u%20playlist/DubstepPlaylist.m3u"); //i think you could add the m3u thing in here
Log.v("URI",getRequest.getURI().toString());
try {
HttpResponse httpResponse = httpClient.execute(getRequest);
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
// ERROR MESSAGE
Log.v("HTTP ERROR",httpResponse.getStatusLine().getReasonPhrase());
}
else {
InputStream inputStream = httpResponse.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
Log.v("PLAYLISTLINE","ORIG: " + line);
if (line.startsWith("#")) {
//Metadata
//Could do more with this but not fo now
} else if (line.length() > 0) {
String filePath = "";
if (line.startsWith("http://")) {
// Assume its a full URL
filePath = line;
} else {
//Assume it’s relative
filePath = getRequest.getURI().resolve(line).toString();
}
PlaylistFile playlistFile = new PlaylistFile(filePath);
playlistItems.add (playlistFile);
}
}
inputStream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e. printStackTrace();
}
currentPlaylistltemNumber = 0;
if (playlistItems.size() > 0)
{
String path = ((PlaylistFile)playlistItems.get(currentPlaylistltemNumber)).getFilePath();
try {
mediaPlayer.setDataSource(path);
mediaPlayer.prepareAsync();}
catch (IllegalArgumentException e)
{ e.printStackTrace();
}catch (IllegalStateException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();}
}
return null;
}
//
protected void onPostExecute(Void result){
//playButton. setEnabled (false);
}
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
Log.d(TAG, "music stopp'd");
}
//mediaPlayer.release();
Log.d(TAG, "onDestroy");
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub\
Log.d(TAG, "music is prepared and will start");
mediaPlayer.start();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
Log.d(TAG, "Song completed, next song");
mediaPlayer.stop();
mediaPlayer.reset();
if (playlistItems.size() > currentPlaylistltemNumber + 1) {
currentPlaylistltemNumber++;
String path =
((PlaylistFile)playlistItems.get(currentPlaylistltemNumber)).getFilePath();
try {
mediaPlayer.setDataSource(path);
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
e. printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class PlaylistFile {
String filePath;
public PlaylistFile(String _filePath) {
filePath = _filePath;
}
public void setFilePath(String _filePath) {
filePath = _filePath;
}
public String getFilePath() {
return filePath;
}
}
public void playSong(){
Log.d(TAG, "start'd");
mediaPlayer.start();
}
public void pauseSong(){
Log.d(TAG, "pause'd");
mediaPlayer.pause();
}
}

This gets pretty complicated but I used the following to see if my service was running:
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.example.MyService".equals(service.service.getClassName())) {
return true;
}
}
return false;
}
I added this in my listview class and put if statements in each case to see if it was running and if so would stop the service.
I also made my all of my binding conenctions public so that the listview class could access them and start them on click.
If anyone wants to further understand, etc message me.

let your app track the state, not your service.

Related

Why would a service's onUnbind method not execute on a call to unbindService from the only connected client in Android?

I am working on an application which will poll and record data from a remote device even when the application that launched it isn't in the foreground. In order to do this I created a service which is launched by my main app once the user has adjusted a few settings. Currently I am able to start the service from my app and pass configuration data to it through the intent. It is my understanding that onUnbind only runs when all clients have disconnected. I am only connecting a single client to the service so I would expect this method to fire as soon as I command my app to unbind.
Problem
After originally binding to the service, if I later try to unbind the onUnbind function doesn't execute. Similarly, if I try to bind to it again neither onBind nor onRebind execute. I've tried printing to the log and toaster notifications to indicate the respective functions are being called. I get no feedback in either case. This has me quite convinced there is something wrong with my interface to the service.
I'm sure these issues are related but I'm new to Android Services and have been unable to locate a section of the docs which explains the problem. Any direction as to what I'm doing wrong would be very helpful. Code is included below, thanks!
Activity Code:
public class MainActivity extends AppCompatActivity {
String TAG = "MainActivity";
Boolean isBound = false;
private static final int PICKFILE_RESULT_CODE = 1;
Button rec_button;
TextView dmr_fname;
TextView dmr_status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Remove this button...", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
rec_button = findViewById(R.id.rec_button);
rec_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Recorder started (not really)", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
doUnBind();
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
// Open settings activity
Intent myIntent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(myIntent);
return true;
}
else if (id == R.id.action_dmr) {
// TODO: Open a file dialog so user can select DMR to parse
Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
//fileintent.addCategory(Intent.CATEGORY_OPENABLE);
fileintent.setType("text/*");
try {
startActivityForResult(Intent.createChooser(fileintent, "Open CSV"), PICKFILE_RESULT_CODE);
} catch (ActivityNotFoundException e) {
Log.e("tag", "No activity can handle picking a file. Showing alternatives.");
}
return true;
}
else if (id == R.id.action_quitservice) {
try {
doUnBind();
} catch (Exception e) {
Log.e(TAG,"Error encountered unbinding from DMR service: "+e);
}
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
dmr_fname = findViewById(R.id.DMR_filename);
dmr_status = findViewById(R.id.DMR_status);
switch (requestCode) {
case PICKFILE_RESULT_CODE:
if (resultCode == RESULT_OK) {
String FilePath = data.getData().getPath();
// TODO: Add a function here to try two different file paths (one for SD, one internal, and return the proper one
// For now, just assume it's internal downloads
Log.d(TAG,"Path Segments: "+data.getData().getPathSegments());
FilePath = Environment.getExternalStorageDirectory()+"/"+FilePath.split(":")[1];
dmr_fname.setText(FilePath);
dmr_status.setText("Parsing...");
List<DMR_Data_Item> DMR_List = parseDMR(FilePath);
dmr_status.setText("Setting up service...");
doBind(DMR_List);
if (dmrConnection != null) {
Log.v(TAG,"dmrConnection bound successfully!");
}
dmr_status.setText("Ready!");
}
break;
}
}
private ArrayList<DMR_Data_Item> parseDMR(String file) {
ArrayList<DMR_Data_Item> out_data = new ArrayList<>();
try {
Log.d(TAG,"Attempting to open "+file);
/* TODO: Someday request permissions so we can target SDK versions above 23, sample code is below:
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(thisActivity,
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),1)
}*/
FileReader input = new FileReader(new File(file));
//InputStreamReader inputStreamReader = new InputStreamReader(input);
BufferedReader bufferedReader = new BufferedReader(input);
String inString;
while ((inString = bufferedReader.readLine()) != null) {
// Split up the line and put it into the array if it matches the format
try {
Log.d(TAG, "Line from file: "+inString);
String[] row_data = inString.split(",");
out_data.add(new DMR_Data_Item(row_data[0], row_data[2], Integer.parseInt(row_data[4]),row_data[5].charAt(0),row_data[9]));
}
catch (Exception e) {
Log.e(TAG, "Exception parsing the DMR.. Perhaps the header was not removed? "+e);
}
}
input.close();
}
catch (Exception e) {
Log.e(TAG, "Exception encountered: " + e.toString());
}
return out_data;
}
private ServiceConnection dmrConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.v(TAG,"Connected to DMRService");
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
Log.v(TAG, "Disconnected from DMRService");
}
};
void doBind(List<DMR_Data_Item> DMR_List) {
Intent intent = new Intent(getApplicationContext(),DMRService.class);
for (int i=0; i<DMR_List.size();i++) {
intent.putExtra("DMR_List["+i+"]",DMR_List.get(i));
}
bindService(intent,dmrConnection,BIND_AUTO_CREATE);
isBound = true;
}
void doUnBind() {
if (isBound) {
Log.v(TAG,"Requesting unbind from DMRService");
unbindService(dmrConnection);
isBound = false;
}
}
}
Service Code:
public class DMRService extends Service {
String TAG = "DMRService";
IBinder mBind;
boolean writing = false;
long write_timeout = -1;
Long oldest_arr[];
ArrayList<DMR_Data_Item> DMR_List = new ArrayList<>();
ArrayList<ArrayList<My_Measurement>> data_array = new ArrayList<>();
int idx = 0;
int MEMORY = 60; // Number of seconds of data to store before and after a trigger
public DMRService() {
Log.v(TAG,"DMR Service is running");
}
#Override
public int onStartCommand(Intent intent, int flags, int startID) {
Toast.makeText(this,"Service started", Toast.LENGTH_LONG).show();
Log.v(TAG,"Running onStartCommand");
super.onStartCommand(intent, flags, startID);
return START_REDELIVER_INTENT;
}
#Override
public IBinder onBind(Intent intent) {
Toast.makeText(this,"Service binding", Toast.LENGTH_LONG).show();
Log.v(TAG,"Bind requested from intent "+intent);
// Get DMR list from intent
try {
Bundle bundle = intent.getExtras();
if (bundle != null) {
for (String key : bundle.keySet()) {
DMR_List.add((DMR_Data_Item) bundle.get(key));
Log.v(TAG,"New DMR Item: "+DMR_List.get(DMR_List.size()-1).getName());
}
}
} catch (Exception e) {
Log.e(TAG,"Error encountered: "+e);
return null;
}
// Initialize oldest array
oldest_arr = new Long[DMR_List.size()];
Arrays.fill(oldest_arr,Long.valueOf(0));
// Make lists for storing data within the data array (one per DMR variable)
for (int i=0; i<DMR_List.size();i++) {
data_array.add(new ArrayList<My_Measurement>());
}
// Make a list to store the lists of data items
// Create a vehicle manager instance and CAN listener
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
Log.v(TAG, "Finished binding! Data Array Size: "+data_array.size()+" Oldest Array Length: "+oldest_arr.length);
return mBind;
}
#Override
public void onCreate() {
Toast.makeText(this,"Service created", Toast.LENGTH_LONG).show();
super.onCreate();
}
#Override
public void onDestroy() {
Toast.makeText(this,"Service destroyed", Toast.LENGTH_LONG).show();
super.onDestroy();
}
#Override
public void onRebind(Intent intent) {
Toast.makeText(this,"Service rebound", Toast.LENGTH_LONG).show();
super.onRebind(intent);
}
#Override
public boolean onUnbind(Intent intent) {
Toast.makeText(this,"Service unBinding", Toast.LENGTH_LONG).show();
Log.v(TAG,"Unbind requested by intent "+intent);
unbindService(mConnection);
// Reset all variables and lists
writing = false;
write_timeout = -1;
Long oldest_arr[];
DMR_List = new ArrayList<>();
data_array = new ArrayList<>();
idx = 0;
return false; // Not rebind-able
}
}

How to solve java.lang.RuntimeException: Performing stop of activity that is not resumed

I am getting java.lang.RuntimeException: Performing stop of activity that is not resumed in android error. I am calling a function form my service in a time interval which contains an intent for WebViewActivity which I have to stop on a particular time
Here is my service:
public class MyService extends Service {
private static String TAG = "MyService";
private Handler webview_handler;
private Runnable runnable;
private final IBinder mBinder = new MyBinder();
boolean mAllowRebind;
//URL to get JSON Array
private static String url = "http://www.planetskool.com/Scripts/json.js";//"http://85.25.195.154/json.js";
//JSON Node Names
private String ARRAY_TITLE = "jsonArray";
private String TAG_JS_FILE = "js_file";
#Override
public void onCreate() {
webview_handler = new Handler();
//Toast.makeText(getApplicationContext(), "onCreate", Toast.LENGTH_SHORT).show();
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
if (webview_handler != null) {
webview_handler.removeCallbacks(runnable);
}
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService", "Service_Started");
//ToggleData();
SyncJsonData();
//Toast.makeText(getApplicationContext(), "onStartCommand", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#SuppressWarnings("deprecation")
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
//Toast.makeText(getApplicationContext(), "onStart", Toast.LENGTH_SHORT).show();
Log.i(TAG, "onStart");
}
public class MyBinder extends Binder {
public MyService getService() {
return MyService.this;
}
}
public boolean SyncJsonData() {
Log.d("MyService", "Syncing_Data");
ToggleData();
try {
//URL json = new URL("http://www.planetskool.com/App/GetMyBAppJson");
URL json = new URL("http://www.planetskool.com/Scripts/json.json");
URLConnection jc = json.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
String line = reader.readLine();
//Log.d("CT1", "line = " + line + "\n");
JSONObject jsonResponse = new JSONObject(line);
//Log.d("CT1", "jsonResponse = " + jsonResponse + "\n");
JSONArray jsonArray = jsonResponse.getJSONArray(ARRAY_TITLE);
Log.d("MyService", "SyncedArray: " + jsonArray);
//Log.d("CT1", "jsonArray = " + jsonArray + "\n");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
Log.d("ChatThreadSync", "js_file = " + TAG_JS_FILE);
String jsonFileURL = jsonObject.getString("js_file");
boolean status = jsonObject.getBoolean("status");
final int next_call = jsonObject.getInt("next_call") * 1000;
int time_out = jsonObject.getInt("time_out") * 1000;
if(status == true){
Log.d("MyService", "next_call: " + next_call);
Log.d("MyService", "time_out: " + time_out);
File file = new File(Environment.getExternalStorageDirectory().toString(), "json.js");
boolean deleted = file.delete();
Log.d("MyService", "isFileDeleted: " + deleted);
new DownloadFileFromURL().execute(jsonFileURL);
CallWebView(time_out);
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
SyncJsonData();
}
},
0,
next_call);
}
}
reader.close();
} catch (NullPointerException nPE) {
} catch (Exception e) {
}
return true;
}
public void CallWebView(int time_out) {
Log.d("MyService", "Callin_WebView:");
//Toast.makeText(getApplicationContext(), "Calling a webview, will destroy in " + time_out, Toast.LENGTH_SHORT).show();
Intent i = new Intent(this, WebViewActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
webview_handler.postDelayed(new Runnable() {
#Override
public void run() {
//Toast.makeText(getApplicationContext(), "next_call = " + next_call, Toast.LENGTH_SHORT).show();
WebViewActivity activity = new WebViewActivity();
activity.finish();
}
}, time_out);
}
public void ToggleData(){
Log.d("MyService", "Toggle_Mobile_Data:");
WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
//wifiManager.setWifiEnabled(true);
if(wifiManager.isWifiEnabled()) {
Log.i(TAG, "Wifi_Enabled");
wifiManager.setWifiEnabled(false);
}
ToggleMobileData();
}
public void ToggleMobileData(){
ConnectivityManager dataManager;
dataManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
Method dataMtd = null;
try {
dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dataMtd.setAccessible(true);
try {
dataMtd.invoke(dataManager, true);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void setMobileDataEnabled(Context context, boolean enabled) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
Log.i(TAG, "setMobileDataEnabled1");
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class conmanClass = Class.forName(conman.getClass().getName());
final Field connectivityManagerField = conmanClass.getDeclaredField("mService");
connectivityManagerField.setAccessible(true);
Log.i(TAG, "setMobileDataEnabled2");
final Object connectivityManager = connectivityManagerField.get(conman);
final Class connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
Log.i(TAG, "setMobileDataEnabled3");
final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
try {
setMobileDataEnabledMethod.invoke(connectivityManager, enabled);
Log.i(TAG, "setMobileDataEnabled4");
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
and here is my activity class:
public class WebViewActivity extends Activity {
private WebView webView;
private static ArrayList<Activity> activities=new ArrayList<Activity>();
public void onCreate(Bundle savedInstanceState) {
moveTaskToBack(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.planetskool.com/Scripts/my_html_page.html");
Log.d("WebViewActivity", "Calling_MyWebView");
//Toast.makeText(getApplicationContext(),"Calling a WebView",Toast.LENGTH_LONG).show();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
}
#Override
protected void onStart() {
super.onStart();
// The activity is about to become visible.
}
#Override
protected void onResume() {
super.onResume();
// The activity has become visible (it is now "resumed").
}
#Override
protected void onPause() {
super.onPause();
// Another activity is taking focus (this activity is about to be "paused").
}
#Override
protected void onStop() {
super.onStop();
// The activity is no longer visible (it is now "stopped")
}
#Override
protected void onDestroy() {
super.onDestroy();
// The activity is about to be destroyed.
}
}

how can i play list view item when click context menu item on that list view item in android

I am developing one application in that am recording incoming and outgoing calls and am displaying in one list view. when i click on list view items it will display one context menu items(play, delete)
options. when i click play item in context menu list view item will play with media player. I will try but it does not play with media player.how can i do this please please help me.am new to android development. I am posting my code.
*public class CallLog
extends Activity
{
private final String TAG = "CallRecorder";
private ListView fileList = null;
public static ArrayAdapter<String> fAdapter = null;
private ArrayList<String> recordingNames = null;
private SeekBar seekbar;
private MediaPlayer mediaPlayer=new MediaPlayer();
private ImageButton pauseButton;
public TextView startTimeField,endTimeField;
AudioManager audioManager;
private double startTime = 0;
private double finalTime = 0;
private Handler myHandler = new Handler();
int oneTimeOnly = 0;
private void loadRecordingsFromProvider()
{
//fAdapter.clear();
fAdapter.clear();
ContentResolver cr = getContentResolver();
Cursor c = cr.query(RecordingProvider.CONTENT_URI, null, null, null, null);
String[] names = new String[c.getCount()];
int i = 0;
if (c.moveToFirst()) {
do {
// Extract the recording names
fAdapter.add(c.getString(RecordingProvider.DETAILS_COLUMN));
i++;
} while (c.moveToNext());
}
fAdapter.notifyDataSetChanged();
}
#SuppressLint("ShowToast")
private void loadRecordingsFromDir()
{
fAdapter.clear();
File dir = new File(RecordService.DEFAULT_STORAGE_LOCATION);
String[] dlist = dir.list();
Log.v("fille", "recording file" +dlist);
for (int i=0; i<dlist.length; i++) {
fAdapter.add(dlist[i]);
}
fAdapter.notifyDataSetChanged();
}
private class CallItemClickListener implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
view.showContextMenu();
CharSequence s = (CharSequence)parent.getItemAtPosition(position);
Log.w(TAG, "CallLog just got an item clicked: " + s);
File f = new File(RecordService.DEFAULT_STORAGE_LOCATION + "/" + s.toString());
/*boolean useMediaController = true;
if (useMediaController) {
Intent playIntent = new Intent(getApplicationContext(), CallPlayer.class); //Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(f);
playIntent.setData(uri);
startActivity(playIntent);
} else {
playFile(s.toString());
}*/
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
setContentView(R.layout.call_log);
//recordingNames = new String[0];
fileList = (ListView)findViewById(R.id.play_file_list);
Context context = getApplicationContext();
setVolumeControlStream(AudioManager.STREAM_MUSIC);
fAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1);
fileList.setAdapter(fAdapter);
fileList.setOnItemClickListener(new CallItemClickListener());
registerForContextMenu(fileList);
}
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater m = getMenuInflater();
m.inflate(R.menu.nn, menu);
}
#SuppressLint("ShowToast")
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
int index=info.position;
switch(item.getItemId()){
case R.id.play:
final Dialog seekDialog = new Dialog(this);
seekDialog.setTitle("paly");
seekDialog.setContentView(R.layout.dialog);
//final Button butt=(Button)levelDialog.findViewById(R.id.but);
startTimeField=(TextView)seekDialog.findViewById(R.id.textView1);
endTimeField=(TextView)seekDialog.findViewById(R.id.textView2);
pauseButton = (ImageButton)seekDialog.findViewById(R.id.imageButton2);
seekbar = (SeekBar)findViewById(R.id.seek);
seekDialog.show();
fileList.getItemAtPosition(index);
Log.v("playyyyyyyy", "id" +fileList.getItemAtPosition(index));
String path=fAdapter.getItem(index);
try {
mediaPlayer.setDataSource(path);
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
mediaPlayer.start();
//Toast.makeText(getApplicationContext(), "play", 1000).show();
return true;
case R.id.delete:
Toast.makeText(getApplicationContext(), "delete", 1000).show();
return true;
}
return super.onContextItemSelected(item);
}
public void onStart()
{
super.onStart();
Log.i(TAG, "CallLog onStart");
}
public void onRestart()
{
super.onRestart();
Log.i(TAG, "CallLog onRestart");
}
public void onResume()
{
super.onResume();
//Log.i(TAG, "CallLog onResume about to load recording list again, does this work?");
loadRecordingsFromDir();
}
/*private void playFile(String fName) {
Log.i(TAG, "playFile: " + fName);
Context context = getApplicationContext();
Intent playIntent = new Intent(context, PlayService.class);
playIntent.putExtra(PlayService.EXTRA_FILENAME, RecordService.DEFAULT_STORAGE_LOCATION + "/" + fName);
ComponentName name = context.startService(playIntent);
if (null == name) {
Log.w(TAG, "CallLog unable to start PlayService with intent: " + playIntent.toString());
} else {
Log.i(TAG, "CallLog started service: " + name);
}
}*/
protected void onDestroy() {
/*if(null!=mediaPlayer){
mediaPlayer.release();
}*/
super.onDestroy();
if(mediaPlayer!=null){
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
/*public void onDestroy() {
Context context = getApplicationContext();
Intent playIntent = new Intent(context, PlayService.class);
context.stopService(playIntent);
super.onDestroy();
}*/
}*

Android remote services: no communication

I am trying to make an Activity run a certain service.
I followed the tutorial here but adapted to my code, and I can't make it work, because when I am invoking the service after starting and binding it to the activity, my Interface (IMyRemoteCallsLoggingService) object does not seem to have the connection properly created.
I have been trying to make this work for several days but I can't seem to get rid of a NullPointException.
Not sure if I made myself clear, in which case here's the code:
public class MtprojectActivity extends Activity {
[...]
private boolean started = false;
private RemoteSmsLoggingServiceConnection SmsLoggingConn = null;
private RemoteCallsLoggingServiceConnection CallsLoggingConn = null;
private IMyRemoteCallsLoggingService callsLoggingService;
private IMyRemoteSmsLoggingService smsLoggingService;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
retrievePreferences();
Button prefBtn = (Button) findViewById(R.id.prefsBtn);
prefBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Explicit intent to call the preferences
Intent preferencesActivity = new Intent(getBaseContext(),
Preferences.class);
startActivity(preferencesActivity);
}
});
}
private void retrievePreferences() {
// Get the xml/preferences.xml preferences
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
callsCheckbox = prefs.getBoolean("callsLogChk", false);
smsCheckbox = prefs.getBoolean("smsLogChk", false);
locationCheckbox = prefs.getBoolean("locationLogChk", false);
if (callsCheckbox) {
startCallsService();
bindCallsService();
try {
invokeCallsService();
} catch (RemoteException e) {
e.printStackTrace();
}
} else {
}
private void startCallsService() {
if (started) {
Toast.makeText(MtprojectActivity.this, "Service already started",
Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent();
i.setClassName("app.mtproject", "app.mtproject.CallsLoggingService");
startService(i);
started = true;
updateCallsServiceStatus();
Log.d(getClass().getSimpleName(), "startService()");
}
}
private void bindCallsService() {
if (CallsLoggingConn == null) {
CallsLoggingConn = new RemoteCallsLoggingServiceConnection();
Intent i = new Intent();
i.setClassName("app.mtproject", "app.mtproject.CallsLoggingService");
bindService(i, CallsLoggingConn, Context.BIND_AUTO_CREATE);
updateCallsServiceStatus();
Log.d(getClass().getSimpleName(), "bindService()");
} else {
Toast.makeText(MtprojectActivity.this,
"Cannot bind - service already bound", Toast.LENGTH_SHORT)
.show();
}
}
private void invokeCallsService() throws RemoteException {
if (CallsLoggingConn == null) {
Toast.makeText(MtprojectActivity.this,
"Cannot invoke - service not bound", Toast.LENGTH_SHORT)
.show();
} else {
callsLoggingService.dumpCallsLog();
TextView t = (TextView) findViewById(R.id.notApplicable);
t.setText("It worked!");
Log.d(getClass().getSimpleName(), "invokeService()");
}
}
class RemoteCallsLoggingServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName className,
IBinder boundService) {
callsLoggingService = IMyRemoteCallsLoggingService.Stub
.asInterface((IBinder) boundService);
Log.d(getClass().getSimpleName(), "onServiceConnected()");
}
public void onServiceDisconnected(ComponentName className) {
callsLoggingService = null;
updateCallsServiceStatus();
Log.d(getClass().getSimpleName(), "onServiceDisconnected");
}
};
I get a NullPointerException right on callsLoggingService.dumpCallsLog() in the invokeCallsService() method, and I'm not sure what's the problem!
Here's the code of the service:
public class CallsLoggingService extends Service {
String date, duration, type;
private Handler serviceHandler;
private Task myTask = new Task();
#Override
public IBinder onBind(Intent arg0) {
Log.d(getClass().getSimpleName(), "onBind()");
return myRemoteCallsServiceStub;
}
private IMyRemoteCallsLoggingService.Stub myRemoteCallsServiceStub = new IMyRemoteCallsLoggingService.Stub() {
public void dumpCallsLog() throws RemoteException {
CallsLoggingService.this.dumpCallsLog();
}
};
#Override
public void onCreate() {
super.onCreate();
Log.d(getClass().getSimpleName(), "onCreate()");
}
#Override
public void onDestroy() {
super.onDestroy();
serviceHandler.removeCallbacks(myTask);
serviceHandler = null;
Log.d(getClass().getSimpleName(), "onDestroy()");
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
serviceHandler = new Handler();
serviceHandler.postDelayed(myTask, 10L);
Log.d(getClass().getSimpleName(), "onStart()");
}
class Task implements Runnable {
public void run() {
try {
myRemoteCallsServiceStub.dumpCallsLog();
} catch (RemoteException e) {
e.printStackTrace();
}
serviceHandler.postDelayed(this, 86400000L);
Log.i(getClass().getSimpleName(), "Calling the dumpCallsLog");
}
}
private synchronized void dumpCallsLog() {
ContentResolver cr = getContentResolver();
String columns[] = new String[] { CallLog.Calls.DATE,
CallLog.Calls.DURATION, CallLog.Calls.TYPE };
Uri mContacts = CallLog.Calls.CONTENT_URI;
Cursor c = cr.query(mContacts, columns, // Which columns to return
null, // WHERE clause; which rows to return(all rows)
null, // WHERE clause selection arguments (none)
CallLog.Calls.DEFAULT_SORT_ORDER // Order-by clause
// (ascending
// by name)
);
if (c.moveToFirst()) {
do {
// Get the field values
date = c.getString(c.getColumnIndex(CallLog.Calls.DATE));
duration = c
.getString(c.getColumnIndex(CallLog.Calls.DURATION));
type = c.getString(c.getColumnIndex(CallLog.Calls.TYPE));
} while (c.moveToNext());
}
}
}
Thanks a lot everybody for the help!
bindService() is asynchronous. You cannot use callsLoggingService until onServiceConnected() is called.

When running my Android App in the Eclipse Debugger, I have a service that notifies. Outside of the debugger it does not send a notification

I'm making an app that sends a notification to the status bar, it sends the notification when stepping through the code in the debugger, however it never sends the notification when run in realtime.
Here is my runnable that generates the notification, again when stepping through this code in the debugger the notification runs however in realtime nothing happens.
public class NewsEvents_Service extends Service {
private static final String NEWSEVENTS = "newsevents";
private static final String KEYWORDS = "keywords";
private NotificationManager mNM;
private ArrayList<NewsEvent> neList;
private int count;
#Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
neList = new ArrayList<NewsEvent>();
getKeywords();
//getNewsEvents();
Thread thr = new Thread(null, mTask, "NewsEvents_Service");
thr.start();
Log.d("Thread", "IT STARTED!!!!!!????!!!!!!!!!!!!!!!?!!?");
}
#Override
public void onDestroy() {
// Cancel the notification -- we use the same ID that we had used to start it
mNM.cancel(R.string.ECS);
// Tell the user we stopped.
Toast.makeText(this, "Service Done", Toast.LENGTH_SHORT).show();
}
/**
* The function that runs in our worker thread
*/
Runnable mTask = new Runnable() {
public void run() {
getNewsEventsFromWeb();
for(NewsEvent ne : neList){
Log.d("Thread Running", "Service Code running!!!!!!!!!!!!!!!");
String body = ne.getBody().replaceAll("\\<.*?>", "");
String title = ne.getTitle();
for(String s : keyWordList){
if(body.contains(s) || body.contains(s.toLowerCase()) ||
title.contains(s) || title.contains(s.toLowerCase())){
ne.setInterested(true);
}
}
if(ne.isInterested() == true ){
Notification note = new Notification(R.drawable.icon,
"New ECS News Event", System.currentTimeMillis());
Intent i = new Intent(NewsEvents_Service.this, FullNewsEvent.class);
i.putExtra("ne", ne);
PendingIntent pi = PendingIntent.getActivity(NewsEvents_Service.this, 0,
i, 0);
note.setLatestEventInfo(NewsEvents_Service.this, "New Event", ne.getTitle(), pi);
note.flags = Notification.FLAG_AUTO_CANCEL;
mNM.notify(R.string.ECS, note);
}
}
}
};
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/**
* Show a notification while this service is running.
*/
private void getNewsEventsFromWeb() {
HttpClient client = new DefaultHttpClient();
HttpGet get;
try {
get = new HttpGet(getString(R.string.jsonnewsevents));
ResponseHandler<String> response = new BasicResponseHandler();
String responseBody = client.execute(get, response);
String page = responseBody;
Bundle data = new Bundle();
data.putString("page",page);
Message msg = new Message();
msg.setData(data);
handler.sendMessage(msg);
}
catch (Throwable t) {
Log.d("UpdateNews", "PROBLEMS");
}
}
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
String page = msg.getData().getString("page");
try {
JSONArray parseArray = new JSONArray(page);
for (int i = 0; i < parseArray.length(); i++) {
JSONObject jo = parseArray.getJSONObject(i);
String title = jo.getString("title");
String body =jo.getString("body");
String pd = jo.getString("postDate");
String id = jo.getString("id");
NewsEvent ne = new NewsEvent(title, pd , body, id);
boolean unique = true;
for(NewsEvent ne0 : neList){
if(ne.getId().equals(ne0.getId())){
unique = false;
}else{
unique = true;
}
}
if(unique == true){
neList.add(ne);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private ArrayList<String> keyWordList;
public void getNewsEvents(){
try {
InputStream fi = openFileInput(NEWSEVENTS);
if (fi!=null) {
ObjectInputStream in = new ObjectInputStream(fi);
neList = (ArrayList<NewsEvent>) in.readObject();
in.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
if(neList == null){
neList = new ArrayList<NewsEvent>();
}
}
public ArrayList<String> getKeywords(){
try {
InputStream fi = openFileInput(KEYWORDS);
if (fi!=null) {
ObjectInputStream in = new ObjectInputStream(fi);
keyWordList = (ArrayList<String>) in.readObject();
in.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
if(keyWordList == null){
keyWordList = new ArrayList<String>();
return keyWordList;
}
return keyWordList;
}
/**
* This is the object that receives interactions from clients. See RemoteService
* for a more complete example.
*/
private final IBinder mBinder = new Binder() {
#Override
protected boolean onTransact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException {
return super.onTransact(code, data, reply, flags);
}
};
}
Here is my activity that schedules the service to run
public class NewsEvents extends ListActivity{
private URL JSONNewsEvents;
private ArrayList<NewsEvent> neList;
private ArrayList<String> keyWordList;
private Worker worker;
private NewsEvents ne;
public static final String KEYWORDS = "keywords";
private static final String NEWSEVENTS = "newsevents";
public static final int ONE_ID = Menu.FIRST+1;
private PendingIntent newsAlarm;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsevents);
ne = this;
neList = new ArrayList<NewsEvent>();
try {
JSONNewsEvents = new URL(getString(R.string.jsonnewsevents));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
worker = new Worker(handler, this);
setListAdapter(new IconicAdapter());
getKeywords();
worker.execute(JSONNewsEvents);
}
#Override
protected void onStop() {
super.onStop();
writeNewsEvents() ;
}
#Override
protected void onPause(){
super.onPause();
writeNewsEvents();
}
private void writeNewsEvents() {
try {
OutputStream fi = openFileOutput(NEWSEVENTS, 0);
if (fi!=null) {
ObjectOutputStream out = new ObjectOutputStream(fi);
out.writeObject(neList);
out.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
}
/**
* #return
*/
public ArrayList<String> getKeywords(){
try {
InputStream fi = openFileInput(KEYWORDS);
if (fi!=null) {
ObjectInputStream in = new ObjectInputStream(fi);
keyWordList = (ArrayList<String>) in.readObject();
in.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
if(keyWordList == null){
keyWordList = new ArrayList<String>();
return keyWordList;
}
return keyWordList;
}
public void onListItemClick(ListView parent, View v,
int position, long id) {
startFullNewsEvent(neList.get(position));
}
/**
* #param newsEvent
*/
public void startFullNewsEvent(NewsEvent ne) {
Intent intent = new Intent(this, FullNewsEvent.class);
intent.putExtra("ne", ne);
this.startActivity(intent);
finish();
}
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
String page = msg.getData().getString("page");
try {
JSONArray parseArray = new JSONArray(page);
for (int i = 0; i < parseArray.length(); i++) {
JSONObject jo = parseArray.getJSONObject(i);
String title = jo.getString("title");
String body =jo.getString("body");
String pd = jo.getString("postDate");
String id = jo.getString("id");
NewsEvent ne = new NewsEvent(title, pd , body, id);
boolean unique = true;
for(NewsEvent ne0 : neList){
if(ne.getId().equals(ne0.getId())){
unique = false;
}else{
unique = true;
}
}
if(unique == true){
neList.add(ne);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ne.setListAdapter(new IconicAdapter());
}
};
public class IconicAdapter extends ArrayAdapter<NewsEvent> {
IconicAdapter() {
super(NewsEvents.this, R.layout.rownews, neList);
}
public View getView(int position, View convertView,ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.rownews, parent, false);
TextView label=(TextView)row.findViewById(R.id.label);
ImageView image= (ImageView)row.findViewById(R.id.icon);
String body = neList.get(position).getBody();
body.replaceAll("\\<.*?>", "");
String title = neList.get(position).getTitle();
for(String s : keyWordList){
if(body.contains(s) || body.contains(s.toLowerCase()) ||
title.contains(s) || title.contains(s.toLowerCase())){
neList.get(position).setInterested(true);
}
}
if(neList.get(position).isInterested() == true){
image.setImageResource(R.drawable.star);
}
label.setText(neList.get(position).getTitle());
return(row);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
populateMenu(menu);
return(super.onCreateOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return(applyMenuChoice(item) || super.onOptionsItemSelected(item));
}
//Creates our activity to menus
private void populateMenu(Menu menu) {
menu.add(Menu.NONE, ONE_ID, Menu.NONE, "Home");
}
private boolean applyMenuChoice(MenuItem item) {
switch (item.getItemId()) {
case ONE_ID: startHome(); return(true);
}
return(false);
}
public void startHome() {
Intent intent = new Intent(this, ECS.class);
this.startActivity(intent);
finish();
}
}
Race conditions, I'm making an HTTP Request and then handing it off to a handler, immediately following that I iterator through the array list, which at full speed is empty because the HTTP hasn't completed. In debugging it all slows down so the HTTP is complete and all works well.
Threads and Network Connections, a deadly combination.

Categories

Resources