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

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).

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.

AsyncTask kills istelf without any error message while debugging

I'm having a very weird problem with AsyncTask which I use to download a zip file in my android application. It was working flawlessly until I decided to use strings.xml resource for every string linked to this task.
when I click on the download button inside my app, the progressbar of the AsyncTask shows for a second or less then dismisses itself and the task goes to the onPostExecute() state.
I tried debuging the app on my test device and there is no error about the task. I even added some stubs with Log.d tag, I've included the logcat results:
275-15524/xmc.androidexpert35.com.xtrememusicchecker D/ANDRO_ASYNC: path set
2019-04-04 20:19:22.484 15275-15524/xmc.androidexpert35.com.xtrememusicchecker D/ANDRO_ASYNC: Try block
2019-04-04 20:19:22.487 15275-15524/xmc.androidexpert35.com.xtrememusicchecker D/ANDRO_ASYNC: file url got
2019-04-04 20:19:22.490 15275-15524/xmc.androidexpert35.com.xtrememusicchecker D/ANDRO_ASYNC: opening connection
2019-04-04 20:19:22.515 495-528/? D/SurfaceFlinger: duplicate layer name: changing xmc.androidexpert35.com.xtrememusicchecker/xmc.androidexpert35.com.xtrememusicchecker.SettingsActivity to xmc.androidexpert35.com.xtrememusicchecker/xmc.androidexpert35.com.xtrememusicchecker.SettingsActivity#1
2019-04-04 20:19:22.585 495-794/? D/SurfaceFlinger: duplicate layer name: changing Surface(name=cafcbf6 xmc.androidexpert35.com.xtrememusicchecker/xmc.androidexpert35.com.xtrememusicchecker.SettingsActivity)/#0x3604cd - animation-leash to Surface(name=cafcbf6 xmc.androidexpert35.com.xtrememusicchecker/xmc.androidexpert35.com.xtrememusicchecker.SettingsActivity)/#0x3604cd - animation-leash#1
2019-04-04 20:19:22.614 15275-15275/xmc.androidexpert35.com.xtrememusicchecker I/ViewRootImpl: CPU Rendering VSync enable = true
2019-04-04 20:19:22.672 495-528/? W/SurfaceFlinger: Attempting to set client state on removed layer: xmc.androidexpert35.com.xtrememusicchecker/xmc.androidexpert35.com.xtrememusicchecker.SettingsActivity#1
2019-04-04 20:19:22.672 495-528/? W/SurfaceFlinger: Attempting to destroy on removed layer: xmc.androidexpert35.com.xtrememusicchecker/xmc.androidexpert35.com.xtrememusicchecker.SettingsActivity#1
2019-04-04 20:19:24.758 15275-15314/xmc.androidexpert35.com.xtrememusicchecker D/FA: Logging event (FE): user_engagement(_e), Bundle[{firebase_event_origin(_o)=auto, engagement_time_msec(_et)=3635, firebase_screen_class(_sc)=SettingsActivity, firebase_screen_id(_si)=-6495914915605520780}]
2019-04-04 20:19:26.125 829-3715/? W/NotificationService: Toast already killed. pkg=xmc.androidexpert35.com.xtrememusicchecker callback=android.app.ITransientNotification$Stub$Proxy#3b51651
This is my AsyncTask code, if anyone can help me find the issue? or suggest a useful debug solution to discover it?
Thanks, any help is very appreciated!
public class DownloadFile extends AsyncTask<String, String, String> {
private static String file_url;
private Context context;
private ProgressDialog dialog;
private String dialogString;
private File path;
private String xmpath;
private boolean canceled = false;
public DownloadFile(Context cxt) {
context = cxt;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
dialog.setMessage(context.getString(R.string.xm_downloading));
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setCancelable(false);
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, context.getString(R.string.xm_cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
path.delete();
canceled = true;
dialog.dismiss();
}
});
dialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
int count;
if (SettingsActivity.isMagisk){
file_url = "http://androidexpert35developer.altervista.org/Xtrememusic-versions/XTREMEMusic_MAGISK_OFICIAL_By_androidexpert35.zip";
path= new File(Environment.getExternalStorageDirectory() + "/XTREMEMusic_Download/XTREMEMusic_Magisk.zip");
}else{
file_url = "http://androidexpert35developer.altervista.org/Xtrememusic-versions/XTREMEMusic_OFFICIAL_By_androidexpert35.zip";
path = new File(Environment.getExternalStorageDirectory() + "/XTREMEMusic_Download/XTREMEMusic.zip");
Log.d("ANDRO_ASYNC","path set");
}
try {
Log.d("ANDRO_ASYNC","Try block");
URL url = new URL(file_url);
Log.d("ANDRO_ASYNC","file url got");
URLConnection conexion = url.openConnection();
Log.d("ANDRO_ASYNC","opening connection");
conexion.connect();
Log.d("ANDRO_ASYNC","Connected");
int lenghtOfFile = conexion.getContentLength();
InputStream is = url.openStream();
File testDirectory = new File(Environment.getExternalStorageDirectory() + "/XTREMEMusic_Download");
Log.d("ANDRO_ASYNC","making directory");
if (!testDirectory.exists()) {
testDirectory.mkdir();
}
FileOutputStream fos;
Log.d("ANDRO_ASYNC","Stream");
if(SettingsActivity.isMagisk) {
fos = new FileOutputStream(testDirectory + "/" + ("XTREMEMusic_Magisk") + ".zip");
Log.d("ANDRO_ASYNC","Downloading");
}else{
fos = new FileOutputStream(testDirectory + "/" + ("XTREMEMusic") + ".zip");
Log.d("ANDRO_ASYNC","Downloading");
}
byte data[] = new byte[1024];
long total = 0;
int progress = 0;
while ((count = is.read(data)) != -1) {
total += count;
int progress_temp = (int) total * 100 / lenghtOfFile;
publishProgress(""+ progress_temp);
if (progress_temp % 10 == 0 && progress != progress_temp) {
progress = progress_temp;
}
fos.write(data, 0, count);
}
is.close();
fos.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
dialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dialog.dismiss();
if(SettingsActivity.isInstall) {
installer();
}else if (canceled) {
Toast.makeText(context, R.string.xm_cancelled, Toast.LENGTH_LONG).show();
} else{
xmpath = path.toString();
Toast.makeText(context, context.getString(R.string.xm_downloaded, xmpath), Toast.LENGTH_LONG).show();
}
}

Android Music Player Notification with Progress Bar

I'm developing music player notification with progress bar . Somehow I managed to show progress with Handler but now the problem is after some time whole android system freezes. And then rebooting the system is only a solution.
I'm new in android and this is my first app, please help me to complete my first app. I will be very thankful to you.
Here is Screenshot of Music Player Notification with Progress Bar
I've attached screenshot of notification and here is my code. These codes are running in media player foreground service
Some global variables:
private static RemoteViews views;
private static RemoteViews bigViews;
private static Notification status;
private static final int NOTIFICATION_ID = 101;
public Handler mSeekbarUpdateHandler= new Handler();
This is Runnable code:
public Runnable mUpdateseekbar=new Runnable() {
#Override
public void run() {
if(mediaPlayer != null) {
bigViews.setProgressBar(R.id.progressBar, mediaPlayer.getDuration(), mediaPlayer.getCurrentPosition(), false);
bigViews.setTextViewText(R.id.time_start, timeConvert(mediaPlayer.getCurrentPosition()));
}
startForeground(NOTIFICATION_ID, status);
mSeekbarUpdateHandler.postDelayed(this,1000);
}};
Now calling handler:
#Override
public void onPlay() {
super.onPlay();
resumeMedia();
buildNotification(PlaybackStatus.PLAYING);
mSeekbarUpdateHandler.postDelayed(mUpdateseekbar,0);
//also calling this Handler from method onSkipToNext() and previous. it means when changing song also calling Handler each time.
Finally build notification code:
private void buildNotification(PlaybackStatus playbackStatus)
{
//This section containing long code which works fine so no need to make post longer.
}
when running this code after few minute system becomes slow and finally freeze.
After removing Handler no problem occurs in notification but my progress bar not updating.
}
I have successfully solved this issue by every time Re-building whole notification in the Runnable ...
I have replaced above Runnable code with the following code...
public Runnable mUpdateseekbar = new Runnable() {
#Override
public void run() {
if (mediaPlayer.isPlaying()) {
buildNotification(PlaybackStatus.PLAYING);
}
mSeekbarUpdateHandler.postDelayed(this, 1000);
}
};
And here's the buildNotification method..
private void buildNotification(PlaybackStatus playbackStatus) {
RemoteViews views;
RemoteViews bigViews;
Notification status;
try {
int notificationAction = android.R.drawable.ic_media_pause;
PendingIntent play_pauseAction = null;
if (playbackStatus == PlaybackStatus.PLAYING) {
notificationAction = R.drawable.noty_pause;
play_pauseAction = playbackAction(1);
} else if (playbackStatus == PlaybackStatus.PAUSED) {
notificationAction = R.drawable.noty_play;
play_pauseAction = playbackAction(0);
}
views = new RemoteViews(getPackageName(),
R.layout.status_bar);
bigViews = new RemoteViews(getPackageName(),
R.layout.status_bar_expanded);
views.setImageViewBitmap(R.id.status_bar_album_art,
largeIcon);
bigViews.setImageViewBitmap(R.id.status_bar_album_art,
largeIcon);
views.setImageViewResource(R.id.status_bar_playPause,
notificationAction);
bigViews.setImageViewResource(R.id.status_bar_play,
notificationAction);
bigViews.setProgressBar(R.id.progressBar, mediaPlayer.getDuration(), mediaPlayer.getCurrentPosition(), false);
views.setTextViewText(R.id.status_bar_track_name, activeAudio.getTitle());
bigViews.setTextViewText(R.id.status_bar_track_name, activeAudio.getTitle());
views.setTextViewText(R.id.status_bar_artist_name, activeAudio.getAlbum() + "-" + activeAudio.getArtist());
bigViews.setTextViewText(R.id.status_bar_artist_name, activeAudio.getAlbum() + "-" + activeAudio.getArtist());
views.setTextViewText(R.id.status_bar_metadata, displayMeta);
bigViews.setTextViewText(R.id.status_bar_album_name, displayMeta);
bigViews.setTextViewText(R.id.track_num, (audioIndex + 1) + "/" + audioList.size());
bigViews.setTextViewText(R.id.end_time, timeConvert(mediaPlayer.getDuration()));
bigViews.setTextViewText(R.id.time_start, timeConvert(mediaPlayer.getCurrentPosition()));
views.setOnClickPendingIntent(R.id.status_bar_playPause, play_pauseAction);
bigViews.setOnClickPendingIntent(R.id.status_bar_play, play_pauseAction);
views.setOnClickPendingIntent(R.id.status_bar_next, playbackAction(2));
bigViews.setOnClickPendingIntent(R.id.status_bar_next, playbackAction(2));
views.setOnClickPendingIntent(R.id.status_bar_previous, playbackAction(3));
bigViews.setOnClickPendingIntent(R.id.status_bar_prev, playbackAction(3));
bigViews.setOnClickPendingIntent(R.id.status_bar_ff, playbackAction(5));
bigViews.setOnClickPendingIntent(R.id.status_bar_rev, playbackAction(6));
bigViews.setOnClickPendingIntent(R.id.status_bar_collapse, playbackAction(4));
views.setOnClickPendingIntent(R.id.status_stop,playbackAction(4));
status = new Notification.Builder(this).build();
status.contentView = views;
status.bigContentView = bigViews;
status.flags = Notification.FLAG_ONGOING_EVENT;
status.visibility = Notification.VISIBILITY_PUBLIC;
status.tickerText = activeAudio.getTitle();
if (playbackStatus==PlaybackStatus.PLAYING) {
status.icon = R.drawable.notyskeep;
} else {
status.icon = R.drawable.noty_small_blue;
}
status.priority = Notification.PRIORITY_MAX;
status.contentIntent = playbackAction(8);
startForeground(NOTIFICATION_ID, status);
} catch (Throwable e) {
Toast.makeText(getApplicationContext(), "Exception raised:" + e, Toast.LENGTH_LONG).show();
}
}

Tunring my android to beacon and detecting

Is this right way of doing? AM using this samples https://altbeacon.github.io/android-beacon-library/samples.html
public class App extends Application
implements BootstrapNotifier, BeaconConsumer, RangeNotifier {
private final String TAG = "Application ";
protected static final Region beaconRegion = new Region("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6", null, null, null);
protected BeaconManager beaconManager = null;
private RegionBootstrap regionBootstrap;
private BackgroundPowerSaver backgroundPowerSaver;
protected static String sLog = "";
#Override
public void onCreate() {
super.onCreate();
logIt(TAG, beaconRegion.getId1()+"onCreate - In"+beaconRegion.getUniqueId());
beaconManager = org.altbeacon.beacon.BeaconManager.getInstanceForApplication(this);
beaconManager.getBeaconParsers().clear();
beaconManager.getBeaconParsers().add(new BeaconParser().
setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));//iBeacon (tutti)
//--- wake up the app when a beacon is seen
regionBootstrap = new RegionBootstrap(this, beaconRegion);
//--- activate power saver
backgroundPowerSaver = new BackgroundPowerSaver(this);
beaconManager.bind(this);
logIt(TAG, "onCreate - Out");
}
private void logIt (String TAG, String msg) {
sLog += TAG + msg + "\n";
Log.w(TAG, msg);
}
//-------------------------//
//--- BootstrapNotifier ---//
//-------------------------//
#Override
public void didDetermineStateForRegion(int state, Region region) {
String msg = "didDetermineStateForRegion ";
switch(state) {
case MonitorNotifier.INSIDE:
msg +="(INSIDE)";
break;
case MonitorNotifier.OUTSIDE:
msg +="(OUTSIDE)";
break;
default:
msg +="(state=" +state +")";
break;
}
logIt(TAG, msg);
}
#Override
public void didEnterRegion(Region arg0) {
logIt(TAG, "didEnterRegion - In");
try {
beaconManager.startRangingBeaconsInRegion(beaconRegion);
logIt(TAG,"dER - startRangingBeaconsInRegion OK");
} catch (RemoteException e) {
logIt(TAG, "dER - startRangingBeaconsInRegion Err " +e);
}
logIt(TAG, "didEnterRegion - Out");
}
#Override
public void didExitRegion(Region region) {
logIt(TAG, "didExitRegion - In");
try {
beaconManager.stopRangingBeaconsInRegion(beaconRegion);
logIt(TAG,"dXR - stopRangingBeaconsInRegion OK");
} catch (RemoteException e) {
logIt(TAG, "dXR - stopRangingBeaconsInRegion Err " +e);
}
logIt(TAG, "didExitRegion - Out");
}
//----------------------//
//--- BeaconConsumer ---//
//----------------------//
#Override
public void onBeaconServiceConnect() {
logIt(TAG, "onBeaconServiceConnect - In");
beaconManager.setRangeNotifier(this);
logIt(TAG, "onBeaconServiceConnect - Out");
}
//---------------------//
//--- RangeNotifier ---//
//---------------------//
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
logIt(TAG, "didRangeBeaconsInRegion - " +beacons.size() +" beacons");
Toast.makeText(getApplicationContext(), beaconRegion.getId1()+" beacon detected "+beacons.size(),
Toast.LENGTH_SHORT).show();
for(Beacon beac: beacons)
{
System.out.println(beac.getId1()+"id 1"+TAG);
if(beac.getId1().equals("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6")/send notification
}
}
}
So Basically that class, which extends application am listening to beacons around. Below, is how am turning my phone into a beacon.I am doing this inside an activity on click of button. So there is two phones with app downloaded on both, once he clicks on one app the button I want the other phone to detect it since i have implemented in extends application class.
the turn ur android to beacon code.
Beacon beacon = new Beacon.Builder()
.setId1("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6") // UUID for beacon
.setId2("1") // Major for beacon
.setId3("5") // Minor for beacon
.setManufacturer(0x004C) // Radius Networks.0x0118 Change this for other beacon layouts//0x004C for iPhone
.setTxPower(-56) // Power in dB
.setDataFields(Arrays.asList(new Long[]{0l})) // Remove this for beacon layouts without d: fields
.build();
BeaconParser beaconParser = new BeaconParser()
.setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24");
beaconTransmitter = new BeaconTransmitter(MenuActivity.this, beaconParser);
beaconTransmitter.startAdvertising(beacon, new AdvertiseCallback() {
#Override
public void onStartFailure(int errorCode) {
Log.e("tag", "Advertisement start failed with code: " + errorCode);
}
#Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
Log.i("tag", "Advertisement start succeeded.");
Toast.makeText(MenuActivity.this, "advertisement start succeeded",
Toast.LENGTH_SHORT).show();
System.out.println("startedddddddddddd");
}
});
// beaconTransmitter.stopAdvertising();
}
catch(Exception o)
{
System.out.println("affda "+o.getMessage());
}
I am also havig an issue, that didenterregion and didRangeBeaconsInRegion are fired many times, so am sending many notification to the user multiple times. its not user friendly.
The didRangeBeaconsInRegion callback is supposed to get called many times -- that's how ranging works. It is called approximately once per second when the beacon is detected to tell you it is there and give you a distance estimate.
If you want to fire a notification only once for the first time you get a call to this method, then you can set a flag for this specific beacon.
Here is an example of some code you might use to do that:
// Add this to the top of your class
private HashMap<String,Boolean> mAlreadySentNotification = new HashMap<String,Boolean>();
...
// Add this to the inside of your didRangeBeaconsInRegion method
if (mAlreadySentNotification.get(beacon.toString())) {
mAlreadySentNotification.put(beacon.toString(), true);
// Send notification here.
}

how can i add multithreading or other similar function to android application?

my android application freezes for a few seconds when i try to send my database file to my remote server, is there anyway i can set this as a background thread using multithreading or another such feature?
this is the code for the dialog box that appears to ask me if i want to send
public void showYesNoBox(){
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
SendData();
finish();//go back to the previous Activity
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
finish();//go back to the previous Activity
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_DARK);
builder.setMessage("Do you want to send the data now?");
builder.setPositiveButton("Yes", dialogClickListener);
builder.setNegativeButton("No", dialogClickListener);
builder.show();
}
and here is the code it executes when i click the "Yes" button
public void SendData() {
File path = getDatabasePath(DataBaseHelper.DATABASE_NAME);
if (path.exists())
copyDatabase(path);
}
/**
* Copy the database to the sdcard
* #param file
*/
private void copyDatabase(File file) {
SimpleDateFormat dateFormat1 = new SimpleDateFormat("ddMMyy-HHmmss");
String dateString = dateFormat1.format(new Date());
String pathdest = getDir().getAbsolutePath() + Configuration.LOST_FOLDER + "/Database/";
String pathdir = pathdest;
File dir = new File(pathdir);
if (!dir.exists())
dir.mkdirs();
String namefile = file.getName();
int pos = namefile.lastIndexOf('.');
if (pos != -1) {
String ext = namefile.substring(pos + 1);
String name = namefile.substring(0, pos - 1);
pathdest += name;
pathdest += "_" + dateString;
pathdest += ext;
} else {
pathdest += namefile;
pathdest += "_" + dateString;
}
File filedest = new File(pathdest);
try {
if (filedest.createNewFile())
copyFile(file.getAbsolutePath(), pathdest);
} catch (IOException e) {
e.printStackTrace();
}
}
any help with this problem would be greatly appreciated as while the problem doesn't prevent the user from being able to send the data it is anoying to be stuck on one screen for a few seconds while it attempts to execute the action.
while the problem doesn't prevent the user from being able to send the data it is anoying to be stuck on one screen for a few seconds while it attempts to execute the action.
You can see AsyncTask. Its for the same purposes. User need not be stuck on UI when you want to do long running processes including taking to server, doing database stuff etc. This can be done in the background using AsyncTask. There are many good tutorials out there. Just Google it. Checkout Android Background Processing with Threads, Handlers and AsyncTask - Tutorial and What arguments are passed into AsyncTask<arg1, arg2, arg3>? . Hope this helps.
I've been using asynctask for handling all the processes I want to do in the background.
AsyncTask
Use all network operations in AsyncTask
like the below example
private class UploadTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
// upload task
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Once created, a task is executed very simply:
new UploadTask().execute(url1, url2, url3);

Categories

Resources