Generate Random Characters in Android Studio using Broadcast Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!How 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”?

Is there such thing as an Availability Group failover trigger?

When the Haste spell ends on a creature, do attackers have advantage against that creature?

Is safe to use va_start macro with this as parameter?

また usage in a dictionary

How to convince students of the implication truth values?

First console to have temporary backward compatibility

Why do we bend a book to keep it straight?

Why aren't air breathing engines used as small first stages

Do square wave exist?

What are the out-of-universe reasons for the references to Toby Maguire-era Spider-Man in ITSV

Is CEO the profession with the most psychopaths?

What is the meaning of the simile “quick as silk”?

Can you use the Shield Master feat to shove someone before you make an attack by using a Readied action?

How do I find out the mythology and history of my Fortress?

Is grep documentation wrong?

What do you call the main part of a joke?

How could we fake a moon landing now?

How to tell that you are a giant?

Can a new player join a group only when a new campaign starts?

What does "lightly crushed" mean for cardamon pods?

Is there any way for the UK Prime Minister to make a motion directly dependent on Government confidence?

What causes the direction of lightning flashes?

Around usage results

Why are both D and D# fitting into my E minor key?



Generate Random Characters in Android Studio using Broadcast



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!How 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”?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








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









        GirishGirish

        9902717




        9902717





























            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

            1928 у кіно

            Захаров Федір Захарович

            Ель Греко