Android Studio - Voice search - Crashing on saying number 2 and 4 - java

I have an activity that has voice function. which lets you say 4 words and these words are added into an array. I am want only the second and the last word.
I am converting the second word into a string and the last word into an int (last word is always a number from 1-5).
The code is working fine as long as I don't say 2 or 4. as soon I say those two numbers the app crashes.
how can I fix this?
I tried of thinking of inserting an if statement. for example - if string contains word for, four then it = 4. (rough code).
I have posted the code and stack trace below.
public class Report extends AppCompatActivity {
private static final int REQ_CODE_SPEECH_INPUT = 100;
private TextView mVoiceInputTv;
private ImageButton mSpeakBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.report);
mVoiceInputTv = (TextView) findViewById(R.id.voiceInput);
mSpeakBtn = (ImageButton) findViewById(R.id.btnSpeak);
mSpeakBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startVoiceInput();
}
});
final String carreg = mVoiceInputTv.getText().toString();
}
private void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "e.g- Report fpg563 rating 3");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mVoiceInputTv.setText(result.get(0));
}
break;
}
}
if(mVoiceInputTv.getText().toString().contains("report")) {
input();
}
}
public void input() {
String test = mVoiceInputTv.getText().toString();
String[] ms = test.split(" ");
List<String> selectedWords = new ArrayList<>();
for (int i = 0; i < ms.length; i++) {
selectedWords.add(ms[i]);
final String carreg = ms[1];
final String newrating = ms[3];
final int rating = Integer.parseInt(newrating);
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(Report.this, Report.class);
Report.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Report.this);
builder.setMessage("Reporting Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Report_request registerRequest = new Report_request(carreg, rating, responseListener);
RequestQueue queue = Volley.newRequestQueue(Report.this);
queue.add(registerRequest);
}
}
}
Stack Trace:
10-25 17:45:41.449 32501-32501/com.example.naveen.loginregister E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.naveen.loginregister, PID: 32501
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=Intent { launchParam=MultiScreenLaunchParams { mDisplayId=0 mFlags=0 }(has extras) }} to activity {com.example.naveen.loginregister/com.example.naveen.loginregister.Report}: java.lang.NumberFormatException: For input string: "for"
at android.app.ActivityThread.deliverResults(ActivityThread.java:4472)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4515)
at android.app.ActivityThread.-wrap22(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1687)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Caused by: java.lang.NumberFormatException: For input string: "for"
at java.lang.Integer.parseInt(Integer.java:521)
at java.lang.Integer.parseInt(Integer.java:556)
at com.example.naveen.loginregister.Report.input(Report.java:103)
at com.example.naveen.loginregister.Report.onActivityResult(Report.java:85)
at android.app.Activity.dispatchActivityResult(Activity.java:7256)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4468)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4515) 
at android.app.ActivityThread.-wrap22(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1687) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6682) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410) 
whats up with this downvotes? im asking an honest question. ofcourse the grammer might be bad. but im still learning english. u want me to go to a english classs before i post a question?

This is must be happening because 2 is also the word "to" or "too" which is not going to be convertable into an int unless you are catching those cases. Similarly, as you pointed out 4 is probably being converted to the word "for" which again won't convert to an int unless you specifically catch that case.
I think you're on the right track, catching those cases where the voice to text is going to hand you a word that sounds like a number but isn't one.
BUT if you want your code to not crash you need to prepare for any possible input. So you should be catching the exception if it is thrown and then doing the right thing.
try {
final int rating = Integer.parseInt(newrating);
} catch ( NumberFormatException e ) {
//uhoh couldn't get the number
//prompt the user to try again or
//do something else that makes sense
}

Related

NumberFormatException For Input String "4018.B"

The following code comes from a Android App for Handheld Scanner Device; the Device should scan different Barcodes and QR codes, different digit ranges, numbers and digits;
that´s why I decided to go with .matcher instead of Regular Expressions; The following code works fine when it comes to parse combinations like "1367+700" etc.:
editBarcode.setOnClickListener(new View.OnClickListener() { //tv is the TextView.
public void onClick(View v) {
code = editBarcode.getText().toString();
XXXStorageApp.getInstance().setScannedCode(code);
editBarcode.setText("");
if (ScanService.checkEnteredCode(code, basic, content, MainDetailActivity.this) == true) {
return;
}
else {
Pattern p = Pattern.compile(code);
Matcher matcher = p.matcher(Pattern.quote("\\+"));
if (matcher.find()){
retrievedItemNo = String.valueOf(matcher);
}
String intermediateItemNo = code;
String[] splitString = intermediateItemNo.split(Pattern.quote("+"));
retrievedItemNo = splitString [0];
String intermediateString = code.substring(code.indexOf("+") + 1);
retrievedQuantity = intermediateString.split("\\+")[0];
if(XXXStorageApp.getInstance().NoList.contains(retrievedItemNo) || XXXStorageApp.getInstance().EanList.contains(scannedCode)){
Log.d(String.valueOf(XXXStorageApp.getInstance().NoList),"NoList");
Log.d(String.valueOf(XXXStorageApp.getInstance().EanList),"EanList");
}
else {
Log.d(String.valueOf(XXXStorageApp.getInstance().NoList),"NoList");
Log.d(String.valueOf(XXXStorageApp.getInstance().EanList),"EanList");
Vibrator vibrator;
vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(3000);
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
Toast.makeText(getApplicationContext(), R.string.not_in_database, Toast.LENGTH_LONG).show();
return;
}
if (!addBooking.isEnabled() == true && removeBooking.isEnabled())
{
AddBookingMessage message = new AddBookingMessage();
message.setType("add-item-to-pallet");
message.setPalNo(receivedPalNo);
message.setItem(retrievedItemNo);
if (String.valueOf(retrievedQuantity).matches("") ||
retrievedQuantity == null ||
retrievedQuantity.trim().isEmpty()) {
final Dialog dialog = new Dialog(MainDetailActivity.this, 0);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.sortiment_layout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
TextView textView = dialog.findViewById(R.id.textView4);
Button okButton = dialog.findViewById(R.id.ok);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
retrievedQuantity = textView.getText().toString();
message.setQuantity(Integer.valueOf(retrievedQuantity));
message.setSource(source);
message.setTime(time);
RestClient.putBookingOnPallet(basic, message, MainDetailActivity.this);
dialog.dismiss();
}
});
Button cancelButton = dialog.findViewById(R.id.cancel);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
else
{
message.setQuantity(Integer.valueOf(retrievedQuantity));
message.setSource(source);
message.setTime(time);
RestClient.putBookingOnPallet(basic, message, MainDetailActivity.this);
}
}
if (addBooking.isEnabled() && !removeBooking.isEnabled() == true)
{
AddBookingMessage message = new AddBookingMessage();
message.setType("remove-item-from-pallet");
message.setPalNo(receivedPalNo);
message.setItem(retrievedItemNo);
message.setEan(scannedCode);
if (spinner != null && spinner.getSelectedItem() != null) {
source = spinner.getSelectedItem().toString();
}
if (String.valueOf(retrievedQuantity).matches("") || retrievedQuantity == null
|| retrievedQuantity.trim().isEmpty())
{
final Dialog enterDialog = new Dialog(MainDetailActivity.this, 0);
enterDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
enterDialog.setCancelable(true);
enterDialog.setContentView(R.layout.sortiment_layout);
enterDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
TextView enterQuantityView = enterDialog.findViewById(R.id.textView4);
Button okQuantityButton = enterDialog.findViewById(R.id.ok);
okQuantityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
retrievedQuantity = enterQuantityView.getText().toString();
message.setQuantity(Integer.valueOf(retrievedQuantity));
message.setSource(source);
message.setTime(time);
RestClient.removeItemFromPallet(basic, message, MainDetailActivity.this);
enterDialog.dismiss();
}
});
Button cancelQuantityButton = enterDialog.findViewById(R.id.cancel);
cancelQuantityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
enterDialog.dismiss();
}
});
enterDialog.show();
}
else {
message.setQuantity(Integer.valueOf(retrievedQuantity));
message.setSource(source);
message.setTime(time);
RestClient.removeItemFromPallet(basic, message, MainDetailActivity.this);
}
}
editBarcode.setText("");
}}
however the App crashes with a
java.lang.NumberFormatException: For input string: "4018.B"
So, the problem here is to parse a string like "4018.B+95".
I don´t know how to handle this mixed input String with .matcher and definitely don´t want to use a Regular Expression; so basically, all of the following Input Strings - including Type conversion - should be handled correctly:
1256+70
1235.B+70
1256+70+DB
1235.B+70+DB
1256+70+DB2020-123
1235.B+70+DB2020-123
1256+0+DB2020-123
1235.B+0+DB2020-123
So, basically I need a condition for .matcher() that handles input like
"1235.B"
a mixed Integer and String; I need to store it in one variable which is of type String;
the problem here is that the "." in "1235.B" is not recognized and the App crashes hence, because the Number contains a string (".B")
So, two questions here:
How can I use .matcher() to recognize if a String contains ".B" or ".C" or anything similar?
How do I handle the different Types correctly in one Variable type?
As I am stuck with this, I would appreciate any hints or help.

Integer putExtra() in Intent Data is being set as ParcelledData causing AsyncTask exception?

I am running into an error when attempting to getExtras() from an intent. At the moment the Intent Data says its a ParcelledData piece but the argument I entered in the putExtra() method was actually of type int. This causes an exception when during the doIntBackground() process.
Application Context
Flow.java is a container for items called flowElements (aka. Tasks).
A Flow object has a LinkedList which keeps track of all its flowElements.
SandBoxMain.java is an activity where the user can see all the current flowElements in the Flow they are currently working on, or create a flowElement one.
ElementDesigner.java is an activity where the user can name and time their new flowElement.
Error
//// Not expecting a parcel, expecting an integer ////
D/nhacks16.flow.Main.ElementDesigner: intent data is: Bundle[mParcelledData.dataSize=24]
D/nhacks16.flow D/nhacks16.flow.Main.ElementDesigner: Element's name is Task 1
D/nhacks16.flow D/nhacks16.flow.Main.ElementDesigner: Element's time is 20
D/nhacks16.flow D/nhacks16.flow.Main.ElementDesigner: Element's time is minutes
D/nhacks16.flow E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: nhacks16.flow, PID: 21352
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NumberFormatException: Invalid int: "Bundle[mParcelledData.dataSize=24]"
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parse(Integer.java:410)
at java.lang.Integer.parseInt(Integer.java:367)
at java.lang.Integer.parseInt(Integer.java:334)
at nhacks16.flow.Main.ElementDesigner$newElemAsync.doInBackground(ElementDesigner.java:104)
at nhacks16.flow.Main.ElementDesigner$newElemAsync.doInBackground(ElementDesigner.java:91)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
SandBoxMain.java
public class SandBoxMain extends AppCompatActivity {
// The SandBox serves as a hub for a Flow Object. SandBox will:
// 1) Execute the elementDesigner activity
// 2) Draw the flowElements on its view
private static final String TAG = SandBoxMain.class.getName();
private Toolbar sbToolbar;
private Flow workingFlow;
// Flow currently being worked on
private FlowElement f;
// Global FlowElement holder
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
workingFlow = getIntent().getParcelableExtra("selectedFlow");
//This parcelable extra comes from a previous activity,
//it is a Flow object, which was selected from a ListView
setContentView(R.layout.activity_sand_box_main);
}
public void newElement(View view) {
//Instantiate a Blank Flow Element
// Add it in the Flow's LinkedList
// Get an id to pass to element designer.
f = new FlowElement();
workingFlow.addElement(f);
Log.d(TAG, "The number of Flow Elements in the current Flow is:"
+ workingFlow.getElementCount());
f.setId(workingFlow.findElement(f));
Log.d(TAG, "The the new blank element's Id is: "
+ f.getId());
Intent in = new Intent(SandBoxMain.this, ElementDesigner.class);
//\\~~~~~~ TROUBLE AREA ~~~~~~~//\\
in.putExtra("id", f.getId());
//Passes the element's id (position in the LinkedList) to the
//Element Designer
\\// ~~~~~~~~~~~~~~~~~~~~~~~~~ \\//
startActivityForResult(in, 1);
//Starts new activity waiting for the return data
}
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
ElementDesigner.java
public class ElementDesigner extends AppCompatActivity {
// This class is the activity for the flow element designer, where the
// User can name and time the new task element
// This class will create the object and assign it the inputted properties,
// Then pass them back to the SandboxMain to draw and store
private static final String TAG = ElementDesigner.class.getName();
public void saveElement(View view) {
EditText nameInput = (EditText)findViewById(R.id.nameInput);
EditText timeInput = (EditText)findViewById(R.id.timeInput);
String elementName = nameInput.getText().toString();
String elementTime = timeInput.getText().toString();
String timeUnits = selectTime.getSelectedItem().toString();
//\\ ~~~~~~ TROUBLE AREA ~~~~~~~ //\\
String elementId = getIntent().getExtras().toString();
Log.d(TAG, "intent data is: " + elementId);
\\// ~~~~~~~~~~~~~~~~~~~~~~~~~ \\//
try {
new newElemAsync().execute(elementName, elementTime,
timeUnits, elementId);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
//Runs Async task to create a new FlowElement Object using user's inputs
private class newElemAsync extends AsyncTask<String, String,
FlowElement> {
#Override
protected FlowElement doInBackground(String... params) {
String elementName = params[0];
Log.d(TAG, "Element's name is " + params[0]);
Double elementTime = Double.parseDouble(params[1]);
Log.d(TAG, "Element's time is " + params[1]);
String timeUnits = params[2];
Log.d(TAG, "Element's time is " + params[2]);
//\\ ~~~~~~~~ TROUBLE AREA ~~~~~~~~ //\\
int elementId = Integer.parseInt(params[3]);
Log.d(TAG, "Element's id is " + params[3]);
\\// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \\//
FlowElement newElement = new FlowElement(elementName, elementTime, timeUnits, elementId);
return newElement;
}
#Override
protected void onPostExecute(FlowElement newElem) {
Intent returnData = new Intent();
returnData.putExtra("newElement", newElem);
setResult(1,returnData);
finish();
}
}
}
Flow.java
public class Flow implements Parcelable{
private static final String TAG = Flow.class.getName();
private String name;
private List<FlowElement> childFlowElements = new
LinkedList<FlowElement>();
public int findElement(FlowElement element) {
Log.d(TAG, "The element was found at index: " +
childFlowElements.indexOf(element) +
" in the Flow's childFlowElements LinkedList");
return childFlowElements.indexOf(element);
}
public void addElement(FlowElement newElement) {
childFlowElements.add(newElement);
}
}
edit; please note I removed the OnCreate Methods, for the sake post length!
Invalid int: "Bundle[mParcelledData.dataSize=24]"
is the returned value of Bundle.toString(); which is, indeed, not a valid int. It means that in your code, you have
Integer.parseInt(bundle.toString());
E.g. could be the returned value of getIntent().getExtras();
Integer.parseInt(getIntent().getExtras().toString());
You can think of the Bundle as a key-value map. So if you are adding a value using one of its put (putInt) method, you have to use one of its get (getInt) method to retrieve it

LibGDX/Google Play Services Error

I have been trying to implement Google Play Services into my LibGDX game, and have been using the real-time Multiplayer APK.
However, after everyone has joined the room through auto-matching, I try to start the game through calling a method to change the screen, but i get the error as followed. Even if i removed the contents of the method, the same error still occurs. Could anyone enlighten me?
Thank you!
The error logged in the console is ,
java.lang.RuntimeException: Failure delivering result
ResultInfo{who=null, request=10002, result=-1, data=Intent { (has
extras) }} to activity
{com.mygdx.game/com.mygdx.game.AndroidLauncher}:
java.lang.NullPointerException
Caused by: java.lang.NullPointerException
at com.mygdx.game.GSGameHelper.onActivityResult(GSGameHelper.java:76) -->
which points to this.game.multiplayerready()
Code as Follows:
public void onActivityResult(int request,int response, Intent data){
if (request == GSGameHelper.RC_WAITING_ROOM){
if (response == Activity.RESULT_CANCELED || response == GamesActivityResultCodes.RESULT_LEFT_ROOM ){
Games.RealTimeMultiplayer.leave(getApiClient(), this, mRoomID);
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
BaseGameUtils.showAlert(activity, "Left Room");
}else{
BaseGameUtils.showAlert(activity, "Game Starting!");
this.game.multiplayerGameReady();
}
}
else if (request == GSGameHelper.RC_SELECT_PLAYERS){
if (response != Activity.RESULT_OK) {
// user canceled
return;
}
// get the invitee list
Bundle extras = data.getExtras();
final ArrayList<String> invitees =
data.getStringArrayListExtra(Games.EXTRA_PLAYER_IDS);
// get auto-match criteria
Bundle autoMatchCriteria = null;
int minAutoMatchPlayers =
data.getIntExtra(Multiplayer.EXTRA_MIN_AUTOMATCH_PLAYERS, 0);
int maxAutoMatchPlayers =
data.getIntExtra(Multiplayer.EXTRA_MAX_AUTOMATCH_PLAYERS, 0);
Gdx.app.log("J", "Jmin" + minAutoMatchPlayers + " Jmax:" + maxAutoMatchPlayers);
for (String invitee : invitees){
Gdx.app.log("L" , invitee);
}
if (minAutoMatchPlayers > 0) {
autoMatchCriteria = RoomConfig.createAutoMatchCriteria(
minAutoMatchPlayers, maxAutoMatchPlayers, 0);
} else {
autoMatchCriteria = null;
}
// create the room and specify a variant if appropriate
RoomConfig.Builder roomConfigBuilder = makeBasicRoomConfigBuilder();
roomConfigBuilder.addPlayersToInvite(invitees);
if (autoMatchCriteria != null) {
roomConfigBuilder.setAutoMatchCriteria(autoMatchCriteria);
}
RoomConfig roomConfig = roomConfigBuilder.build();
Games.RealTimeMultiplayer.create(getApiClient(), roomConfig);
// prevent screen from sleeping during handshake
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}else{
super.onActivityResult(request, response, data);
}
}
public class MacroHardv2 extends ApplicationAdapter {
public void multiplayerGameReady(){
//gamew.multiplayer = true;
//Gdx.app.log("EMPEZANDO", "Starting Game");
//gsm.set(new PlayState(gsm));
//dispose();
}
}
This is where i initiate the class
public class AndroidLauncher extends AndroidApplication implements ActionResolver{
private GSGameHelper _gameHelper;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_gameHelper = new GSGameHelper(this, GameHelper.CLIENT_GAMES);
_gameHelper.enableDebugLog(false);
GameHelperListener gameHelperListerner = new GameHelper.GameHelperListener() {
#Override
public void onSignInSucceeded() {
// TODO Auto-generated method stub
}
#Override
public void onSignInFailed() {
// TODO Auto-generated method stub
}
};
_gameHelper.setup(gameHelperListerner);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();config.useImmersiveMode = true;
initialize(new MacroHardv2(this), config);
}
And The class constructor is as follows
public MacroHardv2(ActionResolver actionResolver) {
this.actionResolver = actionResolver;
actionResolver.setGame(this);
}
You are trying to call
this.game.multiplayerGameReady();
But you probably didn't set "this.game" anywhere. Where did you define your "game" object. Can you please show the code block that you define it and also set it, or instantiate it.
So "this.game" is your null object you trying to use.

Getting null point exception when i declare latlong values globally

I have got latlong values using shared preferences and stored it as double values.
Declared latlong values globally.
Getting null point Exception.
Tried different ways of declaring values globally,but nothing seems working.
MainActivity.java
public class MapsActivityConnect extends FragmentActivity {
ImageView emerg;
SharedPreferences pref;
String vechile;
Double deslatituded, deslongituded, srclatituded, srclongituded;
private GoogleMap mMap = null;
private final LatLng end = new LatLng(deslatituded, deslongituded);
private final LatLng start = new LatLng(srclatituded, srclongituded);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps_activity_connect);
pref = getSharedPreferences("gps", Context.MODE_PRIVATE);
Bundle extras = getIntent().getExtras();
if (extras != null) {
deslatituded = extras.getDouble("deslatitude");
deslongituded = extras.getDouble("deslongitude");
srclatituded = extras.getDouble("srclatitude");
srclongituded = extras.getDouble("srclongitude");
vechile = extras.getString("vechile");
if (!Utils.isConnected(getApplicationContext())) {
Toast.makeText(getApplicationContext(), "Internet not available. Cross check your internet connectivity and try again", Toast.LENGTH_LONG).show();
return;
}
if (!Utils.isGPSTurnOn(getApplicationContext())) {
showGPSDialog();
return;
}
}
}
#SuppressLint("NewApi")
#Override
protected void onResume() {
super.onResume();
if (Utils.isConnected(getApplicationContext())) {
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true);
final TextView txtDistance = (TextView) findViewById(R.id.txtSpeed);
new Routing(getParent(), mMap, txtDistance).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, start, end);
}
}
private void showGPSDialog() {
new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AppBaseTheme)) // Theme
.setTitle(R.string.gps_lable_gps) // setTitle
.setMessage(R.string.gps_lable_warning_message) // setMessage
.setInverseBackgroundForced(false).setCancelable(false) //
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(final DialogInterface dialog, final int which) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(final DialogInterface dialog, final int which) {
dialog.dismiss();
}
}).setIcon(android.R.drawable.ic_dialog_alert).show();
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Utils.isGPSTurnOn(getApplicationContext())) {
onResume();
}
}
}
Logcat
9-29 13:40:56.383 32078- 32149/zybo.example.ramz.demo_location_tracking V/RenderScript﹕ Application requested CPU execution
09-29 13:40:56.393 32078- 32149/zybo.example.ramz.demo_location_tracking V/RenderScript﹕ 0xb7579cd8 Launching thread(s), CPUs 4
09-29 13:41:01.527 32078-32078/zybo.example.ramz.demo_location_tracking D/AndroidRuntime﹕ Shutting down VM
09-29 13:41:01.536 32078-32078/zybo.example.ramz.demo_location_tracking E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: zybo.example.ramz.demo_location_tracking, PID: 32078
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{zybo.example.ramz.demo_location_tracking/zybo.example.ramz.demo_location_tracking.MapsActivityConnect}: java.lang.NullPointerException: Attempt to invoke virtual method 'double java.lang.Double.doubleValue()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2250)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413)
at android.app.ActivityThread.access$800(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'double java.lang.Double.doubleValue()' on a null object reference
at zybo.example.ramz.demo_location_tracking.MapsActivityConnect.<init>(MapsActivityConnect.java:62)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1089)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2240)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413)
at
android.app.ActivityThread.access$800(ActivityThread.java:155)
You need to initialize with values.
Double deslatituded, deslongituded, srclatituded, srclongituded;
You declare the doubles, but these are objects, not primitives. Therefore the default value is null. And the unboxing tries to get the primitive like
null.doubleValue()
Make them primitive or assign a default value like:
Double desLatituded = new Double(0);
I am not sure what is your error. But one of the scenario is
you declare class variables
private final LatLng end = new LatLng(deslatituded, deslongituded);
private final LatLng start = new LatLng(srclatituded, srclongituded);
Here deslatituded, deslongituded values must be null. Maybe this will the reason for the nullPoiner please check this.
You need to pass the values for this. Or just initialise the values like deslatituded=0 or something. This will save you from crash
Try this (and make sure your LatLng variables aren't final):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps_activity_connect);
pref = getSharedPreferences("gps", Context.MODE_PRIVATE);
Bundle extras = getIntent().getExtras();
if (extras != null) {
deslatituded = extras.getDouble("deslatitude");
deslongituded = extras.getDouble("deslongitude");
srclatituded = extras.getDouble("srclatitude");
srclongituded = extras.getDouble("srclongitude");
// NEW CODE
end = new LatLng(deslatituded, deslongituded);
start = new LatLng(srclatituded, srclongituded);
// END NEW CODE
vechile = extras.getString("vechile");
if (!Utils.isConnected(getApplicationContext())) {
Toast.makeText(getApplicationContext(), "Internet not available. Cross check your internet connectivity and try again", Toast.LENGTH_LONG).show();
return;
}
if (!Utils.isGPSTurnOn(getApplicationContext())) {
showGPSDialog();
return;
}
}
}
Please check if your extras has the key "deslatitude"
like:
if(getIntent().hasCategory("deslatitude"))
{
deslatituded = extras.getDouble("deslatitude");
}
Log.e(TAG, "deslatitude: " + deslatituded );
And if your log prints the valuew then check it for all (deslat,deslong,srclat,srclong)
Are there any values in
extras.getDouble("deslatitude");
extras.getDouble("deslongitude");
extras.getDouble("srclatitude");
extras.getDouble("srclongitude");
there is nothing in intent extras.

How to pass data in a class to another member?

I have this code and I am trying to pass this.thecost to the public void click() method but it looks like it is not working because I receive "Paymnet Failed" when click the paypal button.
What did i go wrong?
by the way, what do you call the private {}, private void {} - all those function() looking thing?
private void initUI(int theprice) {
launchPayPalButton = mPayPal.getCheckoutButton(this,
PayPal.BUTTON_278x43, CheckoutButton.TEXT_PAY);
LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.bottomMargin = theprice;
this.thecost = theprice;
launchPayPalButton.setLayoutParams(params);
launchPayPalButton.setOnClickListener(this);
((LinearLayout)findViewById(R.id.main_layout2)).addView(launchPayPalButton);
}
public void onClick(View v) {
payWithPaypal(this.thecost);
}
private void payWithPaypal(Integer gg) {
PayPalPayment newPayment = new PayPalPayment();
BigDecimal bigDecimal=new BigDecimal(gg);
newPayment.setSubtotal(bigDecimal);
newPayment.setCurrencyType(Currency.getInstance(Locale.US));
newPayment.setRecipient("email#hotmail.com");
newPayment.setMerchantName("My Merchant");
Intent paypalIntent = PayPal.getInstance().checkout(newPayment, this);
this.startActivityForResult(paypalIntent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(resultCode) {
case Activity.RESULT_OK:
String payKey = data.getStringExtra(PayPalActivity.EXTRA_PAY_KEY);
data.getStringExtra(PayPalActivity.EXTRA_PAY_KEY);
Toast.makeText(this,"Paymnet Successful",Toast.LENGTH_LONG).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(this,"Paymnet Cancel",Toast.LENGTH_LONG).show();
break;
case PayPalActivity.RESULT_FAILURE:
Toast.makeText(this,"Paymnet Failed",Toast.LENGTH_LONG).show();
String errorID =
data.getStringExtra(PayPalActivity.EXTRA_ERROR_ID);
String errorMessage =
data.getStringExtra(PayPalActivity.EXTRA_ERROR_MESSAGE);
break;
}
EDITED: I call initUI() at the oncreate method
EDITED AGAIN: I change the global variable to 'double' because the price usually have decimal place.
Now i tried to toast the value and i see the error much clearer. The toast display a message that the value that was passed is "0.0". And because of that, there is an error of 'Payment Failed' and invalid payment.
int eprice;
double thecost;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail);
//Data mSource = new Data;
Intent myLocalIntent = getIntent();
Bundle myBundle = myLocalIntent.getExtras();
eprice = myBundle.getInt("eprice");
String epricetxt = myBundle.getString("eprice");
Adapter mAdapter = new Adapter(this, mSource);
//details = (Data) mAdapter.getItem(pos);
TextView theprice = (TextView) findViewById(R.id.priceTxt);
theprice.setText("Price: $" + epricetxt);
this.setCost(eprice);
this.thecost = eprice;
//Paypal
mPayPal=PayPal.initWithAppID(this,Constants.PAYPAL_APP_ID,PayPal.ENV_SANDBOX);
initUI(eprice);
}
private void initUI(int theprice) {
launchPayPalButton = mPayPal.getCheckoutButton(this,
PayPal.BUTTON_278x43, CheckoutButton.TEXT_PAY);
LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.bottomMargin = theprice;
this.thecost = theprice;
launchPayPalButton.setLayoutParams(params);
launchPayPalButton.setOnClickListener(this);
((LinearLayout)findViewById(R.id.main_layout2)).addView(launchPayPalButton);
}
public void onClick(View v) {
//
payWithPaypal(getCost());
}
public void setCost(int cost) {
this.thecost = cost;
}
public double getCost() {
return this.thecost;
}
private void payWithPaypal(Double gg) {
PayPalPayment newPayment = new PayPalPayment();
Toast.makeText(getApplicationContext(),gg.toString(), Toast.LENGTH_LONG).show();
BigDecimal bigDecimal=new BigDecimal(gg);
newPayment.setSubtotal(bigDecimal);
newPayment.setCurrencyType(Currency.getInstance(Locale.US));
newPayment.setRecipient("email#hotmail.com");
newPayment.setMerchantName("My Merchant");
Intent paypalIntent = PayPal.getInstance().checkout(newPayment, this);
this.startActivityForResult(paypalIntent, 1);
}
We don't have enough information to tell you what went wrong here. For some reason, the PayPal API returned a failure status code. Maybe you don't have an internet connection?
Check the value of the error message string that you retrieved in this line:
String errorMessage = data.getStringExtra(PayPalActivity.EXTRA_ERROR_MESSAGE);
You can use the debugger to inspect it, or use the Log.e function in the Logger class to log it to Logcat so you can read it.
As for your second question:
by the way, what do you call the private {}, private void {} - all those function() looking thing?
In Java, those "function looking things" are called Methods.
EDIT: Okay, now that you've showed us your onCreate method, I can see where you are getting the value that you eventually pass to onInit here:
eprice = myBundle.getInt("eprice");
Doing this implies that you saved the value previously in the bundle in onSaveInstanceState(Bundle)
Did you do that? How does it get the value when you are starting the Activity for the first time?
Using my most updated code, I have no idea why my eprice doesn't work. But I have alternative solution. All i need to do is change
initUI(eprice);
initUI(Double.valueOf(epricetxt));

Categories

Resources