Generate Random Characters in Android Studio using Broadcast The Next CEO of Stack OverflowHow to generate a random alpha-numeric string?How do I generate random integers within a specific range in Java?Close/hide the Android Soft KeyboardGenerate random string/characters in JavaScriptGenerating random whole numbers in JavaScript in a specific range?Why is the Android emulator so slow? How can we speed up the Android emulator?How do I generate a random int number?Generate random number between two numbers in JavaScriptProper use cases for Android UserManager.isUserAGoat()?Why does this code using random strings print “hello world”?

How can the PCs determine if an item is a phylactery?

Raspberry pi 3 B with Ubuntu 18.04 server arm64: what pi version

Which acid/base does a strong base/acid react when added to a buffer solution?

How can I separate the number from the unit in argument?

Is it possible to make a 9x9 table fit within the default margins?

How dangerous is XSS

Read/write a pipe-delimited file line by line with some simple text manipulation

Is it possible to create a QR code using text?

Compensation for working overtime on Saturdays

How can a day be of 24 hours?

Why can't we say "I have been having a dog"?

What did the word "leisure" mean in late 18th Century usage?

Upgrading From a 9 Speed Sora Derailleur?

A hang glider, sudden unexpected lift to 25,000 feet altitude, what could do this?

How exploitable/balanced is this homebrew spell: Spell Permanency?

Are British MPs missing the point, with these 'Indicative Votes'?

How badly should I try to prevent a user from XSSing themselves?

How to find if SQL server backup is encrypted with TDE without restoring the backup

How do I keep Mac Emacs from trapping M-`?

MT "will strike" & LXX "will watch carefully" (Gen 3:15)?

What is the difference between 'contrib' and 'non-free' packages repositories?

How seriously should I take size and weight limits of hand luggage?

Why did early computer designers eschew integers?

Avoiding the "not like other girls" trope?



Generate Random Characters in Android Studio using Broadcast



The Next CEO of Stack OverflowHow to generate a random alpha-numeric string?How do I generate random integers within a specific range in Java?Close/hide the Android Soft KeyboardGenerate random string/characters in JavaScriptGenerating random whole numbers in JavaScript in a specific range?Why is the Android emulator so slow? How can we speed up the Android emulator?How do I generate a random int number?Generate random number between two numbers in JavaScriptProper use cases for Android UserManager.isUserAGoat()?Why does this code using random strings print “hello world”?










0















Working on an app that is supposed to generate random characters via a broadcast. I need to broadcast the random characters generated by my custom service, so that the main activity registered to intercept the broadcast can get the random numbers and display them on an EditText. The layout is shown here: app layout



The start button will trigger the random character generator service. The EditText will display the random numbers generated in real time (without any button press). The stop button will stop the service. The EditText won’t display any numbers. I have created a service(RandomCharacterService) and registered it in my manifest. Upon running the app, my app crashes. I am sure it is because I did not register my broadcast in my manifest, but I do not understand how to do that. And perhaps there is something wrong with how I am handling the broadcast in my main activity. In my button click method for the start button, I tried to do a for-loop, but this resulted in the app crashing as well.



AndroidManifest.xml:



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.cs7455rehmarazzaklab8">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".RandomCharacterService"></service>

</application>




MainActivityjava:



 package com.example.cs7455rehmarazzaklab8;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
import java.util.Random;

public class MainActivity extends AppCompatActivity

private Button btnStart, btnStop;
private EditText myTV;

private Intent serviceIntent;
private RandomCharacterService myService;
private ServiceConnection myServiceConnection;
private boolean isServiceOn; //checks if the service is on

private int myRandomCharacter;
char MyRandomCharacter = (char)myRandomCharacter;
private boolean isRandomGeneratorOn;

private final int MIN = 65;
char m = (char)MIN;
private final int MAX = 26;
char x = (char)MAX;
private final String TAG = "Random Char Service: ";

private final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

private Context mContext;
private Random mRandom = new Random();

// Initialize a new BroadcastReceiver instance
private BroadcastReceiver mRandomCharReceiver = new BroadcastReceiver()

@Override
public void onReceive(Context context, Intent intent)
// Get the received random number
myRandomCharacter = intent.getIntExtra("RandomCharacter",-1);

// Display a notification that the broadcast received
Toast.makeText(context,"Received : " + myRandomCharacter,Toast.LENGTH_SHORT).show();

;

@Override
protected void onCreate(Bundle savedInstanceState)

requestWindowFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the application context
mContext = getApplicationContext();

btnStart = (Button) findViewById(R.id.StartButton);
btnStop = (Button) findViewById(R.id.StopButton);


myTV = (EditText)findViewById(R.id.RandomCharText);

// Register the local broadcast
LocalBroadcastManager.getInstance(mContext).registerReceiver(mRandomCharReceiver, new IntentFilter("BROADCAST_RANDOM_CHARACTER"));

// Change the action bar color
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFFF00BF")));

// Set a click listener for start button
btnStart.setOnClickListener(new View.OnClickListener()

@Override
public void onClick(View view)

isServiceOn = true;

serviceIntent = new Intent(getApplicationContext(), RandomCharacterService.class);
startService(serviceIntent);
setRandomNumber();
// Generate a random char
myRandomCharacter = new Random().nextInt(x)+m;

// Initialize a new intent instance
Intent intent = new Intent("BROADCAST_RANDOM_CHARACTER");
// Put the random character to intent to broadcast it
intent.putExtra("RandomCharacter",myRandomCharacter);

// Send the broadcast
LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);

// Update the TextView with random character
myTV.setText(" " + myRandomCharacter );

);

btnStop.setOnClickListener(new View.OnClickListener()

@Override
public void onClick(View view)

isServiceOn = false;

stopService(serviceIntent);

);

private void setRandomNumber()

myTV.setText("Random Character: " + (char)myService.getRandomCharacter());
String alphabet = myTV.getText().toString();






RandomCharacterService.java:



 package com.example.cs7455rehmarazzaklab8;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.Random;


public class RandomCharacterService extends Service

private int myRandomCharacter;
char MyRandomCharacter = (char)myRandomCharacter;
private boolean isRandomGeneratorOn;

private final int MIN = 65;
char m = (char)MIN;
private final int MAX = 26;
char x = (char)MAX;
private final String TAG = "Random Char Service: ";

private final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

class RandomCharacterServiceBinder extends Binder
public RandomCharacterService getService()

return RandomCharacterService.this;



private IBinder myBinder = new RandomCharacterServiceBinder();

@Override
public int onStartCommand(Intent intent, int flags, int startId)

Log.i(TAG, "In OnStartCommand Thread ID is "+Thread.currentThread().getId());
isRandomGeneratorOn = true;

new Thread(new Runnable()

@Override
public void run()

startRandomGenerator();


).start();

return START_STICKY;


private void startRandomGenerator()

while(isRandomGeneratorOn)

char alphabet = 'A';
for (int i = 65; i < 90; i++)

try

Thread.sleep(1000);
if(isRandomGeneratorOn)

alphabet++;
myRandomCharacter = new Random().nextInt(x)+m;
Log.i(TAG, "Thread ID is "+Thread.currentThread().getId() + ", Random character is "+(char)myRandomCharacter);


catch(InterruptedException e)

Log.i(TAG, "Thread Interrupted.");








private void stopRandomGenerator()

isRandomGeneratorOn = false;


public int getRandomCharacter()

return myRandomCharacter;


public boolean isRandomGeneratorOn()
return isRandomGeneratorOn;


@Override
public void onDestroy()

super.onDestroy();
stopRandomGenerator();
Log.i(TAG, "Service Destroyed.");


@Nullable
@Override
public IBinder onBind(Intent intent)

Log.i(TAG, "In onBind ...");
return myBinder;




Call Stack:callstack from running the app



Call Stack from attempting to press the stop button:crash from attempting to press stop button










share|improve this question
























  • You should include the call stack for the crash you're running into.

    – Advice-Dog
    Mar 8 at 19:25











  • Noted, and included!

    – Amma
    Mar 8 at 20:11











  • 1. You don't initialize myService in the activity so it will always throw an NPE. 2. You have a race condition you use serviceIntent in one button press but initialize it in another. There is, currently, no guarantee that the buttons will be pressed in a specific order.

    – Ge3ng
    Mar 8 at 21:16











  • Oh I see. So how would i initialize myService?

    – Amma
    Mar 8 at 21:36















0















Working on an app that is supposed to generate random characters via a broadcast. I need to broadcast the random characters generated by my custom service, so that the main activity registered to intercept the broadcast can get the random numbers and display them on an EditText. The layout is shown here: app layout



The start button will trigger the random character generator service. The EditText will display the random numbers generated in real time (without any button press). The stop button will stop the service. The EditText won’t display any numbers. I have created a service(RandomCharacterService) and registered it in my manifest. Upon running the app, my app crashes. I am sure it is because I did not register my broadcast in my manifest, but I do not understand how to do that. And perhaps there is something wrong with how I am handling the broadcast in my main activity. In my button click method for the start button, I tried to do a for-loop, but this resulted in the app crashing as well.



AndroidManifest.xml:



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.cs7455rehmarazzaklab8">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".RandomCharacterService"></service>

</application>




MainActivityjava:



 package com.example.cs7455rehmarazzaklab8;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
import java.util.Random;

public class MainActivity extends AppCompatActivity

private Button btnStart, btnStop;
private EditText myTV;

private Intent serviceIntent;
private RandomCharacterService myService;
private ServiceConnection myServiceConnection;
private boolean isServiceOn; //checks if the service is on

private int myRandomCharacter;
char MyRandomCharacter = (char)myRandomCharacter;
private boolean isRandomGeneratorOn;

private final int MIN = 65;
char m = (char)MIN;
private final int MAX = 26;
char x = (char)MAX;
private final String TAG = "Random Char Service: ";

private final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

private Context mContext;
private Random mRandom = new Random();

// Initialize a new BroadcastReceiver instance
private BroadcastReceiver mRandomCharReceiver = new BroadcastReceiver()

@Override
public void onReceive(Context context, Intent intent)
// Get the received random number
myRandomCharacter = intent.getIntExtra("RandomCharacter",-1);

// Display a notification that the broadcast received
Toast.makeText(context,"Received : " + myRandomCharacter,Toast.LENGTH_SHORT).show();

;

@Override
protected void onCreate(Bundle savedInstanceState)

requestWindowFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the application context
mContext = getApplicationContext();

btnStart = (Button) findViewById(R.id.StartButton);
btnStop = (Button) findViewById(R.id.StopButton);


myTV = (EditText)findViewById(R.id.RandomCharText);

// Register the local broadcast
LocalBroadcastManager.getInstance(mContext).registerReceiver(mRandomCharReceiver, new IntentFilter("BROADCAST_RANDOM_CHARACTER"));

// Change the action bar color
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFFF00BF")));

// Set a click listener for start button
btnStart.setOnClickListener(new View.OnClickListener()

@Override
public void onClick(View view)

isServiceOn = true;

serviceIntent = new Intent(getApplicationContext(), RandomCharacterService.class);
startService(serviceIntent);
setRandomNumber();
// Generate a random char
myRandomCharacter = new Random().nextInt(x)+m;

// Initialize a new intent instance
Intent intent = new Intent("BROADCAST_RANDOM_CHARACTER");
// Put the random character to intent to broadcast it
intent.putExtra("RandomCharacter",myRandomCharacter);

// Send the broadcast
LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);

// Update the TextView with random character
myTV.setText(" " + myRandomCharacter );

);

btnStop.setOnClickListener(new View.OnClickListener()

@Override
public void onClick(View view)

isServiceOn = false;

stopService(serviceIntent);

);

private void setRandomNumber()

myTV.setText("Random Character: " + (char)myService.getRandomCharacter());
String alphabet = myTV.getText().toString();






RandomCharacterService.java:



 package com.example.cs7455rehmarazzaklab8;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.Random;


public class RandomCharacterService extends Service

private int myRandomCharacter;
char MyRandomCharacter = (char)myRandomCharacter;
private boolean isRandomGeneratorOn;

private final int MIN = 65;
char m = (char)MIN;
private final int MAX = 26;
char x = (char)MAX;
private final String TAG = "Random Char Service: ";

private final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

class RandomCharacterServiceBinder extends Binder
public RandomCharacterService getService()

return RandomCharacterService.this;



private IBinder myBinder = new RandomCharacterServiceBinder();

@Override
public int onStartCommand(Intent intent, int flags, int startId)

Log.i(TAG, "In OnStartCommand Thread ID is "+Thread.currentThread().getId());
isRandomGeneratorOn = true;

new Thread(new Runnable()

@Override
public void run()

startRandomGenerator();


).start();

return START_STICKY;


private void startRandomGenerator()

while(isRandomGeneratorOn)

char alphabet = 'A';
for (int i = 65; i < 90; i++)

try

Thread.sleep(1000);
if(isRandomGeneratorOn)

alphabet++;
myRandomCharacter = new Random().nextInt(x)+m;
Log.i(TAG, "Thread ID is "+Thread.currentThread().getId() + ", Random character is "+(char)myRandomCharacter);


catch(InterruptedException e)

Log.i(TAG, "Thread Interrupted.");








private void stopRandomGenerator()

isRandomGeneratorOn = false;


public int getRandomCharacter()

return myRandomCharacter;


public boolean isRandomGeneratorOn()
return isRandomGeneratorOn;


@Override
public void onDestroy()

super.onDestroy();
stopRandomGenerator();
Log.i(TAG, "Service Destroyed.");


@Nullable
@Override
public IBinder onBind(Intent intent)

Log.i(TAG, "In onBind ...");
return myBinder;




Call Stack:callstack from running the app



Call Stack from attempting to press the stop button:crash from attempting to press stop button










share|improve this question
























  • You should include the call stack for the crash you're running into.

    – Advice-Dog
    Mar 8 at 19:25











  • Noted, and included!

    – Amma
    Mar 8 at 20:11











  • 1. You don't initialize myService in the activity so it will always throw an NPE. 2. You have a race condition you use serviceIntent in one button press but initialize it in another. There is, currently, no guarantee that the buttons will be pressed in a specific order.

    – Ge3ng
    Mar 8 at 21:16











  • Oh I see. So how would i initialize myService?

    – Amma
    Mar 8 at 21:36













0












0








0








Working on an app that is supposed to generate random characters via a broadcast. I need to broadcast the random characters generated by my custom service, so that the main activity registered to intercept the broadcast can get the random numbers and display them on an EditText. The layout is shown here: app layout



The start button will trigger the random character generator service. The EditText will display the random numbers generated in real time (without any button press). The stop button will stop the service. The EditText won’t display any numbers. I have created a service(RandomCharacterService) and registered it in my manifest. Upon running the app, my app crashes. I am sure it is because I did not register my broadcast in my manifest, but I do not understand how to do that. And perhaps there is something wrong with how I am handling the broadcast in my main activity. In my button click method for the start button, I tried to do a for-loop, but this resulted in the app crashing as well.



AndroidManifest.xml:



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.cs7455rehmarazzaklab8">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".RandomCharacterService"></service>

</application>




MainActivityjava:



 package com.example.cs7455rehmarazzaklab8;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
import java.util.Random;

public class MainActivity extends AppCompatActivity

private Button btnStart, btnStop;
private EditText myTV;

private Intent serviceIntent;
private RandomCharacterService myService;
private ServiceConnection myServiceConnection;
private boolean isServiceOn; //checks if the service is on

private int myRandomCharacter;
char MyRandomCharacter = (char)myRandomCharacter;
private boolean isRandomGeneratorOn;

private final int MIN = 65;
char m = (char)MIN;
private final int MAX = 26;
char x = (char)MAX;
private final String TAG = "Random Char Service: ";

private final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

private Context mContext;
private Random mRandom = new Random();

// Initialize a new BroadcastReceiver instance
private BroadcastReceiver mRandomCharReceiver = new BroadcastReceiver()

@Override
public void onReceive(Context context, Intent intent)
// Get the received random number
myRandomCharacter = intent.getIntExtra("RandomCharacter",-1);

// Display a notification that the broadcast received
Toast.makeText(context,"Received : " + myRandomCharacter,Toast.LENGTH_SHORT).show();

;

@Override
protected void onCreate(Bundle savedInstanceState)

requestWindowFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the application context
mContext = getApplicationContext();

btnStart = (Button) findViewById(R.id.StartButton);
btnStop = (Button) findViewById(R.id.StopButton);


myTV = (EditText)findViewById(R.id.RandomCharText);

// Register the local broadcast
LocalBroadcastManager.getInstance(mContext).registerReceiver(mRandomCharReceiver, new IntentFilter("BROADCAST_RANDOM_CHARACTER"));

// Change the action bar color
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFFF00BF")));

// Set a click listener for start button
btnStart.setOnClickListener(new View.OnClickListener()

@Override
public void onClick(View view)

isServiceOn = true;

serviceIntent = new Intent(getApplicationContext(), RandomCharacterService.class);
startService(serviceIntent);
setRandomNumber();
// Generate a random char
myRandomCharacter = new Random().nextInt(x)+m;

// Initialize a new intent instance
Intent intent = new Intent("BROADCAST_RANDOM_CHARACTER");
// Put the random character to intent to broadcast it
intent.putExtra("RandomCharacter",myRandomCharacter);

// Send the broadcast
LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);

// Update the TextView with random character
myTV.setText(" " + myRandomCharacter );

);

btnStop.setOnClickListener(new View.OnClickListener()

@Override
public void onClick(View view)

isServiceOn = false;

stopService(serviceIntent);

);

private void setRandomNumber()

myTV.setText("Random Character: " + (char)myService.getRandomCharacter());
String alphabet = myTV.getText().toString();






RandomCharacterService.java:



 package com.example.cs7455rehmarazzaklab8;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.Random;


public class RandomCharacterService extends Service

private int myRandomCharacter;
char MyRandomCharacter = (char)myRandomCharacter;
private boolean isRandomGeneratorOn;

private final int MIN = 65;
char m = (char)MIN;
private final int MAX = 26;
char x = (char)MAX;
private final String TAG = "Random Char Service: ";

private final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

class RandomCharacterServiceBinder extends Binder
public RandomCharacterService getService()

return RandomCharacterService.this;



private IBinder myBinder = new RandomCharacterServiceBinder();

@Override
public int onStartCommand(Intent intent, int flags, int startId)

Log.i(TAG, "In OnStartCommand Thread ID is "+Thread.currentThread().getId());
isRandomGeneratorOn = true;

new Thread(new Runnable()

@Override
public void run()

startRandomGenerator();


).start();

return START_STICKY;


private void startRandomGenerator()

while(isRandomGeneratorOn)

char alphabet = 'A';
for (int i = 65; i < 90; i++)

try

Thread.sleep(1000);
if(isRandomGeneratorOn)

alphabet++;
myRandomCharacter = new Random().nextInt(x)+m;
Log.i(TAG, "Thread ID is "+Thread.currentThread().getId() + ", Random character is "+(char)myRandomCharacter);


catch(InterruptedException e)

Log.i(TAG, "Thread Interrupted.");








private void stopRandomGenerator()

isRandomGeneratorOn = false;


public int getRandomCharacter()

return myRandomCharacter;


public boolean isRandomGeneratorOn()
return isRandomGeneratorOn;


@Override
public void onDestroy()

super.onDestroy();
stopRandomGenerator();
Log.i(TAG, "Service Destroyed.");


@Nullable
@Override
public IBinder onBind(Intent intent)

Log.i(TAG, "In onBind ...");
return myBinder;




Call Stack:callstack from running the app



Call Stack from attempting to press the stop button:crash from attempting to press stop button










share|improve this question
















Working on an app that is supposed to generate random characters via a broadcast. I need to broadcast the random characters generated by my custom service, so that the main activity registered to intercept the broadcast can get the random numbers and display them on an EditText. The layout is shown here: app layout



The start button will trigger the random character generator service. The EditText will display the random numbers generated in real time (without any button press). The stop button will stop the service. The EditText won’t display any numbers. I have created a service(RandomCharacterService) and registered it in my manifest. Upon running the app, my app crashes. I am sure it is because I did not register my broadcast in my manifest, but I do not understand how to do that. And perhaps there is something wrong with how I am handling the broadcast in my main activity. In my button click method for the start button, I tried to do a for-loop, but this resulted in the app crashing as well.



AndroidManifest.xml:



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.cs7455rehmarazzaklab8">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".RandomCharacterService"></service>

</application>




MainActivityjava:



 package com.example.cs7455rehmarazzaklab8;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
import java.util.Random;

public class MainActivity extends AppCompatActivity

private Button btnStart, btnStop;
private EditText myTV;

private Intent serviceIntent;
private RandomCharacterService myService;
private ServiceConnection myServiceConnection;
private boolean isServiceOn; //checks if the service is on

private int myRandomCharacter;
char MyRandomCharacter = (char)myRandomCharacter;
private boolean isRandomGeneratorOn;

private final int MIN = 65;
char m = (char)MIN;
private final int MAX = 26;
char x = (char)MAX;
private final String TAG = "Random Char Service: ";

private final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

private Context mContext;
private Random mRandom = new Random();

// Initialize a new BroadcastReceiver instance
private BroadcastReceiver mRandomCharReceiver = new BroadcastReceiver()

@Override
public void onReceive(Context context, Intent intent)
// Get the received random number
myRandomCharacter = intent.getIntExtra("RandomCharacter",-1);

// Display a notification that the broadcast received
Toast.makeText(context,"Received : " + myRandomCharacter,Toast.LENGTH_SHORT).show();

;

@Override
protected void onCreate(Bundle savedInstanceState)

requestWindowFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the application context
mContext = getApplicationContext();

btnStart = (Button) findViewById(R.id.StartButton);
btnStop = (Button) findViewById(R.id.StopButton);


myTV = (EditText)findViewById(R.id.RandomCharText);

// Register the local broadcast
LocalBroadcastManager.getInstance(mContext).registerReceiver(mRandomCharReceiver, new IntentFilter("BROADCAST_RANDOM_CHARACTER"));

// Change the action bar color
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFFF00BF")));

// Set a click listener for start button
btnStart.setOnClickListener(new View.OnClickListener()

@Override
public void onClick(View view)

isServiceOn = true;

serviceIntent = new Intent(getApplicationContext(), RandomCharacterService.class);
startService(serviceIntent);
setRandomNumber();
// Generate a random char
myRandomCharacter = new Random().nextInt(x)+m;

// Initialize a new intent instance
Intent intent = new Intent("BROADCAST_RANDOM_CHARACTER");
// Put the random character to intent to broadcast it
intent.putExtra("RandomCharacter",myRandomCharacter);

// Send the broadcast
LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);

// Update the TextView with random character
myTV.setText(" " + myRandomCharacter );

);

btnStop.setOnClickListener(new View.OnClickListener()

@Override
public void onClick(View view)

isServiceOn = false;

stopService(serviceIntent);

);

private void setRandomNumber()

myTV.setText("Random Character: " + (char)myService.getRandomCharacter());
String alphabet = myTV.getText().toString();






RandomCharacterService.java:



 package com.example.cs7455rehmarazzaklab8;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.Random;


public class RandomCharacterService extends Service

private int myRandomCharacter;
char MyRandomCharacter = (char)myRandomCharacter;
private boolean isRandomGeneratorOn;

private final int MIN = 65;
char m = (char)MIN;
private final int MAX = 26;
char x = (char)MAX;
private final String TAG = "Random Char Service: ";

private final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

class RandomCharacterServiceBinder extends Binder
public RandomCharacterService getService()

return RandomCharacterService.this;



private IBinder myBinder = new RandomCharacterServiceBinder();

@Override
public int onStartCommand(Intent intent, int flags, int startId)

Log.i(TAG, "In OnStartCommand Thread ID is "+Thread.currentThread().getId());
isRandomGeneratorOn = true;

new Thread(new Runnable()

@Override
public void run()

startRandomGenerator();


).start();

return START_STICKY;


private void startRandomGenerator()

while(isRandomGeneratorOn)

char alphabet = 'A';
for (int i = 65; i < 90; i++)

try

Thread.sleep(1000);
if(isRandomGeneratorOn)

alphabet++;
myRandomCharacter = new Random().nextInt(x)+m;
Log.i(TAG, "Thread ID is "+Thread.currentThread().getId() + ", Random character is "+(char)myRandomCharacter);


catch(InterruptedException e)

Log.i(TAG, "Thread Interrupted.");








private void stopRandomGenerator()

isRandomGeneratorOn = false;


public int getRandomCharacter()

return myRandomCharacter;


public boolean isRandomGeneratorOn()
return isRandomGeneratorOn;


@Override
public void onDestroy()

super.onDestroy();
stopRandomGenerator();
Log.i(TAG, "Service Destroyed.");


@Nullable
@Override
public IBinder onBind(Intent intent)

Log.i(TAG, "In onBind ...");
return myBinder;




Call Stack:callstack from running the app



Call Stack from attempting to press the stop button:crash from attempting to press stop button







java android random broadcastreceiver






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 20:11







Amma

















asked Mar 8 at 18:57









AmmaAmma

75




75












  • You should include the call stack for the crash you're running into.

    – Advice-Dog
    Mar 8 at 19:25











  • Noted, and included!

    – Amma
    Mar 8 at 20:11











  • 1. You don't initialize myService in the activity so it will always throw an NPE. 2. You have a race condition you use serviceIntent in one button press but initialize it in another. There is, currently, no guarantee that the buttons will be pressed in a specific order.

    – Ge3ng
    Mar 8 at 21:16











  • Oh I see. So how would i initialize myService?

    – Amma
    Mar 8 at 21:36

















  • You should include the call stack for the crash you're running into.

    – Advice-Dog
    Mar 8 at 19:25











  • Noted, and included!

    – Amma
    Mar 8 at 20:11











  • 1. You don't initialize myService in the activity so it will always throw an NPE. 2. You have a race condition you use serviceIntent in one button press but initialize it in another. There is, currently, no guarantee that the buttons will be pressed in a specific order.

    – Ge3ng
    Mar 8 at 21:16











  • Oh I see. So how would i initialize myService?

    – Amma
    Mar 8 at 21:36
















You should include the call stack for the crash you're running into.

– Advice-Dog
Mar 8 at 19:25





You should include the call stack for the crash you're running into.

– Advice-Dog
Mar 8 at 19:25













Noted, and included!

– Amma
Mar 8 at 20:11





Noted, and included!

– Amma
Mar 8 at 20:11













1. You don't initialize myService in the activity so it will always throw an NPE. 2. You have a race condition you use serviceIntent in one button press but initialize it in another. There is, currently, no guarantee that the buttons will be pressed in a specific order.

– Ge3ng
Mar 8 at 21:16





1. You don't initialize myService in the activity so it will always throw an NPE. 2. You have a race condition you use serviceIntent in one button press but initialize it in another. There is, currently, no guarantee that the buttons will be pressed in a specific order.

– Ge3ng
Mar 8 at 21:16













Oh I see. So how would i initialize myService?

– Amma
Mar 8 at 21:36





Oh I see. So how would i initialize myService?

– Amma
Mar 8 at 21:36












1 Answer
1






active

oldest

votes


















0














Since you are using the bound service (using Ibinder). You will have to start the service by calling bindService instead of startService. But before that you need to initialize your ServiceConnection variable and better use the isServiceOn boolean as in the below example.



private ServiceConnection myServiceConnection = new ServiceConnection() 
@Override
// IBinder interface is through which we receive the service object for communication.
public void onServiceConnected(ComponentName name, IBinder binder)
RandomCharacterServiceBinder myBinder = (RandomCharacterServiceBinder) binder;
isServiceOn = true;
myService = myBinder.getService();
Toast.makeText(context,"Service connected", Toast.LENGTH_SHORT).show();


@Override
public void onServiceDisconnected(ComponentName name)
isServiceOn = false;
myService = null;

;


After onServiceConnected is called, you will get your service object. Most probably your service will be initialized before you perform a click. But just to ensure you can TOAST some message within it.



And you should start the service in Activity's onCreate method, so service will get some time in creation. So move the below code from you click listener to onCreate method.



serviceIntent = new Intent(getApplicationContext(), RandomCharacterService.class);
// startService(serviceIntent); <-- remove this line, call bindService
bindService(intent, myServiceConnection, Context.BIND_AUTO_CREATE);


and wait for the service connection Toast to appear.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55069367%2fgenerate-random-characters-in-android-studio-using-broadcast%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Since you are using the bound service (using Ibinder). You will have to start the service by calling bindService instead of startService. But before that you need to initialize your ServiceConnection variable and better use the isServiceOn boolean as in the below example.



    private ServiceConnection myServiceConnection = new ServiceConnection() 
    @Override
    // IBinder interface is through which we receive the service object for communication.
    public void onServiceConnected(ComponentName name, IBinder binder)
    RandomCharacterServiceBinder myBinder = (RandomCharacterServiceBinder) binder;
    isServiceOn = true;
    myService = myBinder.getService();
    Toast.makeText(context,"Service connected", Toast.LENGTH_SHORT).show();


    @Override
    public void onServiceDisconnected(ComponentName name)
    isServiceOn = false;
    myService = null;

    ;


    After onServiceConnected is called, you will get your service object. Most probably your service will be initialized before you perform a click. But just to ensure you can TOAST some message within it.



    And you should start the service in Activity's onCreate method, so service will get some time in creation. So move the below code from you click listener to onCreate method.



    serviceIntent = new Intent(getApplicationContext(), RandomCharacterService.class);
    // startService(serviceIntent); <-- remove this line, call bindService
    bindService(intent, myServiceConnection, Context.BIND_AUTO_CREATE);


    and wait for the service connection Toast to appear.






    share|improve this answer



























      0














      Since you are using the bound service (using Ibinder). You will have to start the service by calling bindService instead of startService. But before that you need to initialize your ServiceConnection variable and better use the isServiceOn boolean as in the below example.



      private ServiceConnection myServiceConnection = new ServiceConnection() 
      @Override
      // IBinder interface is through which we receive the service object for communication.
      public void onServiceConnected(ComponentName name, IBinder binder)
      RandomCharacterServiceBinder myBinder = (RandomCharacterServiceBinder) binder;
      isServiceOn = true;
      myService = myBinder.getService();
      Toast.makeText(context,"Service connected", Toast.LENGTH_SHORT).show();


      @Override
      public void onServiceDisconnected(ComponentName name)
      isServiceOn = false;
      myService = null;

      ;


      After onServiceConnected is called, you will get your service object. Most probably your service will be initialized before you perform a click. But just to ensure you can TOAST some message within it.



      And you should start the service in Activity's onCreate method, so service will get some time in creation. So move the below code from you click listener to onCreate method.



      serviceIntent = new Intent(getApplicationContext(), RandomCharacterService.class);
      // startService(serviceIntent); <-- remove this line, call bindService
      bindService(intent, myServiceConnection, Context.BIND_AUTO_CREATE);


      and wait for the service connection Toast to appear.






      share|improve this answer

























        0












        0








        0







        Since you are using the bound service (using Ibinder). You will have to start the service by calling bindService instead of startService. But before that you need to initialize your ServiceConnection variable and better use the isServiceOn boolean as in the below example.



        private ServiceConnection myServiceConnection = new ServiceConnection() 
        @Override
        // IBinder interface is through which we receive the service object for communication.
        public void onServiceConnected(ComponentName name, IBinder binder)
        RandomCharacterServiceBinder myBinder = (RandomCharacterServiceBinder) binder;
        isServiceOn = true;
        myService = myBinder.getService();
        Toast.makeText(context,"Service connected", Toast.LENGTH_SHORT).show();


        @Override
        public void onServiceDisconnected(ComponentName name)
        isServiceOn = false;
        myService = null;

        ;


        After onServiceConnected is called, you will get your service object. Most probably your service will be initialized before you perform a click. But just to ensure you can TOAST some message within it.



        And you should start the service in Activity's onCreate method, so service will get some time in creation. So move the below code from you click listener to onCreate method.



        serviceIntent = new Intent(getApplicationContext(), RandomCharacterService.class);
        // startService(serviceIntent); <-- remove this line, call bindService
        bindService(intent, myServiceConnection, Context.BIND_AUTO_CREATE);


        and wait for the service connection Toast to appear.






        share|improve this answer













        Since you are using the bound service (using Ibinder). You will have to start the service by calling bindService instead of startService. But before that you need to initialize your ServiceConnection variable and better use the isServiceOn boolean as in the below example.



        private ServiceConnection myServiceConnection = new ServiceConnection() 
        @Override
        // IBinder interface is through which we receive the service object for communication.
        public void onServiceConnected(ComponentName name, IBinder binder)
        RandomCharacterServiceBinder myBinder = (RandomCharacterServiceBinder) binder;
        isServiceOn = true;
        myService = myBinder.getService();
        Toast.makeText(context,"Service connected", Toast.LENGTH_SHORT).show();


        @Override
        public void onServiceDisconnected(ComponentName name)
        isServiceOn = false;
        myService = null;

        ;


        After onServiceConnected is called, you will get your service object. Most probably your service will be initialized before you perform a click. But just to ensure you can TOAST some message within it.



        And you should start the service in Activity's onCreate method, so service will get some time in creation. So move the below code from you click listener to onCreate method.



        serviceIntent = new Intent(getApplicationContext(), RandomCharacterService.class);
        // startService(serviceIntent); <-- remove this line, call bindService
        bindService(intent, myServiceConnection, Context.BIND_AUTO_CREATE);


        and wait for the service connection Toast to appear.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 9 at 8:21









        Rick SanchezRick Sanchez

        8702717




        8702717





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55069367%2fgenerate-random-characters-in-android-studio-using-broadcast%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme