Using GoogleApiClient in Fragment Android - google-maps

I tried to load a Google map into a fragment. I don't know what the three lines should be... (the three lines commented with "problem!").
Most examples are using "this" in the parenthesis. I understand this is a fragment, not an activity, so I used "getActivity()" instead. But if I changed all three lines to getActivity(), it didn't work either. Please help! Thanks in advance!
public class MapFragment extends Fragment implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,com.google.android.gms.location.LocationListener {
private static final String TAG = "***MapFragment***";
private final int PERMISSION_CODE = 1;
private GoogleApiClient myGoogleApiClient;
private GoogleMap myMap;
private Location curLocation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_target, container, false);
// create api client
if (myGoogleApiClient == null) {
myGoogleApiClient = new GoogleApiClient.Builder(getActivity()) // problem!
.addConnectionCallbacks(this) // problem!
.addOnConnectionFailedListener(this) // problem!
.addApi(LocationServices.API)
.build();
}

Here need context, u can use getActivity()
new GoogleApiClient.Builder(getActivity()) // problem!
Below two methods need callback, so your fragment must implement ConnectionCallbacks, OnConnectionFailedListener listeners.
.addConnectionCallbacks(this) // problem!
.addOnConnectionFailedListener(this) // problem!
Explanation
.addConnectionCallbacks method needs ConnectionCallbacks
.addOnConnectionFailedListener method needs OnConnectionFailedListener
You already implemented them
public class MapFragment extends Fragment implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
...
}
So, 'this' here refers your MapFragment class. And when u pass 'this' in above methods, they uses their callbacks.

Related

How to verify an internal method call using Powermock?

I am trying to use PowerMockito to test a save method by verifying an internal audit() method call.
This internal call is made by auditor object which is being instantiated in an init() method of the class. As it is not injected I will not be able to mock it directly. When I used Mockito to verify it always said "There were zero interaction with the mock".
Question:How exactly do I test the save feature? Kindly help!
public class DaoImpl implements Dao{
private Auditor auditor;
#InjectValue
private ObjectLoader loader;
#InjectValue
private ConfigurationProvider confProvider;
#PostConstruct
public void init() {
//Mock this object instantiation and verify audit is called once
auditor = new SyncAuditor(confProvider.getClientConfiguration(), new EventRegProvider());
}
#Override
public void save(final AuditEvt auditEvt) {
final AuditedEvent auditedEvent = builder.build();
auditor.audit(auditedEvent);
}
Test :
#RunWith(PowerMockRunner.class)
#PrepareForTest({ DaoImplTest.class })
#PowerMockIgnore("javax.management.*")
public class DaoImplTest extends PowerMockito {
#InjectMocks
private DaoImpl dataAccess;
#Mock
private SynchAuditor auditorMock;
#Before
public void setUp() throws Exception {
loader = ObjectLoader.init("JUNIT");
loader.bind(ConfigurationProvider.class, configurationProviderMock);
dataAccess = loader.newInstance(DaoImpl.class);
}
#After
public void tearDown() {
loader.release(dataAccess);
ConnectionMgr.disconnect("JUNIT");
}
#Test
public void testSaveAuditEvent() throws Exception {
PowerMockito.whenNew(SynchAuditor.class).
withArguments(Matchers.any(ClientConfiguration.class), Matchers.any(EventRegProvider.class)).thenReturn(this.auditorMock);
final AuditEvent event = AuditEvent.from(null, "principal", UUID.randomUUID().toString(), "randomText",
new AuditEvtDefn((long) 522, "234242", "234242fdgd", true), SUCCESS, null, new GregorianCalendar());
dataAccess.save(event);
Mockito.verify(auditorMock, times(1)).audit(Matchers.any(AuditedEvent.class));
}
Even PowerMockito.verifyNew says there were zero interaction
PowerMockito.verifyNew(SynchronousAuditor.class,times(1)).withArguments(Matchers.any(AuditorClientConfiguration.class),Matchers.any(EventRegistrationProvider.class));
So, I figured out that java reflection will help in such a situation. You will have to get hold onto the real object and then set mocked object to it.
final Field privateAuditorField = DaoImpl.class.getDeclaredField("auditor");
privateAuditorField.setAccessible(true);
privateAuditorField.set(dataAccess, auditorMock);
Now verify will run sucessfully.
Mockito.verify(auditorMock, Mockito.times(1)).audit(Matchers.any(AuditedEvent.class));

JProgress Bar Indeterminate mode not updating

I have a JNI function that can take a while to complete, and I want a JProgress bar in indeterminate mode running while it is finishing the function. I have read the tutorials provided by Oracle, but the nature of their tutorials doesn't seem to help me understand how to do it. I realize that I should be running this function in a background thread, but I'm not quite sure how to do it.
Here is relevant code. I have a button (runButton) that will call the function, mainCpp(), when pressed:
public class Foo extends javax.swing.JFrame
implements ActionListener,
PropertyChangeListener{
#Override
public void actionPerformed(ActionEvent ae){
//Don't know what goes here, I don't think it is necessary though because I do not intend to use a determinate progress bar
}
#Override
public void propertyChange(PropertyChangeEvent pce){
//I don't intend on using an determinate progress bar, so I also do not think this is necassary
}
class Task extends SwingWorker<Void, Void>{
#Override
public Void doInBackground{
Foo t = new Foo();
t.mainCpp();
System.out.println("Done...");
}
return null;
}
/*JNI Function Declaration*/
public native int mainCpp(); //The original function takes arguments, but I have ommitted them for simplicity. If they are part of the problem, I can put them back in.
...//some codes about GUI
private void runButtonActionPerformed(java.awt.event.ActionEvent evt) {
ProgressBar.setIndeterminate(true);
Task task = new Task();
task.execute();
ProgressBar.setIndeterminate(false);
}
/*Declarations*/
private javax.swing.JButton runButton;
}
Any help would be appreciated.
EDIT: Editted in an attempt to do what kiheru suggested, but still does not work.
Assuming you have a SwingWorker like this:
class Task extends SwingWorker<Void, Void>{
#Override
public Void doInBackground() {
// I'm not sure of the code snippets if you are already in a
// Foo instance; if this is internal to Foo then you obviously do
// not need to create another instance, but just call mainCpp().
Foo t = new Foo();
t.mainCpp();
return null;
}
#Override
public void done()
// Stop progress bar, etc
...
}
}
You can either keep an instance in a field of the containing object, and then using it would work like this:
private void runButtonActionPerformed(java.awt.event.ActionEvent evt) {
// Start progress bar, disable the button, etc.
...
// Task task has been created earlier, maybe in the constructor
task.execute();
}
, or you can create a worker in place:
private void runButtonActionPerformed(java.awt.event.ActionEvent evt) {
// Start progress bar, disable the button, etc.
...
new Task().execute();
}

JMockit mock protected method in superclass and still test method in real child class

I am still learning JMockit and need help understanding it.
I am testing a class that uses superclass methods. My test gets a null pointer when it attempts to use the superclass method due to code inside it that uses struts action context to get the session and pull an object from the session.
The method I want to bypass the struts session stuff inside the protected method.
public class MyExtendingClass extends MySuperClass{
public void methodIamTesting(){///}
}
public abstract class MySuperClass{
//I want to mock this method
protected Object myProtectedSuperClassMethod(){
// struts action context code that returns an object//}
}
Test code
#Test
public void testRunsAndDoesntPass() {
Mockit.setUpMock(MySuperClass.class, new MySuperClass(){
public Object myProtectedSuperClassMethod() {
return object;
}
});
// real class method invocation happens
assertEquals(expected, actual);
}
I keep getting NullPointers just like if I didn't have the mock
Not sure what to try next. All the docs and code samples I have read say to just declare the superclass method as public in the setUpMock and it should work.
I can't mock the entire class because that is the class I am testing.
I discovered that I needed to create the MockClass then reference it using setupmock correctly.
I am really falling in love with JMockit.
#MockClass(realClass = MyExtendingClass.class)
public static class MockSuperClass {
final Object object = new Object();
#Mock
public Object myProtectedSuperClassMethod() {
return object;
}}
#Test
public void testRunsAndNowWillPass() {
Mockit.setUpMock(MySuperClass.class, new MockSuperClass(){
public Object myProtectedSuperClassMethod() {
return object;
}});
// real class method invocation happens where i set expected and actual
assertEquals(expected, actual);
}
you mask the parent class implementation out totally #Mocked final MySuperClass base
abstract class MySuperClass{
protected Object myProtectedSuperClassMethod(){
}
class MyExtendingClass extends MySuperClass{
public void methodIamTesting(){///}
}
#Test
public void testRunsAndDoesntPass(#Mocked final MySuperClass base ) {
//you could mask out all the base class implementation like this
new Expectations(){{
invoke(base, "myProtectedSuperClassMethod");
}};
// real class method invocation happens
// ...
assertEquals(expected, actual);
}

Getting a list of all JADE containers

I want to get a list of all containers in the current platform. This question is similar, but the answer is obsolete and the method is by querying to the AMS agent. Is there any simpler way out than to communicate via ACL messages which I think is complex, there should be a way out to get a simple list of containers. Thanks for your help
You can achieve this by using the AMSSubscriber class and listen to the events when a container is added or removed. See sample code below:
public class myAgent extends Agent {
private ArrayList<ContainerID> availableContainers = new ArrayList<ContainerID>();
/**
* Agent initializations
**/
protected void setup() {
AMSSubscriber subscriber = new AMSSubscriber(){
protected void installHandlers(Map handlers){
EventHandler addedHandler = new EventHandler(){
public void handle(Event event){
AddedContainer addedContainer = (AddedContainer) event;
availableContainers.add(addedContainer.getContainer());
}
};
handlers.put(IntrospectionVocabulary.ADDEDCONTAINER,addedHandler);
EventHandler removedHandler = new EventHandler(){
public void handle(Event event){
RemovedContainer removedContainer = (RemovedContainer) event;
ArrayList<ContainerID> temp = new ArrayList<ContainerID>(availableContainers);
for(ContainerID container : temp){
if(container.getID().equalsIgnoreCase(removedContainer.getContainer().getID()))
availableContainers.remove(container);
}
}
};
handlers.put(IntrospectionVocabulary.REMOVEDCONTAINER,removedHandler);
}
};
addBehaviour(subscriber);
}
}
Reference: 1) Developing multi-agent systems with JADE
By Fabio Luigi Bellifemine, Giovanni Caire, Dominic Greenwood (page 111)
2) Jade API

load html at listview item onclick

I'm now stuck in html loading from my assets folder. I've several html pages under assets folder and have to load those at listview item onclick. Each listview item own their html pages.Does anybody know how i can get onclick event and how to show specific html pages ?
Thanks
public class WebViewWithListActivity extends Activity {
private String lv_arr[] = { "Android", "iPhone", "BlackBerry"};
ListView lv1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv1 = (ListView) findViewById(R.id.listView1);
lv1.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, lv_arr));
lv1.setTextFilterEnabled(true);
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long id)
{
AlertDialog.Builder adb = new AlertDialog.Builder(WebViewWithListActivity.this);
adb.setTitle("Selected item");
adb.setMessage("Selected Item is = "
+ lv1.getItemAtPosition(position));
adb.setPositiveButton("Ok", null);
Log.i("Selected item is ",(String) lv1.getItemAtPosition(position)+"" );
adb.show();
//TextView tvUrl = (TextView) view.findViewById(R.id.item2);
TextView tvUrl=(TextView) findViewById(R.id.item2);
if(lv1.getItemAtPosition(position).equals("Android"))
{
GlobalVariable.SetURL("http://www.google.co.in/");
Log.i("Global vari : ",GlobalVariable.GetURL());
Intent i = new Intent(WebViewWithListActivity.this,WebViewDemo.class);
//i.putExtra("http://www.google.co.in/", tvUrl.getText());
startActivity(i);
}
}
});
}
}
This is WebViewDemo. I simply extended Activity:
public class WebViewDemo extends Activity{
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_webview);
//String url =getIntent().getStringExtra("url");//get url that pass from the other screen
//Log.i("url ", url+"");
Log.i("Global vari : ",GlobalVariable.GetURL());
webView = (WebView)findViewById(R.id.wvDisplay);
WebSettings webSetting= webView.getSettings(); //create new settings for webView
webSetting.setJavaScriptEnabled(true); // enabled javascript
webView.setWebViewClient(new WebViewClient()); //set up webviewclient, this set not to open the default browser when link click
//Log.i("url ", url+"");
webView.loadUrl(GlobalVariable.GetURL());//load the web page
}
}
public class GlobalVariable extends Application{
private static String url;
public static String GetURL()
{
return url;
}
public static void SetURL(String URL) {
url = URL;
}
}
You can use ListView's setOnItemClickListener method to get click event on list items.
You can use WebView's loadUrl method to show your html pages. See WebView tutorial.
Dude ... give up ... it won't work -- no way to get this listener working when you have a webview inside a listview
You can use a custom webViewClient and catch links in the html, then you can do what ever you want will the clicks.