http://developer.android.com/reference/android/view/View.html#attr_android:onClick
Here it is said that
For instance, if you specify android:onClick="sayHello", you must declare a public void sayHello(View v) method of your context (typically, your Activity).
I'm intrested in "typically, your Activity"... And what if not typically? I'm creating a widget app so I don't have an activity at all...
Almost forgot..
And the question is: where should I write that sayHello method?
Here's the code which is responsible for the invacation:
try {
mHandler = getContext().getClass().getMethod(handlerName, View.class);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not find a method " +
handlerName + "(View) in the activity", e);
}
So basiclly it searches in the class which implements the context for the given method. Usually the context is an activity.
Related
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 have got an Activity class by:
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
String activityClassName = launchIntent.getComponent().getClassName();
Class<?> activityClazz = Class.forName(activityClassName);
Is it possible to create an instance of this Activity by using the activityClazz ? If so, how?
(My code is in a independent java class. Not in activity or service. )
Technically, you can create an instance of an Activity like this. However, this instance would be useless because its underlying Context would not have been set up.
The rule is that you should never ever create instances of Android components (Activity, Service, BroadcastReceiver, Provider) yourself (using the new keyword or other means). These classes should only ever be created by the Android framework, because Android sets up the underlying Context for these objects and also manages the lifecycle.
In short, your architecture is flawed if you need to create an instance of an Activity like this.
Class.forName() needs the fully qualified name - that is, the name of the package the class is contained in, plus the simple name of the class itself.
Assuming the package containing the class is called com.your.package, the code would have to be
String className = "com.your.package.Tab3"; // Change here
Object obj= null;
try {
obj= Class.forName(className).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
yes. you can get the activity context by using below line of code
Activity activity = (Activity) getContext();
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()
I'm using AsyncTask to download and parse data in a separate thread and I need to pass in the values returned by loadXml into the database.
The problem is that I can't instantiate the database because it requires a context and my DownloadXmlTask is in a separate class to the activity class where it is instantiated.
How do I use pass the values into the database if I can't instantiate the database class?
Code Sample:
public class DownloadXmlTask extends AsyncTask<String,Void,Void>{
public static final String TAG = "VotingApp";
#Override
protected Void doInBackground(String... urls) {
try {
// Get the parsed list of Candidate objects
ArrayList<Candidate> candidatesList = loadXml(urls[0]);
CandidatesDatabaseHelper db = new CandidatesDatabaseHelper(getApplicationContext()); <---- ERROR (I know I can't use getApplicationContext() here)
// Insert the candidates into the database
for(Candidate c : candidatesList){
//NOT FINISHED
}
} catch (IOException e) {
Log.d(TAG, "Error " + e);
} catch (XmlPullParserException e) {
Log.d(TAG, "Error " + e);
}
Log.d(TAG, "NOT WORKING");
return null;
}
You could solve that problem by making AsyncTask an inner class, but if you just do it the way you are currently doing it then technically you could do AsyncTask<Object,Void,Void>:
#Override
protected Void doInBackground(Object... urls) {
Context context = (Context)urls[0]; //should always be true by your own rules
/*then you can also loop the urls for the rest of the Strings to cast
**if there are going to be more. Or not. Your choice*/
//.....
instead of String. When calling .execute(this, someString), send it the Context first and the String second. Then you just cast each of them into their appropriate variables. Try that and let me know if it works. Can't test it out right now unfortunately so you're going to have to test it.
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.