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
I'm using another class to run some stuff in the background while the main activity is being displayed, and passing that activity's context to this background class. I'm starting another activity from this background class, but am unable to call overridePendingTransition here because "method overridePendingTransition(int, int) is undefined for the type BackgroundClass."
public class GetUPC extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute()
{
...
}
#Override
protected Void doInBackground(Void... arg0)
{
...
boolean dairy;
if(theDairy.equals("N"))
{
//milk test
dairy=true;
}
else
{
dairy=false;
}
//depending on if there is a warning it will either display the warning screen or skip it
if(dairy)
{
Intent intent_warn = new Intent(context, WarningScreen.class);
intent_warn.putExtra("Name", str_name);
intent_warn.putExtra("Size", str_size);
intent_warn.putExtra("Price", str_price);
intent_warn.putExtra("Carbs", str_carbs);
intent_warn.putExtra("Protein", str_protein);
intent_warn.putExtra("Fiber", str_fiber);
intent_warn.putExtra("Sugar", str_sugar);
intent_warn.putExtra("SatFat", str_satFat);
intent_warn.putExtra("TotFat", str_totFat);
intent_warn.putExtra("Cholesterol", str_cholesterol);
intent_warn.putExtra("Sodium", str_sodium);
intent_warn.putExtra("Potassium", str_potassium);
intent_warn.putExtra("Calories", str_calories);
intent_warn.putExtra("Warning", "Contains Dairy");
intent_warn.putExtra("WarningRed", true);
Log.e("Warning",intent_warn.getExtras().getString("Warning"));
context.startActivity(intent_warn);
overridePendingTransition(R.layout.fade_in, R.layout.fade_out); //THIS PART ISN'T WORKING//
}
else
{
Intent intent_menu = new Intent(context, DisplayScreen.class);
intent_menu.putExtra("Name", str_name);
intent_menu.putExtra("Size", str_size);
intent_menu.putExtra("Price", str_price);
intent_menu.putExtra("Carbs", str_carbs);
intent_menu.putExtra("Protein", str_protein);
intent_menu.putExtra("Fiber", str_fiber);
intent_menu.putExtra("Sugar", str_sugar);
intent_menu.putExtra("SatFat", str_satFat);
intent_menu.putExtra("TotFat", str_totFat);
intent_menu.putExtra("Cholesterol", str_cholesterol);
intent_menu.putExtra("Sodium", str_sodium);
intent_menu.putExtra("Potassium", str_potassium);
intent_menu.putExtra("Calories", str_calories);
intent_menu.putExtra("Warning", "Contains no allergens");
intent_menu.putExtra("WarningRed", false);
Log.e("Warning",intent_menu.getExtras().getString("Warning"));
context.startActivity(intent_menu);
}
Log.e("KYLE_DATA_UPCH",str_name+" "+str_price+""+str_size);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
else
{
Log.e("ServiceHandler", "Couldn't get any data from the url");
_errorCode=3;
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
...
}
}
So I actually was able to solve the problem by calling overridePendingTransition on the context, casted to an Activity.
((Activity) context).overridePendingTransition(R.layout.fade_in, R.layout.fade_out);
I realize that this is not the best practice and could get messy with a more complex application, but for our purposes right now I think this is ok. I would like to investigate #bariscan Kayaoglu's solution eventually, as it seems more robust.
Just to add some safety to Tims answer, check if the context is an instance of Activity before casting it:
if (context instanceof Activity) {
((Activity) context).overridePendingTransition(R.layout.fade_in, R.layout.fade_out);
}
This simply makes sure that you call a method that is really there. You could also use a try/catch, but I figure this will be enough
Better to create an interface and callback its method.
myInterface mInterface;
public interface myInterface {
public abstract void myTask();
}
public GetUPC(myInterface mInterface) {
this.mInterface = mInterface;
}
and in your doInBackground method, when you are done, call
mInterface.myTask();
Don't forget to implement your interface to your activity and send this to your constructor when you are creating your async task.
myAsyncTask = new GetUPC(this);
And your development platform will inform you to implement unimplemented methods like myTask(). You can do whatever you want in that method while you can access your activity.
I don't think that would be a good idea. Since your class is an Async Task, the activity you would choose may not be the active activity since your async task will work in background. But if you consider memory leaks and null pointers, you can just send your activity to your constructor.
You can't do any UI updation part from background thread, But if wanted to do the same then override onProgressUpdate of AsyncTask class and past your activity starting code in that. to invoke this methode call publishProgress . Before starting activity you have to cancel your AsyncTask otherwise your application will cress.
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);
}
Good day,
I have my main activity with an object,
public Network netConnection = null;
in my main activity i then call:
netConnection = new Network(new Network.OnMessageReceived() {
#Override
// here the messageReceived method is implemented
public void messageReceived(String message) {
// this method calls the onProgressUpdate
publishProgress(message);
}
});
netConnection.run();
Now i create a new activity and i run it with this code:
case R.id.menu_packet: {
Intent intent = new Intent(this, PacketActivity.class);
String id = "" + hashCode();
intent.putExtra("id", id);
startActivity(intent);
return true;
}
I have tried doing things with putExtra() in the intent etc. But i have not come right.
Is there not an easy way to just pass a reference to PacketActivity of my netConnection ?
I don't want to copy it or any thing. just be able to access the netConnection object from the PacketActivity?
Thanks
You can extend Application, create setter and getter method in your extended application, and then call it from new activity.
here a tutorial
useful links:
Extending Application
Extending Application to share variables globally
Android extends Application basics
e.g.
public class myApplication extends Application{
private myType myObj;
public void set_myObj(myType theThing){
myObj = theThing;
}
public myType get_myObj(){
return myObj;
}
}
then from you main activity:
((myApplication)getApplication()).set_myObj(myObj);
and from second activity:
myType myObj = ((myApplication)getApplication()).get_myObj();
and be careful with memory leaks..!
This sounds like a use case for a service:
http://developer.android.com/reference/android/app/Service.html
The thing is once the activity from which you created the Network object is destroyed e.g. to launch the new Activity then the Network object will also be garbage collected so I don't think passing a reference would help...
well my question is that there aren't pointers in JAVA ...
but when we have to start another activity we do like this :
Intent in = new Intent(MyActivity.this, NewActivity.class);
startAcitivity(in);
So my question is that what is the data type of MyActivity.this ??
In java pointers are not explicitly allowed,
However passing by reference(object) in Java is something which is implicitly based on pointer concept.
In your case, you are passing the context of parent class to child class,
which is actually passing by reference concept.
Hope this helps.
Writing MyActivity.this is the same as writing this, if you are in a non-nested class, or to top-level class.
See this example:
public class TopLevel{
public static void main(String[] args){
new TopLevel().printClass();
}
public TopLevel(){
new LowerLevel().printClass();
}
public void printClass(){
System.out.println("Outer Class: ");
// Will print something like "TopLevel.class"
System.out.println(this.getClass());
}
public class LowerLevel{
// This is a Nested-Class.
public void printClass(){
System.out.println("Nested Class: ");
// Will print "TopLevel$LowerLevel.class"
System.out.println(this.getClass());
// Will print "TopLevel.class" again
System.out.println(TopLevel.this.getClass());
}
}
}
Some using this in the nested-class does not reference to the same instance as when using it in the top-level class. Therefor, to get the "context" of the outer class in your nested class, you also specify the class you want the this-context from.