how use getContentResolver in a class without activity? - android

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

Related

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

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

How to reference the current or main activity from another class

I often find myself needing to access methods that require referencing some activity. For example, to use getWindowManager, I need to access some Activity. But often my code for using these methods is in some other class that has no reference to an activity. Up until now, I've either stored a reference to the main activity or passed the context of some activity to the class. Is there some better way to do this?
If you already have a valid context, just use this:
Activity activity = (Activity) context;
Passing context is better way for refrence Activity.
You can pass Context to another class.
IN Activity ::
AnotherClass Obj = new AnotherClass(this);
IN Another Class
class AnotherClass{
public AnotherClass(Context Context){
}
}
You can implement the necessary methods in your activity and implement a Handler. Then, simply pass a handler instance to your classes, where you can obtain a message for handler and send it to target.
You can make you application instance a singleton, and use it when you need a Context
An example is in this question:
Android Application as Singleton
This way, when you need a Context, you can get it with
Context context = MyApplication.getInstance()
This might not be the cleanest solution, but it has worked well for me so far
I found a way to get the Activity to a non-activity class that I have not seen discussed in forums. This was after numerous failed attempts at using getApplicationContext() and of passing the context in as a parameter to constructors, none of which gave Activity. I saw that my adapters were casting the incoming context to Activity so I made the same cast to my non-activity class constructors:
public class HandleDropdown extends Application{
...
public Activity activity;
...
public HandleDropdown() {
super();
}
public HandleDropdown(Activity context) {
this.activity = context;
this.context = context;
}
public void DropList(View v,Activity context) {
this.activity = context;
this.context = context;
...
}
After doing this cast conversion of Context to Activity I could use this.activity wherever I needed an Activity context.
I'm new to android so my suggestion may look guffy but what if you'll just create a reference to your activity as private property and assign that in OnCreate method? You can even create your CustomActivity with OnCreate like that and derive all your activities from your CustomActivity, not the generic Activity provided by android.
class blah extends Activity{
private Activity activityReference;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityReference = this;
}
}
after that you could use that the way you want, i.e. in
Intent i = new Intent(activityReference, SomeOtherActivity.class)
etc
There are many ways for Activities communication.
you can use:
the startActivityForResult method
a system of broadcast message and receiver (you can broadcast an event from the actual activity, and register a receiver in the target activity. Remember that the target activity must be previously initialized and non finished)
as you say, store a reference of the target activity wherever you need.
We built a framework for this. We have a BaseActivity class that inherits from Activity and it overrides all the lifecycle methods and has some static (class) variables that keep track of the activity stack. If anything wants to know what the current activity is, it just calls a static method in BaseActivity that returns the activity on top of our privately-managed stack.
It is kinda hacky, but it works. I'm not sure I would recommend it though.
Handle the Intent in the class you want to do these methods, and send your information to it in a Bundle like so:
Intent i = new Intent("android.intent.action.MAIN");
i.setComponent(new ComponentName("com.my.pkg","com.my.pkg.myActivity"));
Bundle data = new Bundle();
i.putExtras(data);
startActivityForResult(i);
Then use an OnActivityResultListener to grab the new data.
I solved this by making a singleton class has an instance of the class below as a member.
public class InterActivityReferrer <T> {
HashMap<Integer, T> map;
ArrayList<Integer> reserve;
public InterActivityReferrer() {
map = new HashMap<>();
reserve = new ArrayList<>();
}
public synchronized int attach(T obj) {
int id;
if (reserve.isEmpty()) {
id = reserve.size();
}
else {
id = reserve.remove(reserve.size() - 1);
}
map.put(id, obj);
return id;
}
public synchronized T get(int id) {
return map.get(id);
}
public synchronized T detach(int id) {
T obj = map.remove(id);
if (obj != null) reserve.add(id);
return obj;
}
}
This class can get a T object and return a unique integer assigned to the object by attach(). Assigned integers will not collide with each other unless HashMap fails. Each assigned integer will be freed when its corresponding object is detached by detach(). Freed integers will be reused when a new object is attached.
And from a singleton class:
public class SomeSingleton {
...
private InterActivityReferrer<Activity> referrer = new InterActivityReferrer<>();
...
public InterActivityReferrer<Activity> getReferrer() {return referrer;}
}
And from an activity that needs to be referred:
...
int activityID = SomeSingleton.getInstance().getReferrer().attach(this);
...
Now with this, a unique integer corresponding to this activity instance is returned. And an integer can be delivered into another starting activity by using Intent and putExtra().
...
Intent i = new Intent(this, AnotherActivity.class);
i.putExtra("thisActivityID", activityID);
startActivityForResult(i, SOME_INTEGER);
...
And from the another activity:
...
id refereeID = getIntent().getIntExtra("thisActivityID", -1);
Activity referredActivity = SomeSingleton.getInstance().getReferrer().get(refereeID);
...
And finally the activity can be referred. And InterActivityReferrer can be used for any other class.
I hope this helps.
public static Activity getLaunchActivity()
{
final Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
final Method methodApp = activityThreadClass.getMethod("currentApplication");
App = (Application) methodApp.invoke(null, (Object[]) null);
Intent launcherIntent = App.getPackageManager().getLaunchIntentForPackage(App.getPackageName());
launchActivityInfo = launcherIntent.resolveActivityInfo(App.getPackageManager(), 0);
Class<?> clazz;
try
{
clazz = Class.forName(launchActivityInfo.name);
if(clazz != null)
return Activity.class.cast(clazz.newInstance());
}
catch (Exception e)
{}
return null;
}
Just a guess since I haven't done this but it might work.
1) Get your applicationContext by making your Android Application class a Singleton.
2) Get your ActivityManager class from the context.
3) Get a list of RunningTaskInfos using getRunningTasks() on the ActivityManager.
4) Get the first RunningTaskInfo element from the list which should be the most recent task launched.
5) Call topActivity on that RunningTaskInfo which should return you the top activity on the activity stack for that task.
Now, this seems like a LOT more work than any of the other methods mentioned here, but you can probably encapsulate this in a static class and just call it whenever. It seems like it might be the only way to get the top activity on the stack without adding references to the activities.

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.

Passing a null context to a database helper

I have a static function that gets called whenever my background service gets a new location. In this function I want to take to coordinates passed in and save them in my database. Can I pass 'null' as the context to create an instance of the database helper or is there a better way to do this. Thanks.
public static void locationHasChanged() {
final wd_DatabaseHelper helper = new wd_DatabaseHelper(null, "myDB.db", null, 1);
}
Probably not. Usually your Database helper extends SQLiteOpenHelper and the context will be used to call the openOrCreateDatabase() or the getDatabasePath(). I can't say for sure without seeing the code of wd_DatabaseHelper but having a null context is never a good idea. See for your self ... Source of SQLiteOpenHelper
since an android Service is a context you can pass "this of the service" into your method
public class MyLocationHelper {
public static void locationHasChanged(Context context) {
final wd_DatabaseHelper helper = new wd_DatabaseHelper(context, "myDB.db", null, 1);
....
}
}
public class MyService extends Service {
private void onLocationHasChanged()
{
MyLocationHelper.locationHasChanged(this);
}
}

openOrCreateDatabase in different class causes null pointer exception

I have defined a new class to use in my project and I get null pointer exception in the context
Here is what i coded :
public class OurClass extends Activity {
private dha mContext;
private dhaService sContext;
public OurClass(dha dha) {
sContext=null;
mContext = dha;
}
public OurClass(dhaService dhx) {
sContext = dhx;
mContext=null;
}
public void put_default_value( String varname, String value) {
Log.i("dha", "d1");
SQLiteDatabase db;
Log.i("dha", "d1.5");
if (mContext==null) {
Log.i("dha", "dx1");
db = sContext.openOrCreateDatabase("gipi.db", SQLiteDatabase.CREATE_IF_NECESSARY,null);
Log.i("dha", "dx2");
} else {
Log.i("dha", "dz1");
db = android.database.sqlite.SQLiteDatabase.openOrCreateDatabase("gipi.db", null);
Log.i("dha", "dz2");
}
You're not actually checking that the Contexts are valid before using them.
For example, if OurClass(dhaService dhx) is called with a null Context, then putDefaultValue will fail with a NullPointerException because sContext is assigned the value of dhx without checking either dhx or sContext for valid values.
On a side note, neither sContext, nor mContext are being initialised, which means that with the lack of proper checking you have right now, you could easily inadvertently call put_default_value, while never actually having called either of the constructors. This is not best practice.
EDIT:
One way to help guard against this is to make the default constructor private, so that an instance of the class must be created by calling one of the constructors you have provided:
private:
OurClass ( void ) {
}
Even if you do that, you still need to properly validate your inputs to at least detect null pointers - you can't just assume it will all work as you intend, since it clearly isn't right now.

Categories

Resources