I followed google guide:
updated build.gradle dependencies
updated AndroidManifest.xml
updated the AndroidLauncher and tried banner ads first
from libgdx wiki https://libgdx.com/wiki/third-party/admob-in-libgdx
#Override public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libGDX View
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
View gameView = initializeForView(new mygame(), config);
// Create and setup the AdMob view
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111"); // Put in your secret key here
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
// Add the libGDX view
layout.addView(gameView);
// Add the AdMob view
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
adParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layout.addView(adView, adParams);
// Hook it all up
setContentView(layout);
}}
but I cant figure out how to do the same for Interstitial ads
i tried adding adscontroller interface
public interface AdsController {
public void loadInterstitialAd();
public void showInterstitialAd();
}
and updating AndroidLauncher
public class AndroidLauncher extends AndroidApplication implements AdsController {
InterstitialAd mInterstitialAd;
private static final String TAG = "Androidlauncher";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// // Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libGDX View
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
View gameView = initializeForView(new mygame(this), config);
layout.addView(gameView);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
AdRequest adRequest = null;
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.d(TAG, loadAdError.toString());
mInterstitialAd = null;
}
});
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
#Override
public void onAdClicked() {
// Called when a click is recorded for an ad.
Log.d(TAG, "Ad was clicked.");
}
#Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
Log.d(TAG, "Ad dismissed fullscreen content.");
mInterstitialAd = null;
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
Log.e(TAG, "Ad failed to show fullscreen content.");
mInterstitialAd = null;
}
#Override
public void onAdImpression() {
// Called when an impression is recorded for an ad.
Log.d(TAG, "Ad recorded an impression.");
}
#Override
public void onAdShowedFullScreenContent() {
// Called when ad is shown.
Log.d(TAG, "Ad showed fullscreen content.");
}
});
loadInterstitialAd();
}
#Override
public void loadInterstitialAd() {
AdRequest adRequest = new AdRequest.Builder().build();
}
#Override
public void showInterstitialAd() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(mInterstitialAd!=null) {
mInterstitialAd.show();
}
else loadInterstitialAd();
}
});
}
}
InterstitialAd.show(MyActivity.this); require activity but libgdx doesn't work like that(I think?)
every code I found is no longer useful because google updated Admob
AndroidApplication extends Activity, so for interstitials you can just pass in a reference to the application, eg InterstitialAd.show(this);
I did something very similar to get interstitials working in my project. I use Ironsource but the process should be very similar. First, I defined an AdManager interface:
public interface AdManager {
/**
* Show a rewarded video ad
*/
void showRewardedVideo();
/**
* Called on app pause
*/
void onPause();
/**
* Called on app resume
*/
void onResume();
/**
* Attempts to show an interstitial ad
*
* #param onSuccess
* #param onFailed
*/
void showInterstitial(Listener onSuccess, Listener onFailed);
/**
* Called every frame, for any extra work that might need to be done
*
* #param deltaTime
*/
void update(float deltaTime);
}
Following that, you can implement your platform's ad provider:
public class AndroidAdManager implements AdManager, RewardedVideoListener, InterstitialListener, OfferwallListener {
private OnlineRPG game;
private boolean videoAvailable;
private Listener onInterstitialSuccess;
private Listener onInterstitialFailed;
private float timeSinceAd;
public AndroidAdManager(Activity activity, Gamegame) {
this.game = game;
this.activity = activity;
IronSource.setRewardedVideoListener(this);
IronSource.setInterstitialListener(this);
IronSource.setOfferwallListener(this);
IronSource.init(activity, "whatever");
IronSource.shouldTrackNetworkState(activity, true);
IronSource.loadInterstitial();
IntegrationHelper.validateIntegration(activity);
}
#Override
public void showRewardedVideo() {
if (IronSource.isRewardedVideoPlacementCapped(REWARDED_VIDEO_PLACEMENT_NAME)) {
Log.i(TAG, "Rewarded video placement is capped");
return;
}
IronSource.showRewardedVideo(REWARDED_VIDEO_PLACEMENT_NAME);
}
#Override
public void onPause() {
IronSource.onPause(activity);
}
#Override
public void onResume() {
IronSource.onResume(activity);
}
#Override
public void showInterstitial(Listener onSuccess, Listener onFailed) {
if (timeSinceAd < INTERSTITIAL_MIN_PERIOD || true) {
onFailed.invoke();
return;
}
this.onInterstitialSuccess = onSuccess;
this.onInterstitialFailed = onFailed;
IronSource.showInterstitial(INTERSTITIAL_PLACEMENT_NAME);
}
#Override
public void update(float deltaTime) {
timeSinceAd += deltaTime;
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoAdClosed() {
}
#Override
public void onRewardedVideoAvailabilityChanged(boolean b) {
Log.i(TAG, "onRewardedVideoAvailabilityChanged: " + b);
videoAvailable = b;
}
#Override
public void onRewardedVideoAdStarted() {
}
#Override
public void onRewardedVideoAdEnded() {
}
#Override
public void onRewardedVideoAdRewarded(Placement placement) {
}
#Override
public void onRewardedVideoAdShowFailed(IronSourceError ironSourceError) {
}
#Override
public void onRewardedVideoAdClicked(Placement placement) {
}
#Override
public void onInterstitialAdReady() {
}
#Override
public void onInterstitialAdLoadFailed(IronSourceError ironSourceError) {
if (onInterstitialFailed != null) {
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
onInterstitialFailed.invoke();
onInterstitialFailed = null;
}
});
}
}
#Override
public void onInterstitialAdOpened() {
Log.i(TAG, "Interstitial Ad Opened");
}
#Override
public void onInterstitialAdClosed() {
Log.i(TAG, "Interstitial Ad Closed");
if (onInterstitialSuccess != null) {
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
timeSinceAd = 0;
onInterstitialSuccess.invoke();
onInterstitialSuccess = null;
}
});
}
IronSource.loadInterstitial();
}
#Override
public void onInterstitialAdShowSucceeded() {
}
#Override
public void onInterstitialAdShowFailed(IronSourceError ironSourceError) {
Log.e(TAG, ironSourceError.getErrorMessage());
if (onInterstitialFailed != null) {
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
onInterstitialFailed.invoke();
onInterstitialFailed = null;
}
});
}
}
#Override
public void onInterstitialAdClicked() {
}
#Override
public void onOfferwallAvailable(boolean b) {
}
#Override
public void onOfferwallOpened() {
}
#Override
public void onOfferwallShowFailed(IronSourceError ironSourceError) {
}
#Override
public boolean onOfferwallAdCredited(int i, int i1, boolean b) {
return false;
}
#Override
public void onGetOfferwallCreditsFailed(IronSourceError ironSourceError) {
}
#Override
public void onOfferwallClosed() {
}
}
Lastly, in your AndroidLauncher you can create your AndroidAdManager, giving it a reference to your game/activity.
public class AndroidLauncher extends AndroidApplication {
private Game game;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
game = new Game();
game.setAdManager(new AndroidAdManager(this, game));
game.setPermissionManager(new AndroidPermissionManager(this, game));
initialize(game, config);
}
#Override
protected void onPause() {
super.onPause();
game.getAds().onPause();
}
#Override
protected void onResume() {
super.onResume();
game.getAds().onResume();
}
}
I hope this helps in your project!
I had mocked HazelcastInstance and its IMap. I had to test several methods (add, remove) which are having this IMap object is locked, updated, unlocked in the order. But the mocked IMap object is showing zero invocation when I try to run the test. Test class is as follows:
#RunWith(PowerMockRunner.class)
public class Test {
#Mock
private HazelcastInstance hazelcastInstance;
#Mock
private IMap<Object, Object> imap; // but in actual class instead of Object (K, V)
// we are having Class Names. private IMap<ClassA,ClassB> imap;
private TestClass testClass;
#Mock
private ClassA a;
#Mock
private ClassB b;
#Test
public void testAdd() {
when(hazelcastInstance.getMap(anyString())).thenReturn(imap);
testClass.add(a, b);
verify(imap, times(1)).lock(any()); //supposed to be invoked (1 time). But it is showing as zero interaction
verify(imap, times(1)).unlock(any());
}
}
Class to be tested is as follows
public class TestClass {
private IMap<ClassA, ClassB> imap = Hazelcast.newHazelcastInstance().getMap("constant");
public void add(final ClassA key, final ClassB value) {
if (key == null) {
return;
}
try {
imap.lock(key);
imap.put(key, value, 3L, TimeUnit.SECONDS);
} finally {
imap.unlock(key);
}
}
}
In your case, there are two instances of IMAP. The first one is a mock and the second one is a real imap returned by Hazelcast.newHazelcastInstance(). The problem is that the TestClass.add() method uses the real imap, and the verification uses a mock. So it gets a zero of interactions. You need to inject your mock into a TestClass instance using a constructor or a setter.
Sample code of the test
#RunWith(PowerMockRunner.class)
public class Test1 {
#InjectMocks
private TestClass testClass;
#Mock
private IMap<String, Long> imap;
#Test
public void testAdd() {
String key = "a key";
Long value = 123L;
testClass.add(key, value);
verify(imap, times(1)).lock(key);
verify(imap, times(1)).put(eq(key), eq(value), anyLong(), any(TimeUnit.class));
verify(imap, times(1)).unlock(key);
}
}
TestClass after refactoring:
class TestClass {
private IMap<String, Long> imap;
public TestClass(IMap<String, Long> imap) {
this.imap = imap;
}
public void add(final String key, final Long value) {
if (key == null) {
return;
}
try {
imap.lock(key);
imap.put(key, value, 3L, TimeUnit.SECONDS);
} finally {
imap.unlock(key);
}
}
}
The problem is that you mock
#Mock
private HazelcastInstance hazelcastInstance;
When tested class call
Hazelcast.newHazelcastInstance()
That show of architecture problems in tested class. The best way to inject a map into TestClass - pass in constructor arguments.
public class TestClass {
private final IMap<ClassA, ClassB> imap;
public TestClass(IMap<ClassA, ClassB> imap) {
this.imap = imap;
}
Now you can create instance of TestClass
IMap imap = mock(IMap.class)
testClass = new TestClass(imap)
create own imap test class and implements method like this
public class HazelcastMap implements IMap
{
private Map map = new HashMap();
#Override
public void putAll(Map m) {
}
#Override
public int size() {
return 0;
}
#Override
public boolean isEmpty() {
return false;
}
#Override
public boolean containsKey(Object key) {
return map.containsKey(key);
}
#Override
public boolean containsValue(Object value) {
return false;
}
#Override
public Object get(Object key) {
return map.get(key);
}
#Override
public Object put(Object key, Object value) {
map.put(key, value);
return value;
}
#Override
public Object remove(Object key) {
return null;
}
#Override
public boolean remove(Object key, Object value) {
return false;
}
#Override
public void removeAll(Predicate predicate) {
}
#Override
public void delete(Object key) {
}
#Override
public void flush() {
}
#Override
public Map getAll(Set keys) {
return map;
}
#Override
public void loadAll(boolean replaceExistingValues) {
}
#Override
public void loadAll(Set keys, boolean replaceExistingValues) {
}
#Override
public void clear() {
}
#Override
public ICompletableFuture getAsync(Object key) {
return null;
}
#Override
public ICompletableFuture putAsync(Object key, Object value) {
return null;
}
#Override
public ICompletableFuture putAsync(Object key, Object value, long ttl, TimeUnit ttlUnit) {
return null;
}
#Override
public ICompletableFuture putAsync(Object key, Object value, long ttl, TimeUnit ttlUnit, long maxIdle,
TimeUnit maxIdleUnit) {
return null;
}
#Override
public ICompletableFuture setAsync(Object key, Object value) {
return null;
}
#Override
public ICompletableFuture setAsync(Object key, Object value, long ttl, TimeUnit ttlUnit) {
return null;
}
#Override
public ICompletableFuture setAsync(Object key, Object value, long ttl, TimeUnit ttlUnit, long maxIdle,
TimeUnit maxIdleUnit) {
return null;
}
#Override
public ICompletableFuture removeAsync(Object key) {
return null;
}
#Override
public boolean tryRemove(Object key, long timeout, TimeUnit timeunit) {
return false;
}
#Override
public boolean tryPut(Object key, Object value, long timeout, TimeUnit timeunit) {
return false;
}
#Override
public Object put(Object key, Object value, long ttl, TimeUnit ttlUnit) {
return null;
}
#Override
public Object put(Object key, Object value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) {
return null;
}
#Override
public void putTransient(Object key, Object value, long ttl, TimeUnit ttlUnit) {
}
#Override
public void putTransient(Object key, Object value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) {
}
#Override
public Object putIfAbsent(Object key, Object value) {
return null;
}
#Override
public Object putIfAbsent(Object key, Object value, long ttl, TimeUnit ttlUnit) {
return null;
}
#Override
public Object putIfAbsent(Object key, Object value, long ttl, TimeUnit ttlUnit, long maxIdle,
TimeUnit maxIdleUnit) {
return null;
}
#Override
public boolean replace(Object key, Object oldValue, Object newValue) {
return false;
}
#Override
public Object replace(Object key, Object value) {
return null;
}
#Override
public void set(Object key, Object value) {
}
#Override
public void set(Object key, Object value, long ttl, TimeUnit ttlUnit) {
}
#Override
public void set(Object key, Object value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) {
}
#Override
public void lock(Object key) {
}
#Override
public void lock(Object key, long leaseTime, TimeUnit timeUnit) {
}
#Override
public boolean isLocked(Object key) {
return false;
}
#Override
public boolean tryLock(Object key) {
return false;
}
#Override
public boolean tryLock(Object key, long time, TimeUnit timeunit) throws InterruptedException {
return false;
}
#Override
public boolean tryLock(Object key, long time, TimeUnit timeunit, long leaseTime, TimeUnit leaseTimeunit)
throws InterruptedException {
return false;
}
#Override
public void unlock(Object key) {
}
#Override
public void forceUnlock(Object key) {
}
#Override
public String addLocalEntryListener(MapListener listener) {
return null;
}
#Override
public String addLocalEntryListener(EntryListener listener) {
return null;
}
#Override
public String addLocalEntryListener(MapListener listener, Predicate predicate, boolean includeValue) {
return null;
}
#Override
public String addLocalEntryListener(EntryListener listener, Predicate predicate, boolean includeValue) {
return null;
}
#Override
public String addLocalEntryListener(MapListener listener, Predicate predicate, Object key, boolean includeValue) {
return null;
}
#Override
public String addLocalEntryListener(EntryListener listener, Predicate predicate, Object key, boolean includeValue) {
return null;
}
#Override
public String addInterceptor(MapInterceptor interceptor) {
return null;
}
#Override
public void removeInterceptor(String id) {
}
#Override
public String addEntryListener(MapListener listener, boolean includeValue) {
return null;
}
#Override
public String addEntryListener(EntryListener listener, boolean includeValue) {
return null;
}
#Override
public boolean removeEntryListener(String id) {
return false;
}
#Override
public String addPartitionLostListener(MapPartitionLostListener listener) {
return null;
}
#Override
public boolean removePartitionLostListener(String id) {
return false;
}
#Override
public String addEntryListener(MapListener listener, Object key, boolean includeValue) {
return null;
}
#Override
public String addEntryListener(EntryListener listener, Object key, boolean includeValue) {
return null;
}
#Override
public String addEntryListener(MapListener listener, Predicate predicate, boolean includeValue) {
return null;
}
#Override
public String addEntryListener(EntryListener listener, Predicate predicate, boolean includeValue) {
return null;
}
#Override
public String addEntryListener(MapListener listener, Predicate predicate, Object key, boolean includeValue) {
return null;
}
#Override
public String addEntryListener(EntryListener listener, Predicate predicate, Object key, boolean includeValue) {
return null;
}
#Override
public EntryView getEntryView(Object key) {
return null;
}
#Override
public boolean evict(Object key) {
return false;
}
#Override
public void evictAll() {
}
#Override
public Set keySet() {
return null;
}
#Override
public Collection values() {
return null;
}
#Override
public Set entrySet() {
return null;
}
#Override
public Set keySet(Predicate predicate) {
return null;
}
#Override
public Set entrySet(Predicate predicate) {
return null;
}
#Override
public Collection values(Predicate predicate) {
return null;
}
#Override
public Set localKeySet() {
return null;
}
#Override
public Set localKeySet(Predicate predicate) {
return null;
}
#Override
public void addIndex(String attribute, boolean ordered) {
}
#Override
public LocalMapStats getLocalMapStats() {
return null;
}
#Override
public Object executeOnKey(Object key, EntryProcessor entryProcessor) {
return null;
}
#Override
public Map executeOnKeys(Set keys, EntryProcessor entryProcessor) {
return null;
}
#Override
public void submitToKey(Object key, EntryProcessor entryProcessor, ExecutionCallback callback) {
}
#Override
public ICompletableFuture submitToKey(Object key, EntryProcessor entryProcessor) {
return null;
}
#Override
public Map executeOnEntries(EntryProcessor entryProcessor) {
return null;
}
#Override
public Map executeOnEntries(EntryProcessor entryProcessor, Predicate predicate) {
return null;
}
#Override
public QueryCache getQueryCache(String name) {
return null;
}
#Override
public QueryCache getQueryCache(String name, Predicate predicate, boolean includeValue) {
return null;
}
#Override
public QueryCache getQueryCache(String name, MapListener listener, Predicate predicate, boolean includeValue) {
return null;
}
#Override
public boolean setTtl(Object key, long ttl, TimeUnit timeunit) {
return false;
}
#Override
public Object aggregate(Supplier supplier, Aggregation aggregation, JobTracker jobTracker) {
return null;
}
#Override
public Object aggregate(Supplier supplier, Aggregation aggregation) {
return null;
}
#Override
public Collection project(Projection projection, Predicate predicate) {
return null;
}
#Override
public Collection project(Projection projection) {
return null;
}
#Override
public Object aggregate(Aggregator aggregator, Predicate predicate) {
return null;
}
#Override
public Object aggregate(Aggregator aggregator) {
return null;
}
#Override
public String getPartitionKey() {
return null;
}
#Override
public String getName() {
return null;
}
#Override
public String getServiceName() {
return null;
}
#Override
public void destroy() {
}
}
Hi everybody!!
I have two fragments:Fragment1 and Fragment2; Fragment1 contains Json,and after getting Json, I replace Fragment1 to Fragment2 via .replace(..) and transfer the Json via Bundle.
My Goal is: Refresh Json in Fragment1 each 60s for example and update automatically Fragment2 but i don't know how to do that!! i need your help!!
this is my code:
Class Fragment1
public class Fragment1 extends Fragment implements OnClickListener{
public static final String IMAGE_RESOURCE_ID="iconResourceID";
public static final String ITEM_NAME="itemName";
Button btnvalider;
//test transfer variable entre fragment
public Communicator com;
public void setCom(Communicator com) {
this.com = com;
}
/*
* Test Jsonparser
*
*/
Context c;
private ProgressDialog pDialog;
public String testfinalewa="";
JSonParser jsonParser = new JSonParser();
// url to create new product
private static String url_create_product = "http://10.0.2.2/webservice/create_personne.php";
public String getTestfinalewa() {
return testfinalewa;
}
public void setTestfinalewa(String testfinalewa) {
this.testfinalewa = testfinalewa;
}
// JSON Node names
private static final String TAG_SUCCESS = "success";
//fin test json
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
c=getActivity();
return inflater.inflate(R.layout.fragment_1, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
btnvalider=(Button)getActivity().findViewById(R.id.button1);
btnvalider.setOnClickListener(this);
this.com=(Communicator) getActivity();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Handler().postDelayed(new Runnable() {
public void run() {
// call JSON methods here
new AttemptLogin().execute();
}
}, 1 );
}
//interface pour transferer variable entre fragment
public interface Communicator{
public void respond(String data);
}
class AttemptLogin extends AsyncTask<String, String, String>{//<params,progress,result>
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(c);
pDialog.setMessage("Chargement...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
String name ="test";// pseudo.getText().toString();
String moddepasse = "test";//mdp.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
Log.i("misy ve", "ok="+moddepasse);
Log.i("misy ve", "ok="+name);
params.add(new BasicNameValuePair("moddepasse", moddepasse));
Log.i("test", "mbola tena mety eto 1");
// getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
Log.d("Create Response", json.toString());
Log.i("test", "mbola tena mety eto");
try {
int success = json.getInt(TAG_SUCCESS);
String succ=json.getString("ok");
Log.i("milay", succ);
if ((success == 1)) {
Log.i("accepter", "mdp correct");
} else {
Log.i("pas accepter", "non correct");
}
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
protected void onPostExecute(String result) {
pDialog.dismiss();
com.respond(result);
Fragment2 fb=new Fragment2();
FragmentTransaction t=getFragmentManager().beginTransaction();
Bundle args=new Bundle();
args.putString("mondata", result);
fb.setArguments(args);
t.replace(R.id.myFramePrincipal, fb).commit();
}
}
}
class Fragment2
public class Fragment2 extends Fragment{
TextView text;
String aa;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
text=(TextView) getActivity().findViewById(R.id.textView1);
text.setText(getArguments().getString("mondata"));
}
public void refreshData(String data) {
aa= new String(data);
//aa.notifyDataSetChanged();
text.setText(aa);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment_3, container, false);
}
public void ChangerText(String data) {
text.setText(data);
}
}
Thanks for your help!!
Whenever I try to destroy a body in JBox2D it always give me a NullPointerException, and I have checked online and they show various ways of doing it 'safely' which I don't understand. I was wondering if anyone could type up some simple pseudo code to show how you would destroy a body in Box2D. I am also using the LibGDX API as well.
Here is my code that I use:
public void render(float delta) {
if(bodiesContainer.size() > 0)
{
for(Body body:bodiesContainer)
{
world.destroyBody(body);
}
}
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(delta);
stage.draw();
world.step(TIMESTEP, VELOCITYITERATIONS, POSITIONITERATIONS);
camera.update();
debugRenderer.render(world, camera.combined);
batch.begin();
batch.end();
}
public void show() {
// TODO Auto-generated method stub
batch = new SpriteBatch();
camera = new OrthographicCamera(Gdx.graphics.getWidth()/5, Gdx.graphics.getHeight()/5);
world = new World(new Vector2(0,0f), true);
debugRenderer = new Box2DDebugRenderer();
stage = new Stage();
particleCreator = new ParticleCreator(0, 0, 1);
particleCreator.destroyParticle(world, particleBody);
if (particleCreator == null)
{
System.out.println("true");
}
if (particleBody == null)
{
System.out.println("true particleBody");
}
if (particleBodyDef == null)
{
System.out.println("true particleBodyDef");
}
Gdx.input.setInputProcessor(new InputProcessor() {
#Override
public boolean touchUp(int arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean touchDragged(int arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean touchDown(int arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean scrolled(int arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean mouseMoved(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean keyUp(int arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean keyTyped(char arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean keyDown(int keycode) {
switch(keycode) {
case Keys.SPACE:
break;
}
return false;
}
});
}
public class ParticleCreator
{
//Default constructor
public ParticleCreator()
{
}
public ParticleCreator(World world, BodyDef bodyDef, Body body, float position_x, float position_y, float particle_radius)
{
bodyDef = new BodyDef();
bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set(position_x, position_y);
CircleShape circleShape = new CircleShape();
circleShape.setRadius(particle_radius);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = circleShape;
fixtureDef.restitution = 0;
body = world.createBody(bodyDef);
body.createFixture(fixtureDef);
}
public void destroyParticle(World world, Body body)
{
world.destroyBody(body);
System.out.println("This Particle has been destroyed !!!");
}
}
The bodiesContainer is an ArrayList, and the particleBody is a JBox2D body i wish to destroy, but every time I press the space button it crashes and gives me a NullPointerException.