Android: exception thrown in one activity is not caught in another activity - android

I have a ReaderActivity.java class from where I call signString in signData.java class. If all is well then a new activity named ProductActivity is created. If there is exception in signString method, then ProductActivity is not supposed to be created.
The issue is, I still see ProductActivity is created even though I see the KSIEXCEPTION message in the log. What am I missing here?
public class ReaderActivity extends AppCompatActivity {
.....
public void setGlobal(String actualData) {
signData sign = new signData();
try {
sign.signString(getBaseContext(), finalResults, countToSend, locToSend, typeToSend);
Intent productIntent = new Intent(getBaseContext(), ProductActivity.class);
startActivity(productIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now in the signData class I have the method
public class signData extends Activity{
public void signString(Context context, String data, String count, String loc, String type){
try {
/*some http connection code here*/
/*some computation related to specific API*/
}
catch (KSIException e) {
Log.i("KSIEXCEPTION","here");
e.printStackTrace();
}
}
}

You cant create object for an activity like this. signData sign = new signData();
2.
The issue is, I still see ProductActivity is created even though I see
the KSIEXCEPTION message in the log. What am I missing here?
Yes you just catching the exception in signString method, so after execution of this method definitely, it will create next activity.
If you dont want to go to next activity, you can move that method to some utility class and you can get some return value(boolean at-least) and based on that you can move to next activity

Related

on Android, wrapper method for logging Crashlytics events with calling class as source of event

I have a utility method inside Utility.class which is a wrapper for sending Crashlytics events.
public static void logCrashlyticsEvent(String message) {
...
Crashlytics.getInstance().core.logException(new Exception(message));
...
}
The issue is whenever I use it from another class the Crashlytics dashboard shows the source for the event as Utility.class like this:
Utility.java line 106
com.myApp.util.Utility.logCrashlyticsEvent
Instead of the showing the it as the actual class who called it.
Is there a way wrap the call to Crashlytics so it will still show the calling class as the source for the event?
Thanks.
Edit:
Just to improve on #Andre Classen solution.
public static void logCrashlyticsEvent(HandledException e) {
Crashlytics.getInstance().core.logException(e);
Timber.e("Message: %s", e.getMessage());
// More stuff
}
HandledException:
public class HandledException extends Exception {
public HandledException(#NonNull String message, Object... args) {
super(String.format(message, args));
}
}
Usage:
Utility.logCrashlyticsEvent(new HandledException("Cast exception, input value1: %s, value2: %s", someValue, anotherValue));
You are creating a new Exception instead of logging the source exception , so the solution is easy:
public static void logCrashlyticsEvent(Exception e) {
.
.
Crashlytics.getInstance().core.logException(e);
.
.
}
To use it:
try{
String s=null;
int size=toString().length();
}
catch (NullPointerException e){
com.myApp.util.Utility.logCrashlyticsEvent(e);
}
This way the exception is logged the way you want it.

Custom Exception class to handle exceptions over entire application

I've just started to write an application.
I want to create a custom Exception class that spans over my whole application.
Want to do this so that every exception can be passed to that class file & whenever a exception is occurred, the Logs can be stored in one place.
I tired using this, but it does not seems an entirely good practice.
What is the best method to achieve this
Thank You
You could try just making a general (non-Exception) class, and pass the exception to it. Something like this should work:
Public Class ExceptionHandler {
public ExceptionHandler() {
}
public static handle(Exception e) {
// do stuff
}
}
in your code:
try {
}
catch(Exception e) {
ExceptionHandler.handle(e);
}

Android parsing of XML file Null Pointer Exception

I have a method that reads in an XML file, parses it and loads the individual elements into an array. The code itself works when it is included with an Activity class. It needs to be used from 2 different Activities, so I created a utility class so I can call the one copy from each Activity needed. However, when it runs from the utility class, I get a null point exception. This tells me that I'm breaking a rule of what I can do, and from where. I suspect it's related to the access to the resources, as I also tried to access a string resources (just as a test) and that also throws a NPE.
Here is the utility class. The first Log.i appears in LogCat, but the 2nd does not.
class Utils extends MainActivity
{
String debugTag = DEBUG_TAG + "/Utils";
public void loadRankFile() throws XmlPullParserException, IOException
{
int eventType = -1;
boolean boolFoundRanks = false;
int intCounter = 0;
// this line appears in LogCat
Log.i(debugTag, "Inside loadRankFile utility.");
// this line causes the NPE
XmlResourceParser scoutRanks = getResources().getXml(R.xml.scoutranks);
// this line does not appear in LogCat
Log.i(debugTag, "xml file loaded");
.
.
.
}
This is the code from the Activity that calls the method, above:
public class RankProgressActivity extends MainActivity
{
String debugTag = DEBUG_TAG + "/RankProgressActivity";
Utils utilities = new Utils();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.rank_progress);
try
{
initSelectScout();
utilities.loadRankFile();
initSelectRank();
}
catch (IOException e)
{
Log.i(debugTag, "Failure initializing Scout Progress activity items", e);
}
catch (XmlPullParserException e)
{
Log.e(debugTag, "Rank file parse error.", e);
}
.
.
.
}
I'm sure I'm making a classic mistake, but I don't see it, and I haven't been able to find guidance as of yet. Any feedback would be appreciated. I'm rather new to Java and Android, so this is very much a learning experience for me.
Thank you in advance.
Your Utils class should not be extending an Activity. Activities are your user facing interfaces, meaning that you implement an Activity when you want to display some sort of UI to the user.
Read up on the documentation for an Activity.
Your Utils class should look something like this:
class Utils
{
private static final String DEBUG_TAG = "Utils";
public ArrayList<String> parseRankFile(Context context) throws XmlPullParserException, IOException
{
ArrayList<String> scoutRanks = new ArrayList<String>();
Log.i(DEBUG_TAG, "Inside loadRankFile utility.");
XmlResourceParser scoutRanksParser = context.getResources().getXml(R.xml.scoutranks);
Log.i(DEBUG_TAG, "xml file loaded");
// do your parsing and populate the scoutRanks ArrayList
return scoutRanks;
}
}
Then in your Activity you would call your Utils method like this :
ArrayList<String> scoutRanks = Utils.parseRankFile(this);

how use getContentResolver in a class without activity?

my class looks like this:
public class sendInformation{
public void test() throws Exception {
Uri uri = SuspiciousActivityTable.CONTENT_URI;
getContentResolver().update(uri, values2, where,new String[]{"Null"});
}
}
}
but it say getContentResolver() doesn't exist, I know I need a Context or Activity to make this work but how do I get the correct Context here?
You will need to pass off a Context, even the ContentResolver class needs a valid context to be instantiated.
Simplest way is as an argument to the method:
public void test(Context context) throws Exception {
Uri uri = SuspiciousActivityTable.CONTENT_URI;
context.getContentResolver().update(uri, values2, where,new String[]{"Null"});
}
And to call: (assuming that the class that contains test is instantiated and your Activity's name is MyActivity <- Replace with the Activity name you're calling test() from)
try{
sendInformationInstanceVariable.test (MyActivity.this);
}
catch (Exception e)
{
e.printStackTrace();
}
MyActivity.this can be shortened to just this if you're not calling test() from inside an anonymous inner class.
Also, if your class really doesn't have a good reason to be instantiated, consider making test() a static method, like this:
public static void test(Context context) throws Exception {
Uri uri = SuspiciousActivityTable.CONTENT_URI;
context.getContentResolver().update(uri, values2, where,new String[]{"Null"});
}
Then from your Activity, you call this method without needing an instance:
try{
sendInformation.test (MyActivity.this);
}
catch (Exception e)
{
e.printStackTrace();
}
Lastly, throwing Exception is bad practice, do don't do it without good reason and if you do have a good reason, be as specific as possible.
Somewhere between where your application starts (and you have access to getApplicationContext()) and the point where you call test(), you'll need to pass in a Context to your sendInformation class. I would look at what lifecycle your sendInformation class has and compare it to the various Android components (Application, Activity, Fragment) and use the appropriate context from there:
Application: getApplicationContext()
Activity: this (as Activity extends Context)
Fragment: getActivity()

How to call a function present in one class from another class?

I'm trying to call a function present in one class from another class by creating its object. Somehow it's not working. The new activity doesn't load.
My java code:
public class MessagesActivity extends TabActivity {
public WorkEntryScreenActivity workEntryObject = new WorkEntryScreenActivity() ;
public void AddWorkEntryClick(View v) {
workEntryObject.newWorkEntry();
}
}
The other class:
public class WorkEntryScreenActivity extends Activity {
public void newWorkEntry() {
try {
Intent i = new Intent(this, WorkEntryActivity.class);
i.putExtra("CurDate", mDateDisplay.getText());
i.putExtra("DD", String.valueOf(mDay));
i.putExtra("MM", String.valueOf(mMonth));
i.putExtra("YYYY", String.valueOf(mYear));
startActivity(i);
finish();
} catch (Exception e) {
System.out.println("Exception" + e.getStackTrace());
Log.d(TAG, "Exception" + e.getStackTrace());
}
}
}
You must create your workEntryObject first (it's not C++). Like this
public WorkEntryScreenActivity workEntryObject=new WorkEntryScreenActivity();
Also, I highly recommed you to read Android Basics
http://developer.android.com/guide/index.html
#biovamp is correct. It looks like you have a null reference that you're trying to call a method on. In order to call a non-static method, you need a instance of that object.
From the naming of your method, it looks like you might be trying to re-use some of your UI in another part of your application. In Android, the way to accomplish that is through Intents and Activities. If you're not familiar with those or how to use them, I would highly suggest researching them.

Categories

Resources