NumberFormatException For Input String "4018.B" - java

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.

Related

I have got a report of crushes java.lang.RuntimeException:

I tested my app at many devices without any problems, but I received many crushes reports from users.
Can you friends explain where the problem is? Some of the devices such as Samsung A7 gives the same crush, and I have one and does not give me any problem in the testing the app.
Thank you
Here is a report:
java.lang.RuntimeException:
at android.os.AsyncTask$AsyncFutureTask.done (AsyncTask.java:429)
at java.util.concurrent.FutureTask.finishCompletion (FutureTask.java:383)
at java.util.concurrent.FutureTask.setException (FutureTask.java:252)
at java.util.concurrent.FutureTask.run (FutureTask.java:271)
at android.os.AsyncTask$SerialExecutor$1.run (AsyncTask.java:292)
at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641)
at java.lang.Thread.run (Thread.java:929)
Caused by: java.lang.NullPointerException:
at android.util.Log.println_native (Native Method)
at android.util.Log.e (Log.java:265)
at com.waddan.quran.MediaP$Player1.doInBackground (MediaP.java:262)
at com.waddan.quran.MediaP$Player1.doInBackground (MediaP.java:231)
at android.os.AsyncTask$3.call (AsyncTask.java:389)
at java.util.concurrent.FutureTask.run (FutureTask.java:266)
The activity that makes the problem is MediaP, and here is its code:
public class MediaP extends AppCompatActivity {
private ImageView imagePlayPause;
private TextView textCurrentTime, textTotalDuration, tvTest;
private SeekBar playerSeekbar;
private Handler handler = new Handler();
public String kare, pageNum;
private Button btn_goback;
private ImageView img_showPage;
///***********************************************************
private boolean playPause;
private android.media.MediaPlayer mediaPlayer;
private ProgressDialog progressDialog;
private boolean initiaStage = true;
//************************************************************
private Integer[] images = {R.drawable.a604, R.drawable.a603, R.drawable.a602, R.drawable.a601, R.drawable.a600, R.drawable.a599, R.drawable.a598, R.drawable.a597, R.drawable.a596, R.drawable.a595, R.drawable.a594, R.drawable.a593, R.drawable.a592, R.drawable.a591, R.drawable.a590, R.drawable.a589, R.drawable.a588, R.drawable.a587, R.drawable.a586, R.drawable.a585, R.drawable.a584, R.drawable.a583, R.drawable.a582, R.drawable.a581, R.drawable.a580, R.drawable.a579, R.drawable.a578, R.drawable.a577, R.drawable.a576, R.drawable.a575, R.drawable.a574, R.drawable.a573, R.drawable.a572, R.drawable.a571, R.drawable.a570, R.drawable.a569, R.drawable.a568, R.drawable.a567, R.drawable.a566, R.drawable.a565, R.drawable.a564, R.drawable.a563, R.drawable.a562, R.drawable.a561, R.drawable.a560, R.drawable.a559, R.drawable.a558, R.drawable.a557, R.drawable.a556, R.drawable.a555, R.drawable.a554, R.drawable.a553, R.drawable.a552, R.drawable.a551, R.drawable.a550, R.drawable.a549, R.drawable.a548, R.drawable.a547, R.drawable.a546, R.drawable.a545, R.drawable.a544, R.drawable.a543, R.drawable.a542, R.drawable.a541, R.drawable.a540, R.drawable.a539, R.drawable.a538, R.drawable.a537, R.drawable.a536, R.drawable.a535, R.drawable.a534, R.drawable.a533, R.drawable.a532, R.drawable.a531, R.drawable.a530, R.drawable.a529, R.drawable.a528, R.drawable.a527, R.drawable.a526, R.drawable.a525, R.drawable.a524, R.drawable.a523, R.drawable.a522, R.drawable.a521, R.drawable.a520, R.drawable.a519, R.drawable.a518, R.drawable.a517, R.drawable.a516, R.drawable.a515, R.drawable.a514, R.drawable.a513, R.drawable.a512, R.drawable.a511, R.drawable.a510, R.drawable.a509, R.drawable.a508, R.drawable.a507, R.drawable.a506, R.drawable.a505, R.drawable.a504, R.drawable.a503, R.drawable.a502, R.drawable.a501, R.drawable.a500, R.drawable.a499, R.drawable.a498, R.drawable.a497, R.drawable.a496, R.drawable.a495, R.drawable.a494, R.drawable.a493, R.drawable.a492, R.drawable.a491, R.drawable.a490, R.drawable.a489, R.drawable.a488, R.drawable.a487, R.drawable.a486, R.drawable.a485, R.drawable.a484, R.drawable.a483, R.drawable.a482, R.drawable.a481, R.drawable.a480, R.drawable.a479, R.drawable.a478, R.drawable.a477, R.drawable.a476, R.drawable.a475, R.drawable.a474, R.drawable.a473, R.drawable.a472, R.drawable.a471, R.drawable.a470, R.drawable.a469, R.drawable.a468, R.drawable.a467, R.drawable.a466, R.drawable.a465, R.drawable.a464, R.drawable.a463, R.drawable.a462, R.drawable.a461, R.drawable.a460, R.drawable.a459, R.drawable.a458, R.drawable.a457, R.drawable.a456, R.drawable.a455, R.drawable.a454, R.drawable.a453, R.drawable.a452, R.drawable.a451, R.drawable.a450, R.drawable.a449, R.drawable.a448, R.drawable.a447, R.drawable.a446, R.drawable.a445, R.drawable.a444, R.drawable.a443, R.drawable.a442, R.drawable.a441, R.drawable.a440, R.drawable.a439, R.drawable.a438, R.drawable.a437, R.drawable.a436, R.drawable.a435, R.drawable.a434, R.drawable.a433, R.drawable.a432, R.drawable.a431, R.drawable.a430, R.drawable.a429, R.drawable.a428, R.drawable.a427, R.drawable.a426, R.drawable.a425, R.drawable.a424, R.drawable.a423, R.drawable.a422, R.drawable.a421, R.drawable.a420, R.drawable.a419, R.drawable.a418, R.drawable.a417, R.drawable.a416, R.drawable.a415, R.drawable.a414, R.drawable.a413, R.drawable.a412, R.drawable.a411, R.drawable.a410, R.drawable.a409, R.drawable.a408, R.drawable.a407, R.drawable.a406, R.drawable.a405, R.drawable.a404, R.drawable.a403, R.drawable.a402, R.drawable.a401, R.drawable.a400, R.drawable.a399, R.drawable.a398, R.drawable.a397, R.drawable.a396, R.drawable.a395, R.drawable.a394, R.drawable.a393, R.drawable.a392, R.drawable.a391, R.drawable.a390, R.drawable.a389, R.drawable.a388, R.drawable.a387, R.drawable.a386, R.drawable.a385, R.drawable.a384, R.drawable.a383, R.drawable.a382, R.drawable.a381, R.drawable.a380, R.drawable.a379, R.drawable.a378, R.drawable.a377, R.drawable.a376, R.drawable.a375, R.drawable.a374, R.drawable.a373, R.drawable.a372, R.drawable.a371, R.drawable.a370, R.drawable.a369, R.drawable.a368, R.drawable.a367, R.drawable.a366, R.drawable.a365, R.drawable.a364, R.drawable.a363, R.drawable.a362, R.drawable.a361, R.drawable.a360, R.drawable.a359, R.drawable.a358, R.drawable.a357, R.drawable.a356, R.drawable.a355, R.drawable.a354, R.drawable.a353, R.drawable.a352, R.drawable.a351, R.drawable.a350, R.drawable.a349, R.drawable.a348, R.drawable.a347, R.drawable.a346, R.drawable.a345, R.drawable.a344, R.drawable.a343, R.drawable.a342, R.drawable.a341, R.drawable.a340, R.drawable.a339, R.drawable.a338, R.drawable.a337, R.drawable.a336, R.drawable.a335, R.drawable.a334, R.drawable.a333, R.drawable.a332, R.drawable.a331, R.drawable.a330, R.drawable.a329, R.drawable.a328, R.drawable.a327, R.drawable.a326, R.drawable.a325, R.drawable.a324, R.drawable.a323, R.drawable.a322, R.drawable.a321, R.drawable.a320, R.drawable.a319, R.drawable.a318, R.drawable.a317, R.drawable.a316, R.drawable.a315, R.drawable.a314, R.drawable.a313, R.drawable.a312, R.drawable.a311, R.drawable.a310, R.drawable.a309, R.drawable.a308, R.drawable.a307, R.drawable.a306, R.drawable.a305, R.drawable.a304, R.drawable.a303, R.drawable.a302, R.drawable.a301, R.drawable.a300, R.drawable.a299, R.drawable.a298, R.drawable.a297, R.drawable.a296, R.drawable.a295, R.drawable.a294, R.drawable.a293, R.drawable.a292, R.drawable.a291, R.drawable.a290, R.drawable.a289, R.drawable.a288, R.drawable.a287, R.drawable.a286, R.drawable.a285, R.drawable.a284, R.drawable.a283, R.drawable.a282, R.drawable.a281, R.drawable.a280, R.drawable.a279, R.drawable.a278, R.drawable.a277, R.drawable.a276, R.drawable.a275, R.drawable.a274, R.drawable.a273, R.drawable.a272, R.drawable.a271, R.drawable.a270, R.drawable.a269, R.drawable.a268, R.drawable.a267, R.drawable.a266, R.drawable.a265, R.drawable.a264, R.drawable.a263, R.drawable.a262, R.drawable.a261, R.drawable.a260, R.drawable.a259, R.drawable.a258, R.drawable.a257, R.drawable.a256, R.drawable.a255, R.drawable.a254, R.drawable.a253, R.drawable.a252, R.drawable.a251, R.drawable.a250, R.drawable.a249, R.drawable.a248, R.drawable.a247, R.drawable.a246, R.drawable.a245, R.drawable.a244, R.drawable.a243, R.drawable.a242, R.drawable.a241, R.drawable.a240, R.drawable.a239, R.drawable.a238, R.drawable.a237, R.drawable.a236, R.drawable.a235, R.drawable.a234, R.drawable.a233, R.drawable.a232, R.drawable.a231, R.drawable.a230, R.drawable.a229, R.drawable.a228, R.drawable.a227, R.drawable.a226, R.drawable.a225, R.drawable.a224, R.drawable.a223, R.drawable.a222, R.drawable.a221, R.drawable.a220, R.drawable.a219, R.drawable.a218, R.drawable.a217, R.drawable.a216, R.drawable.a215, R.drawable.a214, R.drawable.a213, R.drawable.a212, R.drawable.a211, R.drawable.a210, R.drawable.a209, R.drawable.a208, R.drawable.a207, R.drawable.a206, R.drawable.a205, R.drawable.a204, R.drawable.a203, R.drawable.a202, R.drawable.a201, R.drawable.a200, R.drawable.a199, R.drawable.a198, R.drawable.a197, R.drawable.a196, R.drawable.a195, R.drawable.a194, R.drawable.a193, R.drawable.a192, R.drawable.a191, R.drawable.a190, R.drawable.a189, R.drawable.a188, R.drawable.a187, R.drawable.a186, R.drawable.a185, R.drawable.a184, R.drawable.a183, R.drawable.a182, R.drawable.a181, R.drawable.a180, R.drawable.a179, R.drawable.a178, R.drawable.a177, R.drawable.a176, R.drawable.a175, R.drawable.a174, R.drawable.a173, R.drawable.a172, R.drawable.a171, R.drawable.a170, R.drawable.a169, R.drawable.a168, R.drawable.a167, R.drawable.a166, R.drawable.a165, R.drawable.a164, R.drawable.a163, R.drawable.a162, R.drawable.a161, R.drawable.a160, R.drawable.a159, R.drawable.a158, R.drawable.a157, R.drawable.a156, R.drawable.a155, R.drawable.a154, R.drawable.a153, R.drawable.a152, R.drawable.a151, R.drawable.a150, R.drawable.a149, R.drawable.a148, R.drawable.a147, R.drawable.a146, R.drawable.a145, R.drawable.a144, R.drawable.a143, R.drawable.a142, R.drawable.a141, R.drawable.a140, R.drawable.a139, R.drawable.a138, R.drawable.a137, R.drawable.a136, R.drawable.a135, R.drawable.a134, R.drawable.a133, R.drawable.a132, R.drawable.a131, R.drawable.a130, R.drawable.a129, R.drawable.a128, R.drawable.a127, R.drawable.a126, R.drawable.a125, R.drawable.a124, R.drawable.a123, R.drawable.a122, R.drawable.a121, R.drawable.a120, R.drawable.a119, R.drawable.a118, R.drawable.a117, R.drawable.a116, R.drawable.a115, R.drawable.a114, R.drawable.a113, R.drawable.a112, R.drawable.a111, R.drawable.a110, R.drawable.a109, R.drawable.a108, R.drawable.a107, R.drawable.a106, R.drawable.a105, R.drawable.a104, R.drawable.a103, R.drawable.a102, R.drawable.a101, R.drawable.a100, R.drawable.a99, R.drawable.a98, R.drawable.a97, R.drawable.a96, R.drawable.a95, R.drawable.a94, R.drawable.a93, R.drawable.a92, R.drawable.a91, R.drawable.a90, R.drawable.a89, R.drawable.a88, R.drawable.a87, R.drawable.a86, R.drawable.a85, R.drawable.a84, R.drawable.a83, R.drawable.a82, R.drawable.a81, R.drawable.a80, R.drawable.a79, R.drawable.a78, R.drawable.a77, R.drawable.a76, R.drawable.a75, R.drawable.a74, R.drawable.a73, R.drawable.a72, R.drawable.a71, R.drawable.a70, R.drawable.a69, R.drawable.a68, R.drawable.a67, R.drawable.a66, R.drawable.a65, R.drawable.a64, R.drawable.a63, R.drawable.a62, R.drawable.a61, R.drawable.a60, R.drawable.a59, R.drawable.a58, R.drawable.a57, R.drawable.a56, R.drawable.a55, R.drawable.a54, R.drawable.a53, R.drawable.a52, R.drawable.a51, R.drawable.a50, R.drawable.a49, R.drawable.a48, R.drawable.a47, R.drawable.a46, R.drawable.a45, R.drawable.a44, R.drawable.a43, R.drawable.a42, R.drawable.a41, R.drawable.a40, R.drawable.a39, R.drawable.a38, R.drawable.a37, R.drawable.a36, R.drawable.a35, R.drawable.a34, R.drawable.a33, R.drawable.a32, R.drawable.a31, R.drawable.a30, R.drawable.a29, R.drawable.a28, R.drawable.a27, R.drawable.a26, R.drawable.a25, R.drawable.a24, R.drawable.a23, R.drawable.a22, R.drawable.a21, R.drawable.a20, R.drawable.a19, R.drawable.a18, R.drawable.a17, R.drawable.a16, R.drawable.a15, R.drawable.a14, R.drawable.a13, R.drawable.a12, R.drawable.a11, R.drawable.a10, R.drawable.a9, R.drawable.a8, R.drawable.a7, R.drawable.a6, R.drawable.a5, R.drawable.a4, R.drawable.a3, R.drawable.a2, R.drawable.a1
};
#SuppressLint({"ClickableViewAccessibility", "SourceLockedOrientationActivity"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_p);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
// this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
mediaPlayer = new android.media.MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
progressDialog = new ProgressDialog(this);
kare = getIntent().getStringExtra("EXTRA_KARE1");
imagePlayPause = findViewById(R.id.image_playPause);
textCurrentTime = findViewById(R.id.textCurrentTime);
textTotalDuration = findViewById(R.id.textTotalDuration);
img_showPage = findViewById(R.id.img_showPage);
btn_goback = findViewById(R.id.btn_goack);
tvTest = findViewById(R.id.tvTest);
pageNum = getIntent().getStringExtra("EXTRA_PAGE");
tvTest.setText("ص "+pageNum);
// et_go=findViewById(R.id.et_go);
playerSeekbar = findViewById(R.id.playerSeekar);
mediaPlayer = new MediaPlayer();
playerSeekbar.setMax(100);
//////show page image in the image view
String uri = "#drawable/a" + pageNum; //imname without extension
int imageResource = getResources().getIdentifier(uri, null, getPackageName()); //get image resource
Drawable res = getResources().getDrawable(imageResource); // convert into drawble
img_showPage.setImageDrawable(res); // set as image
//////show page image in the image view end
imagePlayPause.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onClick(View v) {
String url = "";
if (kare.equals("1")) {
url = "https://ia802309.us.archive.org/32/items/mshary-al3afasy-by-qasr-almonfasel-604-page-quran-mp3-128kb_21/";
} else if (kare.equals("2")) {
url = "https://ia902609.us.archive.org/32/items/64kb--yaser--aldosry---quran--mp3---604--part---full/";
} else if (kare.equals("3")) {
url = "https://ia801306.us.archive.org/3/items/rabiea3568356835683568865/";
}
String tt = pageNum;// for testing
int mm = Integer.parseInt(pageNum);
if (mm < 10) {
tt = "00" + pageNum;
} else if (mm < 100 & mm > 10) {
tt = "0" + pageNum;
} else tt = pageNum;
String yy = url + tt + ".mp3";
if (!playPause) {
updateSeekbar();
if (initiaStage) {
new Player1().execute(yy);
imagePlayPause.setImageResource(R.drawable.ic_pause);
updateSeekbar();
} else {
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
updateSeekbar();
}
playPause = true;
imagePlayPause.setImageResource(R.drawable.ic_pause);
} else {
if (mediaPlayer.isPlaying()) {
handler.removeCallbacks(updater);//*********************
mediaPlayer.pause();
imagePlayPause.setImageResource(R.drawable.ic_play);
updateSeekbar();
}
playPause = false;
}
}
});
playerSeekbar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
SeekBar seekBar = (SeekBar) view;
int playPosition = (mediaPlayer.getDuration() / 100) * seekBar.getProgress();
mediaPlayer.seekTo(playPosition);
textCurrentTime.setText(milliSecondsToTimer(mediaPlayer.getCurrentPosition()));
return false;
}
});
mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(MediaPlayer mp, int i) {
playerSeekbar.setSecondaryProgress(i);
;
updateSeekbar();
}
});
btn_goback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
finish();
}
});
}
//**********************
class Player1 extends AsyncTask<String, Void, Boolean> {
// #SuppressLint("WrongThread")
#Override
protected Boolean doInBackground(String... strings) {
Boolean prepared = false;
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.setOnCompletionListener(new android.media.MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(android.media.MediaPlayer mediaPlayer) {
playerSeekbar.setProgress(0);
imagePlayPause.setImageResource(R.drawable.ic_play);
textCurrentTime.setText(R.string.zero);
textTotalDuration.setText(milliSecondsToTimer(mediaPlayer.getDuration()));
mediaPlayer.reset();
initiaStage = true;
playPause = false;
mediaPlayer.stop();
mediaPlayer.reset();
}
});
mediaPlayer.prepare();
textTotalDuration.setText(milliSecondsToTimer(mediaPlayer.getDuration()));
prepared = true;
} catch (Exception e) {
Log.e("MyAudioStreaminApp", e.getMessage());
prepared = false;
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (progressDialog.isShowing()) {
progressDialog.cancel();
updateSeekbar();
}
mediaPlayer.start();
initiaStage = false;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
String yo=pageNum;
progressDialog.setMessage("جاري تحميل الصفحه "+pageNum);
progressDialog.show();
}
}
private Runnable updater = new Runnable() {
#Override
public void run() {
updateSeekbar();
}
};
private void updateSeekbar() {
if (mediaPlayer.isPlaying()) {
handler.postDelayed(updater, 1000);
playerSeekbar.setProgress((int) (((float) mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration()) * 100));
textCurrentTime.setText(milliSecondsToTimer(mediaPlayer.getCurrentPosition()));
}
}
private String milliSecondsToTimer(long milliSeconds) {
String timerString = "";
String secondsString;
int hours = (int) (milliSeconds / (1000 * 60 * 60));
int minutes = (int) (milliSeconds % (100 * 60 * 60)) / (1000 * 60);
int seconds = (int) ((milliSeconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
if (hours > 0) {
timerString = hours + ":";
}
if (seconds < 10) {
secondsString = "0" + seconds;
} else {
secondsString = "" + seconds;
}
timerString = timerString + minutes + ":" + secondsString;
return timerString;
}
#Override
protected void onPause() {
super.onPause();
mediaPlayer.stop();
}
}
We cannot tell you the ultimate cause of your problem because the information about the cause has been lost due to "bad logging".
What has happened is that your code has caught an exception here:
} catch (Exception e) {
Log.e("MyAudioStreaminApp", e.getMessage());
prepared = false;
}
For some reason the exception has a null message. (We don't know why. An exception is not required to have a non-null message. At this stage we could only guess what the exception actually was, though it is probably specific to the media player implementation on certain devices.).
So, you are effectively calling:
Log.e("MyAudioStreaminApp", null);
But the javadoc for the Log.e methods say explicitly that the message must be non-null. So the above results in an NPE being thrown in the depths of the logging code. (Instead of logging the problem you wanted to log, you get something unhelpful.)
The solution (to the NPEs) is to change the logger call to this:
Log.e("MyAudioStreaminApp", "problem playing media", e);
Why:
So that you don't get tripped up by the edge case where the exception has a null message.
So that you do log the classname of the exception.
So that you do log the stacktrace embedded in the exception. That will at least point you to where in your code the exception is triggered, and it may also give you further insights ... depending on what the actual media player does internally.
The next step will be to test the modified app on a Samsung A7, and see what is logged.
The suggestion in the comments to do this:
Log.e("MyAudioStreaminApp", (e.getMessage() != null) ? e.getMessage() : "");
is (IMO) wrong. You won't get the NPE in the logging code, but you will be no clearer to figuring out what the root cause of the problems is. (You will just get useless log entries with no information in them.)
The lesson from this is to use the Log method overloads with a Throwable argument when logging from an exception handler. It is a good habit (IMO).

getIntent(), getStringExtra() are deprecated

I'm trying to pass strings from one activity to another.
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String m = markerMap.get(marker.getId());
for(int i = 0; i < 8; i++) {
if(m.equals(name[i])) {
Intent intent = new Intent(MapsActivity.this, CustomInfoWindowAdapter.class);
intent.putExtra("FOOD_BANK",name[i]);
intent.putExtra("STREET_ADDRESS",address[i]);
intent.putExtra("WEBSITE",website[i]);
startActivity(intent);
}
}
}
});
That's the chunk of code that is supposed to send the strings to the other activity.
private void rendowWindowText(Marker marker, View view) {
Intent intent = getIntent();
String foodBank = getStringExtra("FOOD_BANK");
TextView tvTitle = (TextView) view.findViewById(R.id.title);
tvTitle.setText(foodBank);
String snippet = marker.getSnippet();
TextView tvSnippet = (TextView) view.findViewById(R.id.snippet);
String address = getStringExtra("STREET_ADDRESS");
tvSnippet.setText(address);
/*if(!title.equals("")) {
tvTitle.setText(title);
}*/
}
This bit is what should be receiving the data but getIntent() and getStringExtra() are deprecated. I've tried surpressing the deprecation with #SuppressWarnings("deprecation") before the method. I've tried restarting Android Studio and my computer with no avail. I've tried getActivity().getIntent(); and no luck either.
The message when I hover my cursor over the deprecated getIntent() is:
Cannot resolve method 'getIntent' in 'CustomInfoWindowAdapter'
Would really appreciate any ideas on how to fix this because I'm very new to Android Studio and Java in general.
To get the data which u sent, use the following code :
Bundle extras = getIntent().getExtras();
if (extras != null) {
String foodBank = extras.getString("FOOD_BANK");
String address = extras.getString("STREET_ADDRESS");
}

Making required EditText field in Android Studio

I am starting to make an app. I currently have one EditText. How do I make it required? When nothing is entered into the EditText! the message Please Enter a username should flash on the screen but it still goes to the next scene/activity. How do I stop the submit if the length is 0. I put return false into the public void but I get the following message cannot return a value from a method with void result type
public void sendMessage(View view){
Intent intent = new Intent(this,DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
//Trim whitespace
message = message.trim();
//Checks if the message has anything.
if (message.length() == 0)
{
editText.setError("Please Enter a username!");
//return false;
}
intent.putExtra(EXTRA_MESSAGE,message);
startActivity(intent);
}
try this
string text=editText.getText().toString().trim();
if (TextUtils.isEmpty(text)){
editText.setError("Please Enter a username!");
}else {
//do something
}
Instead of return false;, just write return; with no return type (because the method's return type is void) and it should let you leave the method.
Modify the function like the following.
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
//Trim whitespace
message = message.trim();
//Checks if the message has anything.
if (message.length() == 0) {
editText.setError("Please Enter a username!");
return;
}
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
Use if and else clause will achieve what you want.
//Checks if the message has anything.
if (message.length() == 0)
{
editText.setError("Please Enter a username!");
//return false;
} else {
intent.putExtra(EXTRA_MESSAGE,message);
startActivity(intent);
}
Try this
public void sendMessage(View view){
Intent intent = new Intent(this,DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
if (!emptyEdittext(editText, "Please Enter a username!"))
{
intent.putExtra(EXTRA_MESSAGE,message);
startActivity(intent);
}}
2.Call below method for validation
public boolean emptyEdittext(EditText editText, String msg)
{
/*check edittext length*/
if(editText.getText().toString().length()==0)
{
Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
The issue here is that a TextEdit.getText().toString() doesn't give you a null value... It gives you an empty string, which is still a string. Try this. It is the way I do it.
public void sendMessage(View view){
Intent intent = new Intent(this,DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
//Trim whitespace
message = message.trim();
//Checks if the message has anything. This checks to see if
//it has an empty string rather than a null
if (message.equals(""))
{
Toast.makeText(getApplicationContext(),"Please provide a
message!, Toast.LENGTH_SHORT").show();
}else
intent.putExtra(EXTRA_MESSAGE,message);
startActivity(intent);
}

Pass information between activities

I am doing a project where I have to program a pedometer. The pedometer will work using a button and you have to tell the length of your steps. I made a main activity that let you choose between go anonymous an another one that let you register. The aplication works when I register or when I go anonymous, and the step length is passed well to the third activity, an activity where you can press a button and increase the number of steps done and the meters done. In this activity there is another button to configure the length of your steps and I want to pass all the info to the anonymous activity to change only the length of the steps and I pass all the info. I used the method putExtra() and getIntent().getExtra().getString(), but only works going to the main activity to the registe/anonymous activity and then going to the pedometer activity, but when i want to configure the length of the steps the aplications stops.
This is my code for the anonymous activity:
if(this.getIntent().hasExtra("name")){
names=this.getIntent().getExtras().getString("name");
}else{
names="";
}
if(this.getIntent().hasExtra("user")){
userName=this.getIntent().getExtras().getString("user");
}else{
userName="";
}
if(this.getIntent().hasExtra("pass")){
password=this.getIntent().getExtras().getString("pass");
}else{
password="";
}
if(this.getIntent().hasExtra("feetBefore")){
footBefore=this.getIntent().getExtras().getString("feetBefore");
}else{
footBefore="0";
}
if(this.getIntent().hasExtra("steps")){
stepsDone=this.getIntent().getExtras().getString("steps");
}else{
stepsDone="0";
}
Button continueBtn = findViewById(R.id.continueAnonymous);
foot = findViewById(R.id.lengthFeetAnonymous);
continueBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String footSize = String.valueOf(foot.getText());
if(!footSize.equals("")) {
Intent mainAnonymous = new Intent(getApplicationContext(), Main5Activity.class);
mainAnonymous.putExtra("name", names);
mainAnonymous.putExtra("user", userName);
mainAnonymous.putExtra("pass", password);
mainAnonymous.putExtra("feet", footSize);
mainAnonymous.putExtra("steps", stepsDone);
mainAnonymous.putExtra("feetBefore", footBefore);
startActivity(mainAnonymous);
finish() ;
}else{
Toast.makeText(Main4Activity.this, "You have to complete all the backets.",
Toast.LENGTH_SHORT).show();
}
}
});
This is the code of my pedometer activity:
Bundle parameters = this.getIntent().getExtras();
if(parameters != null){
name = parameters.getString("name");
username = parameters.getString("user");
password = parameters.getString("pass");
String foot = parameters.getString("feet");
String footBefore = parameters.getString("feetBefore");
String stepsDone = parameters.getString("steps");
if(stepsDone!=null) cont = Integer.parseInt(stepsDone);
else cont =0;
if(footBefore!=null)feetBefore = Integer.parseInt(footBefore);
else feetBefore =0;
if(foot !=null)feet = Float.parseFloat(foot)/100;
else feet = (float) 0.43;
cont2 = cont*feetBefore;
}else {
name = "";
username = "";
password = "";
feet = (float) 0.43;
}
increase = findViewById(R.id.increaseStep);
configuration = findViewById(R.id.confBtn);
saveMain = findViewById(R.id.saveBtnMain);
resume = findViewById(R.id.resumBtn);
final TextView steps = findViewById(R.id.stepCounter);
final TextView km = findViewById(R.id.kilometerCounter);
steps.setText(String.format(Locale.ENGLISH,"%d Steps",cont));
String aux =String.format(Locale.ENGLISH,"%.2f Meters", cont2);
km.setText(aux);
increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cont++;
steps.setText(String.format(Locale.ENGLISH,"%d Steps",cont));
cont2 += feet;
String aux =String.format(Locale.ENGLISH,"%.2f Meters", cont2);
km.setText(aux);
}
});
configuration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent conf = new Intent(getApplicationContext(), Main4Activity.class);
conf.putExtra("name", name);
conf.putExtra("user", username);
conf.putExtra("pass", password);
String aux2 = String.valueOf(cont);
conf.putExtra("steps", aux2);
float aux4 =feet*100;
String aux3 = String.valueOf(aux4);
conf.putExtra("feetBefore", aux3);
startActivity(conf);
finish() ;
}
});
}
I started to learn android yesterday so I don't know what I am doing wrong. If you can help me I would apreciate it. In addition, I think it's something about the bundle.
Add all data in a bundle and check only if bundle!=null –by Milan Pansuriya
I don't know the difference between using a bundle to pass al the data and putExtra to my intent but this works for me. Thank you Milan Pansuriya.

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