it is probably an noob question but still. I need to my main activity class will use other class to do some code. This class uses function that are from Activity like getPackageName(), new Intent etc.
So I need some help with this, for example what I need it to setContentView via class. How do I do this?
Main Acticity:
package com.example.testapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SetContentView cn = new SetContentView();
cn.MySetContentView(R.layout.activity_main);
}
}
SetViewClass:
package com.example.testapp;
public class SetContentView
{
void MySetContentView(int activityMain)
{
setContentView(R.layout.activity_main); //no set content view if not activity
}
}
public class MainActivity extends Activity
{
private static MainActivity instance;
public static MainActivity getInstance() {
return instance;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance=this;
}
}
public class OtherClass
{
protected void someMethod() {
MainActivity ma= MainActivity.getInstance();
//use ma methods...
}
}
If I'm getting it right, you could try having a root class extending Activity and holding your methods, and then extending it in MainActivity:
public class Helper extends Activity {
... // your methods, e.g. MySetContentView
}
and then:
public class MainActivity extends Helper {
... // any call to methods in Helper
}
This can be useful if you have a lot of activities that share the same code - you can have them all extending the same Helper class, and still being Activities.
In your case:
public class Helper extends Activity {
public void mySetContentView(int layout) {
setContentView(layout)
}
}
and then:
public class MainActivity extends Helper {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mySetContentView(R.layout.your_layout);
}
Related
I created a ListDialog extending a DialogFragment class and I have a problem with understanding of this code in the DijalogX class
((MainActivity)getActivity()).setTextField(selectedItem);
I understand that with this code above I put selected String variable to the setTextField method as an argument and after that this variable is showed in TextView on MainActivity class.
My questions:
Why I need a cast from getActivity() to the MainActivity and how I get access from DijalogX(fragment) to the method setTextField in MainActivity? Please explain a little about this process.
I also tried instead of ((MainActivity)getActivity()).setTextField(selectedItem)
use an Interface and everything works nice and I got the same resoult but I am wondering what is better solution here Interface or ((MainActivity)getActivity()).setTextField(selectedItem)?
MainActivity
package com.example.dezox.dijaloglist;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity{
private Button btnStartDialog;
private TextView tvSelectedOption;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initWidgets();
setupListener();
}
private void initWidgets() {
btnStartDialog = findViewById(R.id.btnDialog);
tvSelectedOption = findViewById(R.id.tvselectedOption);
}
private void setupListener() {
btnStartDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DijalogX dijalogX = new DijalogX();
dijalogX.show(getSupportFragmentManager(), "dx");
tvSelectedOption.setText("");
}
});
}
public void setTextField(String odabrano){
tvSelectedOption.setText(odabrano);
}
public String getTextField(){
return tvSelectedOption.getText().toString();
}
}
DijalogX
package com.example.dezox.dijaloglist;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
public class DijalogX extends DialogFragment {
private String[] languageList;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initListResource();
}
private void initListResource() {
languageList = getResources().getStringArray(R.array.language_list);
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),
android.R.style.Theme_Material_Dialog_Alert)
.setTitle("Select Language: ")
.setItems(languageList, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String selectedItem = languageList[which];
//THIS PART OF THE CODE I DONT UNDERSTAND:
((MainActivity)getActivity()).setTextField(selectedItem);
}
});
return builder.create();
}
}
You have declared a method in MainActivity called setTextField. If you called
Activity a = getActivity();
you would not be able to call your custom method (it is on your derived class, not the base Activity class).
a.setTextField(selectedIte); // WON'T WORK - NO SUCH METHOD
If instead you call
MainActivity ma = (MainActivity)getActivity();
it is now cast as your derived class and you can then call
ma.setTextField(selectedItem);
Doing it in two lines like this is the same as calling the one-liner in your code
((MainActivity)getActivity()).setTextField(selectedItem);
As far as casting vs. an interface, an interface is a bit more flexible of an approach. If you tried to use this fragment in a different activity (not MainActivity) the casting approach would fail. If you are only ever going to use the fragment in this Activity then either would work.
I call FacebookSdk.sdkInitialize(getApplicationContext()) in my GlobalActivity.
public class GlobalActivity extends Application {
#Override
public void onCreate() {
super.onCreate();
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
}
}
Do I need to call it again each time I am using facebook sdk?
I have a Fragment with a LoginButton.
public class LoginFragment extends Fragment{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
}
}
Simple way is Initialize once in Application class thats enough. when new activity created FacebookSdk automatically Initialized.
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
public class ApplicationName extends Application {
#Override
public void onCreate() {
super.onCreate();
// Initialize the SDK before executing any other operations,
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
}
}
I have a broadcast receiver in my app which is fired every time the user gets an incoming call. Now, when it happens, I need the broadcast receiver to invoke a specific method in a specific activity. Now, I tried to make this method static and therefore available, but something tells me it is a very bad idea.
Accordingly, I tried to instantiate the broadcast receiver inside my activity without declaring it in my manifest but the problem is - when the app is off, the activity dosn't exist and therefore I can't invoke my method.
So my question is - How can I invoke this method when the broadcast receiver is fired up, without making it "public static"?
Here is my activity code(I have deleted the irrelevant parts)
package com.silverfix.ringo.activities;
import com.silverfix.ringo.R;
import com.silverfix.ringo.activities.fragments.DataManagerFragment;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
public class RingtonesActivity extends Activity{
private DataManagerFragment dataManagerFragment;
private IntentFilter filter;
private BroadcastReceiver phoneCall;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ringtones);
ActionBar ab = getActionBar();
ab.setDisplayShowTitleEnabled(false);
ab.setDisplayHomeAsUpEnabled(true);
dataManagerFragment = new DataManagerFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(dataManagerFragment, "DataManagerFragment");
ft.commit();
filter = new IntentFilter();
filter.addAction("android.intent.action.PHONE_STATE");
phoneCall = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
dataManagerFragment.act();
}
};
registerReceiver(phoneCall, filter);
}
}
You can use observers , like
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
ObservableObject.getInstance().updateValue(intent);
}
}
public class MainActivity extends Activity implements Observer {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ObservableObject.getInstance().addObserver(this);
}
#Override
public void update(Observable observable, Object data) {
Toast.makeText(this, String.valueOf("activity observer " + data), Toast.LENGTH_SHORT).show();
}
}
public class ObservableObject extends Observable {
private static ObservableObject instance = new ObservableObject();
public static ObservableObject getInstance() {
return instance;
}
private ObservableObject() {
}
public void updateValue(Object data) {
synchronized (this) {
setChanged();
notifyObservers(data);
}
}
}
Receiver can be used via manifest.
ObservableObject - must be singleton.
This might help: how can I notify a running activity from a broadcast receiver?
Also, you can try using Observers
Something like:
public class BroadcastObserver extends Observable {
private void triggerObservers() {
setChanged();
notifyObservers();
}
public void change() {
triggerObservers();
}
}
In your broadcast receiver:
#Override
public void onReceive(Context context, Intent intent) {
BroadcastObserver bco = new BroadcastObserver();
bco.change();
}
and the Activity:
public class YourActivity extends Activity implements
Observer {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BroadcastObserver bco = new BroadcastObserver();
bco.addObserver(this);
}
#Override
public void update() {
//TODO: call your desired function
}
}
If anyone needs two-way communication between a BroadcastReceiver and a Activity, I wrote this utility class which simplifies invoking Methods on each other while still being memory-safe.
https://gist.github.com/Jenjen1324/4a0c03beff827082cb641fc8fe2c4e71
I am currently trying to learn how to use Loaders and am having trouble starting a Loader in my activity.
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
public class ASwitchActivity extends Activity implements
LoaderManager.LoaderCallbacks<SampleLoader.SampleLoaderResult> {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getLoaderManager().initLoader(0, null, this);
}
public Loader<SampleLoader.SampleLoaderResult> onCreateLoader(int id, Bundle args) {
return new SampleLoader(getBaseContext(), account, "dog");
}
public void onLoadFinished(Loader<SampleLoader.SampleLoaderResult> loader, SampleLoader.SampleLoaderResult out)
{
TextView t=(TextView)findViewById(R.id.testTV);
t.setText("yay");
}
public void onLoaderReset(Loader<SampleLoader.SampleLoaderResult> loader){
}
}
However Eclipse gives an error stating:
The method initLoader(int, Bundle, LoaderManager.LoaderCallbacks)
in the type LoaderManager is not applicable for the arguments (int,
null, ActivitySwitchActivity)
Can anyone help with where I am going wrong?
As I can see you use supportV4 library.
So to implement Loader you should do some things:
extend your activity from FragmentActivity class
Use getSupportLoaderManager method instead of getLoaderManager
here is sample code:
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.widget.Toast;
public class MyActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Object> {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getSupportLoaderManager().initLoader(0, null, this);
}
#Override
public Loader<Object> onCreateLoader(int i, Bundle bundle){
return null; // TODO
}
#Override
public void onLoadFinished(Loader loader, Object o) {
Toast.makeText(this, "onLoadFinished", Toast.LENGTH_SHORT).show();
}
#Override
public void onLoaderReset(Loader loader) {
Toast.makeText(this, "onLoaderReset", Toast.LENGTH_SHORT).show();
}
}
When using loaders with fragments use:
getLoaderManager().initLoader(0,null,this);
And when using loaders with Activity use:
getSupportLoaderManager().initLoader(0,null,this);
The third parameter for getLoaderManager().initLoader(0, null, this); should be a instance that implement interface LoaderManager.LoaderCallbacks
So you should implement the interface first.
For AppCompatActivity use getSupportLoaderManager().initLoader(0,null,this); for initializing the loader.
I am trying to run this Android unit test, following this tutorial ::
http://developer.android.com/resources/tutorials/testing/helloandroid_test.html
and in doing so get a SuperNotCalledException
Here's the test class code ::
package com.example.helloandroid2.test;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.TextView;
import com.example.helloandroid2.HelloAndroid2Activity;
public class HelloAndroid2Test extends ActivityInstrumentationTestCase2<HelloAndroid2Activity>
{
private HelloAndroid2Activity mActivity;
private TextView mView;
private String resourceString;
public HelloAndroid2Test()
{
super("com.example.helloandroid2", HelloAndroid2Activity.class);
}
#Override
protected void setUp() throws Exception
{
super.setUp();
mActivity = this.getActivity();
mView = (TextView) mActivity.findViewById(com.example.helloandroid2.R.id.textview);
resourceString = mActivity.getString(com.example.helloandroid2.R.string.hello);
}
public void testPreconditions()
{
assertNotNull(mView);
}
public void testText()
{
assertEquals(resourceString,(String)mView.getText());
}
}
The class I'm actually testing ::
package com.example.helloandroid2;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroid2Activity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);
}
}
I've set the project API levels at 2_3_1 and am using an avd set at the same.
Am running Eclipse with ADT on Windows Vista.
All wisdom greatfully recieved. Thanks in advance.
Chris
Your onCreate() method in HelloAndroid2Activity needs to call super.onCreate(savedInstanceState);
public class HelloAndroid2Activity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}