Why do app gets stopped unexpectedly everytime using any code - java

My apologies
Hi, I am a newbie to the advance level programming. I have been working around with the basics and the syntax of the language.
I have searched enough
The problem I am having is, that each time, I write the code to handle the events in my App, it gets stopped. I have tried following step by step coding of the video from Treehouse tutorial of using the onClick and I have tried to follow the Android's official developer documents too. I have also looked into the codes at some sites (including and specially Stack Overflow).
All in vain
But each time I run the code, app works and when it has to execute the methods and functions, it gives me an alert saying App (Number Converter) stopped Unexpectedly. I am creating an app to convert the numbers from and to the 4 number systems, decimal, binary, octal and hexadecimal.
But, I am not able to get to the point why and why every time I write the code that is same, doesn't work and app stops.
Here is the code I am trying:
Button frmDeciToOct = (Button) findViewById(R.id.fromDecToOct);
/* here is the method that is the onClick */
frmDeciToBin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* getting the edit text view */
EditText edtTxt = (EditText) findViewById(R.id.decimalValue);
/* to string... */
String value = edtTxt.getText().toString();
/* conversion to int, I saw this method on SO's answer */
int value2 = Integer.valueOf(value);
/* createBinOfDeci is a method, I will post its code after this */
String result = createBinOfDeci(value2);
/* get the text view */
TextView txtView = (TextView) findViewById(R.id.fromDeciRes);
/* set the text as a result */
txtView.setText(result);
}
});
Here is the code for my method createBinOfDeci():
public String createBinOfDeci (int deci) {
String result = "";
result = Integer.toBinaryString(deci);
return result;
}
The only thing that I am getting is that, I am using Windows and it gets crashed due to less RAM amount here! I am truly out of guesses and answers. Any help would be appreciated.

As #CommonsWare suggested, to check the LogCat, and I saw that it showed me a few errors.
Which was a clear sign of saying: The values are not correctly matching up.
Then I came up to the point, that the values weren't actually filled. They were empty, and I was running the code on a null hehe.
I just added the value and it worked!
Thanks guys (for the LogCat suggestion).

Related

How to click button inside method Adapter in RecyclerView?

I am working on stripe-terminal-android-app, to connect to BBPOS 2X Reader device,
wanted to click-item from list,(recyclerView).
I am trying to do:
when list of devices appears(readers), I am checking if readers.size()==1, then click first-device from list,else show recyclerView();
I have very less experience in Android(coming from JS, PY), :)
After going through debugger to understand flow of program-running, I used F8 key, or stepOver the functions one by one,
and where value is assigned to convert in displayble-format in adapter as here.
public ReaderAdapter(#NotNull DiscoveryViewModel viewModel) {
super();
this.viewModel = viewModel;
if (viewModel.readers.getValue() == null) {
readers = new ArrayList<>();
} else {
readers = viewModel.readers.getValue();
if(readers.size() == 1){
Log.e(TAG, "readers.size() is 1 "+ readers.size());
}
}
}
then in ReaderHolder-file, values are bind() as
void bind(#NotNull Reader reader) {
binding.setItem(reader);
binding.setHandler(clickListener);
binding.executePendingBindings();
}
}
I tried assigining button and manually clicking when only-one device appears, by clicing on reader[0], can't do that by findViewById inside Adapter file, to call onClick() method manually,
I tired another StackOverflow's answer but didn't understood, from here.
Main fragment is discovery-fragment,
how can I click first-device by checking readers.size()==1, then click onClick()?
my final-goal is to automate, whole stripe-terminal-payment process on android.
extra-info:
I am fetching data from python-odoo server, then using url, will open app through browser, (done this part), then device will be selected automatically as everytime-no any devices will be present except one,
so will automatically select that from recyclerView, then proceed.
I have asked for help in detailed way on GitHub-issues, and started learning Android's concepts for this app(by customizing stripe's demo app, which works great, but I wanted to avoid manually clicking/selection of devices).

Android , What is the difference between these codes?

i was watching thenewboston's tutorial about fragments and i came across this line of code..
#Override
public void sendtex(String top, String bottom) {
BottomFregment_class bottomFregment = (BottomFregment_class) getSupportFragmentManager().findFragmentById(R.id.Main);
bottomFregment.finale(top,bottom);
}
this was to change TextView by getting text from another fragment! and "sendtext is implemented method from that fragment"
i replaced
BottomFregment_class bottomFregment = (BottomFregment_class) getSupportFragmentManager().findFragmentById(R.id.Main);
bottomFregment.finale(top,bottom);
with
BottomFregment_class bottomFregmentClass = new BottomFregment_class();
bottomFregmentClass.finale(top,bottom);
and everything worked fine!
i want to know that is there any difference in between these two codes?
or will this cause any performance issues?
In the first, you fetch an existing fragment, maybe with some data in there, on the other one you create an empty one.

How can I implement Google Play Licensing for an Android app? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 1 year ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I saw the stock Android-Developer licensing library instructions, but the overview seems to omit several key steps in the process and fails to fully explain how to get something working.
Can someone provide an explicit set of operations that worked to get the licensing library set up on an Android app so it checks to ensure that a user has paid for an app in Google Play before allowing use?
I have been working on implementing licensing in my app for some time now and finally have it working. I wanted to share some of the things I found helpful for getting started and some problems and solutions that I found with everyone. The android dev tutorial I have linked below is ok, but it wasn't that useful for me, so I decided to make a tutorial. Enjoy, and I hope it helps you!
Link to developer page here.
1. Getting started
Things you will need.
1.1 Your Base64 unique application key
How to get it:
a. Go to your developer console. Link.
b. If you haven't already created an application draft for your app, do it now.
c. Once you have created the draft, it is a good idea to upload your .apk as Alpha or Beta. Leave it unpublished.
d. Click Services & APIs
e. Scroll down and find YOUR LICENSE KEY FOR THIS APPLICATION
f. Copy the key into your app like this:
private static final String BASE64_PUBLIC_KEY = "YOUR LICENSE KEY FOR THIS APPLICATION";
Make sure that there are no spaces.
1.2 A salt
a. What is a salt?
A salt is random data that is additional input when hashing a password. They are used to defend against dictionary attacks and rainbow table attacks.
b. How do I get one?
This is a good link to generate a random salt. There should be exactly 20 random integers, so put 20 in for the amount of random strings to generate, each string should be 2 characters long (used for this example, it doesn't have to be). Check numeric digits, and check Identical strings are allowed. They can be negative numbers too. Try to remove any redundancy, e.g. 00 -> 0, for the sake of consistency.
c. Where do I put the salt?
When declaring variables just put this code in, except with your random salt.
private static final byte[] SALT = new byte[] {YOUR RANDOM SALT, COMMA SEPARATED, 20 INTEGERS};
2. Importing the LVL (Licensing) library into Eclipse and the code you need
2.1 Importing the library
a. Open Android SDK Manager
b. Go to Extras
c. Install Google Play Licensing Library
d. Find your SDK install path which is listed at the top of the SDK manager.
e. Once you are there, navigate to: <sdk>/extras/google/play_licensing
f. In eclipse, click file then import, then Existing Android Code Into Workspace and when it asks you for the file path, navigate to the play_licensing folder and click on library.
g. Once the project named library has been imported, right click it, then hit properties. Click Android on the left and navigate to the bottom and check Is Library, then hit apply. This lets eclipse know that you can use this project code as a library.
h. Right click on your app that you are adding licensing to, and click properties, then hit Android. Go to the bottom and click library and add it to the build path. This should import the library to the Android Dependencies folder.
i. Your project is set up to go to the next step.
2.2 Variables to declare along with your SALT and KEY
private Handler mHandler;
private LicenseChecker mChecker;
private LicenseCheckerCallback mLicenseCheckerCallback;
boolean licensed;
boolean checkingLicense;
boolean didCheck;
2.3 The code
Paste this code near the bottom of your app. This implementation will notify the user if the license is not valid and prompt them to buy the app or exit it.
private void doCheck() {
didCheck = false;
checkingLicense = true;
setProgressBarIndeterminateVisibility(true);
mChecker.checkAccess(mLicenseCheckerCallback);
}
private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
#Override
public void allow(int reason) {
// TODO Auto-generated method stub
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
Log.i("License","Accepted!");
//You can do other things here, like saving the licensed status to a
//SharedPreference so the app only has to check the license once.
licensed = true;
checkingLicense = false;
didCheck = true;
}
#SuppressWarnings("deprecation")
#Override
public void dontAllow(int reason) {
// TODO Auto-generated method stub
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
Log.i("License","Denied!");
Log.i("License","Reason for denial: "+reason);
//You can do other things here, like saving the licensed status to a
//SharedPreference so the app only has to check the license once.
licensed = false;
checkingLicense = false;
didCheck = true;
showDialog(0);
}
#SuppressWarnings("deprecation")
#Override
public void applicationError(int reason) {
// TODO Auto-generated method stub
Log.i("License", "Error: " + reason);
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
licensed = true;
checkingLicense = false;
didCheck = false;
showDialog(0);
}
}
protected Dialog onCreateDialog(int id) {
// We have only one dialog.
return new AlertDialog.Builder(this)
.setTitle("UNLICENSED APPLICATION DIALOG TITLE")
.setMessage("This application is not licensed, please buy it from the play store.")
.setPositiveButton("Buy", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(
"http://market.android.com/details?id=" + getPackageName()));
startActivity(marketIntent);
finish();
}
})
.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNeutralButton("Re-Check", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
doCheck();
}
})
.setCancelable(false)
.setOnKeyListener(new DialogInterface.OnKeyListener(){
public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
Log.i("License", "Key Listener");
finish();
return true;
}
})
.create();
}
2.4 Getting your device id
There has been some debate about this in the past about whether or not to use the sim serial or TelephonyManager.getDeviceId(); but it is generally recommended you use the following code to get the ANDROID_ID of your device for maximum compatibility.
String deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
Log.i("Device Id", deviceId); //AN EXAMPLE OF LOGGING THAT YOU SHOULD BE DOING :)
2.5 Creation of the license checker
a. Before you call doCheck(); you must put this code in your app to make sure everything gets created properly.
mHandler = new Handler();
mLicenseCheckerCallback = new MyLicenseCheckerCallback();
mChecker = new LicenseChecker(this, new ServerManagedPolicy(this, new AESObfuscator(SALT, getPackageName(), deviceId)), BASE64_PUBLIC_KEY);
When I was doing my implemetation of LVL, I read that if you are having problems with Licensing, you can change the first this in the mChecker = new LicenseChecker(this... to getApplicationContext(), mine seemed to work without it, but just in case.
2.6 Adding permissions
a. There are two permissions that you need to add to your applications manifest file.
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.android.vending.CHECK_LICENSE"/>
2.7 Make sure you have the proper imports!
You have probably already done this, but I figured it would be a good place for you to check.
2.8 How to call the license to be checked
a. Simply call doCheck(); whenever you want to check the license. For example if the app is on its first run, do the check.
3. How do I test the licensing to make sure it works before publishing it?
3.1 Configuring the testing device
a. I have my personal phone that I also use for testing. It is recommended that there be only one Google account registered on the phone, historically it makes things a little easier. You can check the accounts by going to Settings -> Accounts.
3.2 Configuring the developer console
a. Open your developer console and go to Settings on the left hand side.
b. Find License Testing
c. Make sure that your email address is listed under Gmail accounts with testing access
d. Now, you can change the test response to whatever you like for testing purposes. The app should respond accordingly. Remember that if you are saving the data via SharedPrefs you will need to clear your app data every time you test it. Make sure that you click save after you change the test response or nothing will happen! I forgot about this multiple times and I ended up with a migraine, then I saw that stinking save button. Lol.
4. Things to try
4.1 Conditional license checking
a. You can try this code if you are saving the didCheck data in SharedPreferences.
if(didCheck==false){
Toast.makeText(this, "Checking application license...", Toast.LENGTH_SHORT).show();
doCheck();
Log.i("Checking!", "Checking license!");
}
4.2 Encrypting your SharedPreferences using SecurePreferences
a. Go to this link.
b. Copy and paste the code from SecurePreferences.java into a class with the exact same name into your project.
c. Read the ReadMe.md for info on implementing this.
5. Troubleshooting
Licensing can be one heck of a headache to troubleshoot, simply because there are many more things that can go wrong. For example, there could be network problems or server problems that make you want to rip your hair out. Use of proper logging will help with this, you can also get the server response codes if there is a problem and you can trace it to the server or your app. I have had to do this on multiple occasions.
5.1 I can't get my app to return anything from the server
Possible Fixes:
a. Make sure that your app has the correct KEY.
b. Make sure you are logging each step of the progress
c. Check your log for anything from the licensing service. It can be useful for figuring out where something went wrong.
d. Make sure allow() and dontAllow() and applicationError() have #Override tags.
5.2 My app always says LICENSED or NOT_LICENSED no matter what I set it to in the test response
a. The best cure I have for this is just to wait. It seems that if you do lots of testing in a short period of time, it will always send you server code 291 which is the retry code. I waited overnight and everything worked fine the next morning.
b. You can clear the data (not just cache) of the Google Play app and the Google Play Services app. Then open play back up and accept all the licenses and try again.
c. Clear your app data.
5.3 List of server response codes for debugging
You should get these decimal values for int reason if you log them. Use this table to reference what the server is actually sending to your app.
LICENSED = Hex: 0x0100, Decimal: 256
NOT_LICENSED = Hex: 0x0231, Decimal: 561
RETRY = Hex: 0x0123, Decimal: 291
LICENSED_OLD_KEY = Hex: 0x2, Decimal: 2
ERROR_NOT_MARKET_MANAGED = Hex: 0x3, Decimal: 3
ERROR_SERVER_FAILURE = Hex: 0x4, Decimal: 4
ERROR_OVER_QUOTA = Hex: 0x5, Decimal: 5
ERROR_CONTACTING_SERVER = Hex: 0x101, Decimal: 257
ERROR_INVALID_PACKAGE_NAME = Hex: 0x102, Decimal: 258
ERROR_NON_MATCHING_UID = Hex: 0x103, Decimal: 259
5.4 Room for more! They will come!
I hope this helps you guys! I tried to share my headaches and fixes with you guys as best I can and I hope this helps!
If I made any errors, be sure to tell me about them so I can get them fixed ASAP!

Android - is SignalStrength an Event Class?

I have a little problem with a SignalStrength Android class. Is there a way to use methods from this class without referencing an object from this class in a onSignalStrengthsChanged() method?
From all the examples I saw, it seems to me that this is an Event Class and that object is created when an event (change of gsm signal strength) occurs and that this is the only way to call methods from this class. Am I right?
public void onSignalStrengthsChanged(SignalStrength signalStrength)
{
String power= String.valueOf(signalStrength.getGsmSignalStrength());
gsmStat.setText("GSM cinr: " +power);
}
What if I want to call methods from this class (and read gsm signal properties) in some other case, for example when I click a button object?
Thank you very much for any help, I'm really stuck with this.
BR,
Z
Thank you for clearing this up. I tried to use getNeighbouringCellInfo but for some reason this return 0. And yes I've searched and tried different examples.
Tel = ( TelephonyManager )getSystemService(Context.TELEPHONY_SERVICE);
public void onClick(View v) {
List<NeighboringCellInfo> neighCell = null;
neighCell = Tel.getNeighboringCellInfo();
NeighboringCellInfo thisCell = neighCell.get(1);
int thisNeighRSSI = thisCell.getRssi();
String rssi=Integer.toString(thisNeighRSSI);
tvRSSI.setText("Test: " +rssi);
}
You can't. The only way to get a relevant SignalStrength object is in the onSignalStrengthChanged method.
You can, however, use the TelephonyManager.getNeighbouringCellInfo method to list surrounding cells and get the signal RSSI power (getRssi).
See: getNeighboringCellInfo() returning null list
getNeighboringCellInfo()
This doesn't seem to work on Samsung devices.
Sorry to put this as an answer, but I cannot add a comment to an existing answer.
As for my answer, you can track the RSSI yourself in a service so that when you press the button, the last recorded RSSI value is returned. Having said that, I've found that on the Samsung Galaxy I work with, the RSSI value is actually the number of antenna bars (ie. I only get 4 values) and not the actual RSSI.

Why doesn't "System.out.println" work in Android?

I want to print something in console, so that I can debug it. But for some reason, nothing prints in my Android application.
How do I debug then?
public class HelloWebview extends Activity {
WebView webview;
private static final String LOG_TAG = "WebViewDemo";
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new HelloWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebChromeClient(new MyWebChromeClient());
webview.loadUrl("http://example.com/");
System.out.println("I am here");
}
Correction:
On the emulator and most devices System.out.println gets redirected to LogCat and printed using Log.i(). This may not be true on very old or custom Android versions.
Original:
There is no console to send the messages to so the System.out.println messages get lost. In the same way this happens when you run a "traditional" Java application with javaw.
Instead, you can use the Android Log class:
Log.d("MyApp","I am here");
You can then view the log either in the Logcat view in Eclipse, or by running the following command:
adb logcat
It's good to get in to the habit of looking at logcat output as that is also where the Stack Traces of any uncaught Exceptions are displayed.
The first Entry to every logging call is the log tag which identifies the source of the log message. This is helpful as you can filter the output of the log to show just your messages. To make sure that you're consistent with your log tag it's probably best to define it once as a static final String somewhere.
Log.d(MyActivity.LOG_TAG,"Application started");
There are five one-letter methods in Log corresponding to the following levels:
e() - Error
w() - Warning
i() - Information
d() - Debug
v() - Verbose
wtf() - What a Terrible Failure
The documentation says the following about the levels:
Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.
Use the Log class. Output visible with LogCat
Yes it does. If you're using the emulator, it will show in the Logcat view under the System.out tag. Write something and try it in your emulator.
Of course, to see the result in logcat, you should set the Log level at least to "Info" (Log level in logcat); otherwise, as it happened to me, you won't see your output.
if you really need System.out.println to work(eg. it's called from third party library). you can simply use reflection to change out field in System.class:
try{
Field outField = System.class.getDeclaredField("out");
Field modifiersField = Field.class.getDeclaredField("accessFlags");
modifiersField.setAccessible(true);
modifiersField.set(outField, outField.getModifiers() & ~Modifier.FINAL);
outField.setAccessible(true);
outField.set(null, new PrintStream(new RedirectLogOutputStream());
}catch(NoSuchFieldException e){
e.printStackTrace();
}catch(IllegalAccessException e){
e.printStackTrace();
}
RedirectLogOutputStream class:
public class RedirectLogOutputStream extends OutputStream{
private String mCache;
#Override
public void write(int b) throws IOException{
if(mCache == null) mCache = "";
if(((char) b) == '\n'){
Log.i("redirect from system.out", mCache);
mCache = "";
}else{
mCache += (char) b;
}
}
}
it is not displayed in your application... it is under your emulator's logcat
System.out.println("...") is displayed on the Android Monitor in Android Studio
There is no place on your phone that you can read the System.out.println();
Instead, if you want to see the result of something either look at your logcat/console window or make a Toast or a Snackbar (if you're on a newer device) appear on the device's screen with the message :)
That's what i do when i have to check for example where it goes in a switch case code! Have fun coding! :)
I'll leave this for further visitors as for me it was something about the main thread being unable to System.out.println.
public class LogUtil {
private static String log = "";
private static boolean started = false;
public static void print(String s) {
//Start the thread unless it's already running
if(!started) {
start();
}
//Append a String to the log
log += s;
}
public static void println(String s) {
//Start the thread unless it's already running
if(!started) {
start();
}
//Append a String to the log with a newline.
//NOTE: Change to print(s + "\n") if you don't want it to trim the last newline.
log += (s.endsWith("\n") )? s : (s + "\n");
}
private static void start() {
//Creates a new Thread responsible for showing the logs.
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
while(true) {
//Execute 100 times per second to save CPU cycles.
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//If the log variable has any contents...
if(!log.isEmpty()) {
//...print it and clear the log variable for new data.
System.out.print(log);
log = "";
}
}
}
});
thread.start();
started = true;
}
}
Usage: LogUtil.println("This is a string");
I dont having fancy IDE to use LogCat as I use a mobile IDE.
I had to use various other methods and I have the classes and utilties for you to use if you need.
class jav.android.Msg. Has a collection of static methods.
A: methods for printing android TOASTS.
B: methods for popping up a dialog box.
Each method requires a valid Context. You can set the default context.
A more ambitious way, An Android Console. You instantiate a handle to the console in your app, which fires up the console(if it is installed), and you can write to the console. I recently updated the console to implement reading input from the console. Which doesnt return until the input is recieved, like a regular console.
A: Download and install Android Console( get it from me)
B: A java file is shipped with it(jav.android.console.IConsole). Place it at the appropriate directory. It contains the methods to operate Android Console.
C: Call the constructor which completes the initialization.
D: read<*> and write the console.
There is still work to do. Namely, since OnServiceConnected is not called immediately, You cannot use IConsole in the same function you instantiated it.
Before creating Android Console, I created Console Dialog, which was a dialog operating in the same app to resemble a console. Pro: no need to wait on OnServiceConnected to use it. Con: When app crashes, you dont get the message that crashed the app.
Since Android Console is a seperate app in a seperate process, if your app crashes, you definately get to see the error. Furthermore IConsole sets an uncaught exception handler in your app incase you are not keen in exception handling. It pretty much prints the stack traces and exception messages to Android Console. Finally, if Android Console crashes, it sends its stacktrace and exceptions to you and you can choose an app to read it. Actually, AndroidConsole is not required to crash.
Edit Extras
I noticed that my while APK Builder has no LogCat; AIDE does. Then I realized a pro of using my Android Console anyhow.
Android Console is design to take up only a portion of the screen, so you can see both your app, and data emitted from your app to the console. This is not possible with AIDE. So I I want to touch the screen and see coordinates, Android Console makes this easy.
Android Console is designed to pop up when you write to it.
Android Console will hide when you backpress.
Solution that worked for me:
Under Logcat. (To show Logcat if not already shown. Click View menu-->Tool Windows-->Logcat). It is shown as System.out not as System.out.println as you might expect it. Rebuild the app if you have not already.
In the picture, highlighted yellow shows the System.out and output "Hello again".
Recently I noticed the same issue in Android Studio 3.3. I closed the other Android studio projects and Logcat started working. The accepted answer above is not logical at all.

Categories

Resources