Call LoaderManager from class which is not Activity - android

I'm working on to get contacts from phone, for this purpose I'm using LoaderCallbacks<Cursor> I create a new class with FetchContacts name and implement loaderManager. Now I want when ever I create object of that class loaderManager automatically initialize.
FetchContacts
public class FetchContacts implements LoaderManager.LoaderCallbacks<Cursor> {
private Context context;
FetchContacts(Context ctx){
context = ctx;
getLoaderManager().initLoader(0, null, this); // Error: Undefined method
}
// Reset of code like override methods.
MainActivity
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FetchContacts fetchContacts = new FetchContacts(this);
}
}
I know the reason of error because FetchContacts is not extend from Activity class. Is it necessary to extend it from Activity class or is there and other method to call it from MainActivity ?

Pass LoaderManager as an Argument as #Mike said.
FetchContacts
public class FetchContacts implements LoaderManager.LoaderCallbacks<Cursor> {
private Context context;
FetchContacts(Context ctx, LoaderManager loaderManager){
context = ctx;
loaderManager.initLoader(0, null, this);
}
// Reset of code like override methods.
MainActivity
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FetchContacts fetchContacts = new FetchContacts(this, getLoaderManager());
}
}

Related

Calling a method from another class is causing app to crash

I decided to try and make my code more object oriented and avoid repetitive code in another class.
Source code for Activities :
public class EasyMode extends MainActivity {
GameActivityPVP game = new GameActivityPVP();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
game.initializeButtons();
}
}
public class GameActivityPVP extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
initializeButtons();
}
public void initializeButtons() {
button[0] = (Button) findViewById(R.id.button1);
}
}
The second the program gets to the line where I try to call a method using game.methodName(); the program crashes. No compiling errors or anything.
I am new to programming in general so please take it easy on me and I tried to simplify my code as much as possible.
Android Monitor/logcat :
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
and
W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
You can use another class's method by creating object of parent class.
See below example;
Here you want to use method from 'GameActivityPVP' class. So you need to create one object in this class only.
public class GameActivityPVP extends MainActivity {
public static GameActivityPVP mGameActivity;
public GameActivityPVP getInstance(){
return mGameActivity; // assign value in onCreate() method.
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
mGameActivity = this; // Do not forget this, otherwise you'll get Exception here.
initializeButtons();
}
public void initializeButtons() {
button[0] = (Button) findViewById(R.id.button1);
}
}
Now use this Object in another class 'EasyMode' like this;
if(GameActivityPVP.getInstance()!=null){
GameActivityPVP.getInstance().initializeButtons();
}
Try This:
Make one Class Utils:
In Utils:
public class Utils{
private Activity context;
Button button;
public Utils(Activity context) {
this.context=context;
}
public void inititializeButton(Activity context){
button[0]= (Button) context.findViewById(R.id.button_flasher);
}
}
And in your Class use:
public class EasyMode extends MainActivity {
Utils utils;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
utils=new Utils(this);
utils.initializeButtons();
}
}
As already stated, you shouldn't use nested activities, they are not supposed to interact like this. If you want two activities to interact you have to do it through an intent. Regarding the duplicated code, you have few solution presented but my personal opinion is that the OOP rules are not followed. If I had to write that logic, I would create a BaseActivity to hold the common logic of the other two activities and use inheritance to extend them.
public class BaseActivity extends Activity {
protected List<Button> buttons = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
initializeButtons();
}
protected void initializeButtons() {
buttons.add((Button) findViewById(R.id.button1));
}
}
public class EasyMode extends BaseActivity {
// Add here logic that is used only in EasyMode activity
}
public class GameActivityPVP extends BaseActivity {
// Add here logic that is used only in GameActivityPVP activity
}
Note that in this way you don't have to override onCreate again to initialise the buttons and so on. Also, I saw that you used the same layout for both activities, but if you want to use different layouts you can do it as usual and then call initializeButtons.

Why getResources().getString() return null?

I always get NullPointerException whenever I call:
getApplicationContext().getResources().getStringArray(R.array.days);
I called it from DialogFragment in my Activity. I also tried using getActivity(), but that didn't work for me too. Does anybody have any idea about this problem?
Try this:
If you write this in a fragment:
String[] days = getActivity().getResources().getStringArray(R.array.days);
If you write this in an activity:
String[] days = this.getResources().getStringArray(R.array.days);
It´s just an assumption, but mostly if somebody gets this error, they make a mistake where the code is placed or when they call it. For example, if you call it before onCreate():
public class YourActivity extends Activity {
private String foo = "foo";
private String[] yourArray = getResources().getStringArray(R.array.yourArray);
public void onCreate(Bundle savedInstanceState){
...
}
}
This will result in a NullPointerException. Instead you have to call it like this:
public class YourActivity extends Activity {
private String foo = "foo";
private String[] yourArray;
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.yourLayout);
yourArray = getResources().getStringArray(R.array.yourArray);
}
}
Try this.
public class YourActivity extends Activity{
Context mContext;
public void onCreate(Bundle savedInstanceState){
setContentView(R.layout.yourLayout);
mContext = this;
}
class DialogFragment{
String[] days = mContext.getResources().getStringArray(R.array.days);
...............
}
}
I hope it helps!

Android Main Activity Object Access

Im new to Android and got a problem. I wanted to seperate the OnClickListener from the MainActivity class but I don't know how to access the Objects in the Main Activity class except of using static. Would be happy about a solution.
public class MainActivity extends ActionBarActivity {
public Button btn;
public TextView tv;
public MyListener listener;
public MainActivity() {
this.listener = new MyListener();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.btn = (Button) findViewById(R.id.btn1);
this.tv = (TextView) findViewById(R.id.textView1);
this.btn.setOnClickListener(listener);
}
}
public class MyListener implements OnClickListener {
MainActivity activity;
#Override
public void onClick(View v) {
activity.tv.setText("Hi");
}
}
Doesnt work.
I would appreciate any help.
I don't see why you would want them separated like that.
If you don't want to cram the onCreate method of your activity, just implement the listener in your class like so:
public class MainActivity extends ActionBarActivity implements OnClickListener {
...
}
Then reference the listener with this:
this.btn.setOnClickListener(this);
MainActivity is a Activity class. You should not have constructors for the same. You should not instantiate a activity class. You only declare activities in manifest file
You can have this.listener = new MyListener(); in onCreate itself
Make MyListener an inner class of MainActivity

How to implement parent methods to activity and FragmentActivity?

I am working on an android application,
and I have number of activities that extend from a custom activity.
Now I created a new FragmentActivity and I need the same functions that I have implemented in my custom activity.
How can I do that?
Edit
This is an simple example
public class BaseActivity extends Activity
{
protected void someFunction()
{
Log.i("TEST","This is a test");
}
}
public class MainActivity extends BaseActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
someFunction();
}
}
this is my FragmentActivity:
public class MyFragmentActivity extends FragmentActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// here I want to use someFunction()..
}
}
In Java you can't extend more than one class.
So I guess you should extend BaseActivity from FragmentActivity instead of Activity

Toast from implemented callback

I have an activity that roughly follows this structure:
public class myActivity extends Activity implements myCallback{
//Code
#Override
public void onCreate(Bundle savedInstaceState){
super.onCreate(savedInstanceState);
new myAsyncTask(myActivity.this).execute();
}
public void myCallback(Context context){
//Code
Toast.makeText(context,"Hello",Toast.LENGTH_SHORT).show();
}
}
And myAsyncTask has the myCallback() interface defined and it calls it eventually. No matter what I do, whatever UI element I try to show, be it a Toast or a ProgressDialog, it won't show. Nor do I get any exceptions. The rest of the callback code gets perfectly executed. Why is this?
Try using:
public class myActivity extends Activity implements myCallback{
//Code
Context mContext;
#Override
public void onCreate(Bundle savedInstaceState){
super.onCreate(savedInstanceState);
mContext = this;
new myAsyncTask(getApplicationContext()).execute();
}
public void myCallback(Context context){
//Code
Toast.makeText(mContext,"Hello",Toast.LENGTH_SHORT).show();
}
}
Instead of using context , use getApplicationContext... i hope it will show toast... like this
Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();

Categories

Resources