My app currently looks like this:
I want to add a search bar where I can search any place as Google maps. The search bar should be in an Auto Complete way.I got this code from https://examples.javacodegeeks.com/android/android-google-places-autocomplete-api-example/
Have a look at the above link.
And these codes where for an ORDINARY APP to get Auto Complete search bar. It doesnt suit for app using fragment. And I dont know how to do it with fragments.
Here is my code
For the Main Activity (ProfileActivity)
public class ProfileActivity extends AppCompatActivity {
final String TAG = this.getClass().getName();
BottomBar mBottomBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
mBottomBar = BottomBar.attach(this, savedInstanceState);
mBottomBar.setItemsFromMenu(R.menu.menu_user, new OnMenuTabClickListener() {
#Override
public void onMenuTabSelected(#IdRes int i) {
if(i == R.id.ButtonBarFeed)
{
NewsFragment f = new NewsFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,f).commit();
}
else if(i == R.id.ButtonBarMap)
{
MapFragment f = new MapFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,f).commit();
}
else if(i == R.id.ButtonBarUser)
{
UserFragment f = new UserFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,f).commit();
}
}
#Override
public void onMenuTabReSelected(#IdRes int menuItemId) {
}
});
mBottomBar.mapColorForTab(0,"#28809f");
}
public boolean googleServicesAvailable(){
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int isAvailable = api.isGooglePlayServicesAvailable(this);
if(isAvailable == ConnectionResult.SUCCESS){
return true;
}else if(api.isUserResolvableError(isAvailable)){
Dialog dialog = api.getErrorDialog(this, isAvailable, 0);
dialog.show();
} else {
Toast.makeText(this,"Can't connet to Play Services", Toast.LENGTH_LONG).show();
}
return false;
}
boolean twice;
#Override
public void onBackPressed() {
Log.d(TAG, "click");
if(twice == true){
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
System.exit(0);
}
twice = true;
Log.d(TAG, "twice:" + twice);
Toast.makeText(ProfileActivity.this, "Please press BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
twice = false;
Log.d(TAG, "twice:" + twice);
}
}, 3000);
}
}
MapFragment
public class MapFragment extends Fragment implements OnMapReadyCallback {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.map, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SupportMapFragment fragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.mapView1);
fragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap){
}
}
I have to add a search bar with Auto Complete like Google map.Please with reference of the Link which I have given at starting, Can Anyone code for my MapFragment?
Related
I have a problem with my app. I have a MainActivity, where is a drawer with fragments. From Scan fragment I call Scan Activity. This part is workng. And when I press back button, it goes back to MainActivity with ScanFragment. And there is also socket operation to send the code and maybe there is the problem. When I turn off wifi, it shows I/O error in Toast, but when I try to send the data, it goes into black screen. I found the problem in profiler, that MainActivity do not start after closing Scan activity, but the app is still running.
After a while android ask, if close non responding app. I tried to move all classes and functions into MainActivity, but then scanner wont start. Thanks for any help
My code of MainActivity.java:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ScanFragment()).commit();
navigationView.setCheckedItem(R.id.nav_scan);
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_scan:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ScanFragment()).commit();
break;
case R.id.nav_okruh:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new OkruhFragment()).commit();
break;
case R.id.nav_kzavozu:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new KZavozuFragment()).commit();
break;
case R.id.nav_zprava:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ZpravaFragment()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
Code of ScanFragment.java:
public class ScanFragment extends Fragment {
String kod;
String hostname = (address);
int port = (number);
Date date;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS");
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_scan, container, false);
Button button = (Button) view.findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
zapnoutSkener();
}
});
Button rucne = (Button) view.findViewById(R.id.button3);
final EditText rucneKod = (EditText) view.findViewById(R.id.numberInput);
rucne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
odeslat(rucneKod.getText().toString());
}
});
return view;
}
public class Spojeni extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
Log.i("hodnota", strings[0]);
Log.i("kod", strings[1]);
try (Socket socket = new Socket(hostname, port)) {
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
PrintWriter writer = new PrintWriter(outputStream, true);
writer.println(strings[0] + ";" + kod + ";" + simpleDateFormat.format(date));
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
socket.close();
return line;
} catch (UnknownHostException e) {
return "Server nebezi, zopakujte odeslani";
} catch (IOException e) {
return "I/O Error, zkontrolujte pripojeni k internetu";
} catch (Exception e) {
return "Obecny error";
}
}
}
public void zapnoutSkener() {
Intent intent = new Intent(getActivity(), ScanOkno.class);
Toast.makeText(getActivity(), "Zapinani akce", Toast.LENGTH_LONG).show();
Log.i("Zapinani skeneru", "ted");
startActivityForResult(intent, 1);
}
public void odeslat(String kod) {
date = Calendar.getInstance().getTime();
Toast.makeText(getActivity(), "Odesílám kód: " + kod, Toast.LENGTH_SHORT).show();
Spojeni spojit = new Spojeni();
String odpoved = null;
try {
odpoved = spojit.execute("SCAN", kod).get();
} catch (Exception e) {
e.printStackTrace();
}
Log.i("Odpoved", odpoved);
Toast.makeText(getActivity(), "Odpoved: " + odpoved, Toast.LENGTH_LONG).show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
Log.i("KOD", String.valueOf(resultCode));
if (resultCode == 1) {
String result = data.getStringExtra("code");
Log.i("Vysledek", result);
odeslat(result);
}
}
}
}
Code of scanner activity ScanOkno.java:
public class ScanOkno extends AppCompatActivity implements BarcodeReader.BarcodeReaderListener {
private BarcodeReader barcodeReader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_okno);
barcodeReader = (BarcodeReader) getSupportFragmentManager().findFragmentById(R.id.barcode_fragment);
}
#Override
public void onScanned(Barcode barcode) {
// play beep sound
barcodeReader.playBeep();
String kod = barcode.rawValue;
barcodeReader.pauseScanning();
Intent intent = new Intent();
intent.putExtra("code", barcode.rawValue);
setResult(1, intent);
finish();
//Intent intent = new Intent(getApplicationContext(), MainActivity.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
}
#Override
public void onScannedMultiple(List<Barcode> list) {
}
#Override
public void onBitmapScanned(SparseArray<Barcode> sparseArray) {
}
#Override
public void onScanError(String s) {
}
#Override
public void onCameraPermissionDenied() {
Toast.makeText(getApplicationContext(), "Camera permission denied!", Toast.LENGTH_LONG).show();
}
}
odpoved = spojit.execute("SCAN", kod).get()
is your problem. Calling get() on an AsyncTask blocks the current Thread until the task completes, essentially defeating the purpose of an AsyncTask.
Consider using a callback.
First, make Spojeni a static class:
public static class Spojeni extends AsyncTask<String, Void, String>
This will prevent memory leaks from occurring. I do see some variables that you access inside the parent class, but you can pass them in your call to execute() and retrieve them from your AsyncTask there.
Then, create an interface (can be a child of ScanFragment or in its own file):
public interface OnTaskCompleteListener {
void onTaskComplete(String result);
}
Add a constructor and a global variable to your AsyncTask:
private OnTaskCompleteListener listener;
public Spojeni(OnTaskCompleteListener listener) {
this.listener = listener;
}
And implement onPostExecute():
#Override
public void onPostExecute(String result) {
listener.onTaskComplete(result);
}
When you create an instance of Spojeni:
new Spojeni(new OnTaskCompleteListener() {
#Override
public void onTaskComplete(String result) {
//handle the result
}
});
I have a MasterActivity that has a few fragments. One fragment allows the user to open up Square to pay. After the user signs their name in Square and the data is returned to my app, my app crashes because the Payment fragment can't find the MasterActivity as it is null.
This only happens when the user signs the receipt. If the user pays cash (no signature) the My App works fine.
I have noticed that the when the Square App is ready for a signature it rotates the screen, just before the signature capture activity is view-able, I can see my app rotate too.
After the Square application has returned to my app, I can see the successful upload of the data to my server from my app. Then, it is only when the payment fragment asks the MasterActivity to refresh the data, I get a null pointer exception for the DISP_KEY in MasterAcitvity .
Can any see what I might be doing wrong?
MasterActivity
public class MasterActivity extends AppCompatActivity {
private String TAG = getClass().getSimpleName();
private String DISP_KEY = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_master);
Intent intent = getIntent();
DISP_KEY = (String) intent.getSerializableExtra("SELECTED_DISPATCH");
initView();
refreshData();
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
public void refreshData() {
//Do some network download data stuff using the DISP_KEY
}
private void initView() {
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
//JUST TEXT
tabLayout.addTab(tabLayout.newTab().setText("Details"));
tabLayout.addTab(tabLayout.newTab().setText("Sections"));
tabLayout.addTab(tabLayout.newTab().setText("Area"));
tabLayout.addTab(tabLayout.newTab().setText("Notes"));
tabLayout.addTab(tabLayout.newTab().setText("Payments"));
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new TabPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
}
}
PaymentFragment
public class PaymentFragment extends Fragment {
private static final int SQUARE_CHARGE_REQUEST_CODE = 1;
private String TAG = getClass().getSimpleName();
private PosClient posClient;
public PaymentFragment() {
// Required empty public constructor for fragments
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_payment, container, false);
initGUI(view);
return view;
}
#Override
public void onStart() {
super.onStart();
mVehicle = ((MasterActivity) this.getActivity()).getCurrentVehicle();
if (mVehicle != null) {
reloadData();
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (this != null) {
((MasterActivity) context).registerDataReloadListener(this);
posClient = PosSdk.createClient(getActivity(), AppConfig.SQUARE_APP_ID);
} else {
((MasterActivity) context).onBackPressed();
}
}
#Override
public void onDetach() {
super.onDetach();
if (this != null) {
((MasterActivity) getActivity()).unregisterDataReloadListener(this);
}
}
public void reloadData() {
//Ask the master activity to reload data
}
// SQUARE
private void acceptSquarePayment() {
ChargeRequest.TenderType types;
ChargeRequest request = new ChargeRequest.Builder(Integer.parseInt(square_balance), CurrencyCode.USD)
.enforceBusinessLocation(square_location_id)
.restrictTendersTo(types)
.requestMetadata(square_call_num)
.autoReturn(3200, TimeUnit.MILLISECONDS)
.build();
Intent intent = posClient.createChargeIntent(request);
startActivityForResult(intent, SQUARE_CHARGE_REQUEST_CODE);
}
// GET SQAURE RESULTS
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
ChargeRequest.Success success = posClient.parseChargeSuccess(data);
sendReceiptToAPIServer(success.serverTransactionId, success.clientTransactionId, success.requestMetadata);
}
}
private void sendReceiptToAPIServer(String serverTransactionId, String clientTransactionId, String callNum) {
//Do some data upload stuff
//After the successufull upload, this is where the crash happens
reloadData();
}
#Override
public void onDataReload() {
mVehicle = ((MasterActivity) this.getActivity()).getCurrentVehicle();
if (getView() != null) {
reloadData();
}
}
}
In my project I have just one Activity that have View.
I think that it has two View that switch the View. The first View is my home that has one Button named "play" . when You click play Button in goes to the second View. Second View is my game.
And now my problem is that when I want to use onBackPressed() method in the second View, it closes the Activity. and onBackPressed() method do the same in both View.
How to handle onBackPressed() method in second View that return to the first View.
How to switch the View in onBackPressed()?
I am new with Android and now I really confused.
any suggestion? or any key word to search to solve my problem.
here is my code:
public class PTPlayer extends Cocos2dxActivity {
static Splash splash;
public static AppList appList;
static Noti_Queue noti_queue;
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("----------", "onActivityResult: request: " + requestCode + " result: " + resultCode);
if (requestCode == PTServicesBridge.RC_SIGN_IN) {
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (splash == null) {
splash = new Splash(this);
splash.set_identity("1");
}
if (appList == null) {
appList = new AppList(this);
appList.set_identity("1");
}
if (noti_queue == null) {
noti_queue = new Noti_Queue(this);
noti_queue.set_identity("1");
}
}
#Override
public void onNativeInit() {
initBridges();
}
private void initBridges() {
PTStoreBridge.initBridge(this);
PTServicesBridge.initBridge(this, getString(R.string.app_id));
if (PTJniHelper.isAdNetworkActive("kChartboost")) {
PTAdChartboostBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kRevMob")) {
PTAdRevMobBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kAdMob") || PTJniHelper.isAdNetworkActive("kFacebook")) {
PTAdAdMobBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kAppLovin")) {
PTAdAppLovinBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kLeadBolt")) {
PTAdLeadBoltBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kVungle")) {
PTAdVungleBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kPlayhaven")) {
PTAdUpsightBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kMoPub")) {
PTAdMoPubBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kFacebook")) {
PTAdFacebookBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kHeyzap")) {
PTAdHeyzapBridge.initBridge(this);
}
}
#Override
public Cocos2dxGLSurfaceView onCreateView() {
Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
glSurfaceView.setEGLConfigChooser(8, 8, 8, 0, 0, 0);
return glSurfaceView;
}
static {
System.loadLibrary("player");
}
#Override
protected void onResume() {
super.onResume();
if (PTJniHelper.isAdNetworkActive("kChartboost")) {
PTAdChartboostBridge.onResume(this);
}
}
#Override
protected void onStart() {
super.onStart();
if (PTJniHelper.isAdNetworkActive("kChartboost")) {
PTAdChartboostBridge.onStart(this);
}
}
#Override
protected void onStop() {
super.onStop();
if (PTJniHelper.isAdNetworkActive("kChartboost")) {
PTAdChartboostBridge.onStop(this);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onBackPressed() {
splash.Display();
splash = null;
super.onBackPressed();
}
}
here i think that in my second view:
public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelperListener {
// ===========================================================
// Constants
// ===========================================================
private static final String TAG = Cocos2dxActivity.class.getSimpleName();
// ===========================================================
// Fields
// ===========================================================
private Cocos2dxGLSurfaceView mGLSurfaceView;
private Cocos2dxHandler mHandler;
private static Context sContext = null;
public static Context getContext() {
return sContext;
}
// ===========================================================
// Constructors
// ===========================================================
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sContext = this;
this.mHandler = new Cocos2dxHandler(this);
this.init();
Cocos2dxHelper.init(this, this);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
#Override
protected void onResume() {
super.onResume();
Cocos2dxHelper.onResume();
this.mGLSurfaceView.onResume();
}
#Override
protected void onPause() {
super.onPause();
Cocos2dxHelper.onPause();
this.mGLSurfaceView.onPause();
}
#Override
public void showDialog(final String pTitle, final String pMessage) {
Message msg = new Message();
msg.what = Cocos2dxHandler.HANDLER_SHOW_DIALOG;
msg.obj = new Cocos2dxHandler.DialogMessage(pTitle, pMessage);
this.mHandler.sendMessage(msg);
}
#Override
public void showEditTextDialog(final String pTitle, final String pContent, final int pInputMode, final int pInputFlag, final int pReturnType, final int pMaxLength) {
Message msg = new Message();
msg.what = Cocos2dxHandler.HANDLER_SHOW_EDITBOX_DIALOG;
msg.obj = new Cocos2dxHandler.EditBoxMessage(pTitle, pContent, pInputMode, pInputFlag, pReturnType, pMaxLength);
this.mHandler.sendMessage(msg);
}
#Override
public void runOnGLThread(final Runnable pRunnable) {
this.mGLSurfaceView.queueEvent(pRunnable);
}
// ===========================================================
// Methods
// ===========================================================
public void init() {
// FrameLayout
ViewGroup.LayoutParams framelayout_params =
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
FrameLayout framelayout = new FrameLayout(this);
framelayout.setLayoutParams(framelayout_params);
// Cocos2dxEditText layout
ViewGroup.LayoutParams edittext_layout_params =
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
this.mGLSurfaceView = this.onCreateView();
// Switch to supported OpenGL (ARGB888) mode on emulator
if (isAndroidEmulator())
this.mGLSurfaceView.setEGLConfigChooser(8 , 8, 8, 8, 16, 0);
this.mGLSurfaceView.setCocos2dxRenderer(new Cocos2dxRenderer());
RelativeLayout relativeLayout = new RelativeLayout(getApplicationContext());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
relativeLayout.setLayoutParams(params);
//AdView adad = new AdView(this);
ClickBanner_CLickYab_Holder adad = new ClickBanner_CLickYab_Holder(this);
RelativeLayout.LayoutParams adad_params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
adad_params.addRule(RelativeLayout.CENTER_HORIZONTAL);
adad_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
// adad.setToken(getString(R.string.adad_token));
adad.setLayoutParams(adad_params);
Button myButton = new Button(this);
myButton.setBackgroundResource(R.drawable.more);
RelativeLayout.LayoutParams adad_params1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adad_params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
adad_params1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
myButton.setLayoutParams(adad_params1);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PTPlayer.appList.Display();
}
});
Button myButton1 = new Button(this);
myButton1.setBackgroundResource(R.drawable.more);
RelativeLayout.LayoutParams adad_params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adad_params2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
adad_params2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
myButton1.setLayoutParams(adad_params2);
myButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PTPlayer.appList.Display();
}
});
relativeLayout.addView(this.mGLSurfaceView);
relativeLayout.addView(adad);
relativeLayout.addView(myButton);
relativeLayout.addView(myButton1);
ClickBanner_CLickYab_Holder.setTestMode();
setContentView(relativeLayout);
}
public Cocos2dxGLSurfaceView onCreateView() {
return new Cocos2dxGLSurfaceView(this);
}
private final static boolean isAndroidEmulator() {
String model = Build.MODEL;
Log.d(TAG, "model=" + model);
String product = Build.PRODUCT;
Log.d(TAG, "product=" + product);
boolean isEmulator = false;
if (product != null) {
isEmulator = product.equals("sdk") || product.contains("_sdk") || product.contains("sdk_");
}
Log.d(TAG, "isEmulator=" + isEmulator);
return isEmulator;
}
}
you must use of Override Method for when back button pressed
if you want to stay on currnt activity use like this
#Override
public void onBackPressed() {
return;
}
if you want to use double click to exit and one click to stay you can use like this
first define a variable for double click
boolean doubleBackToExit = false;
and the Override backbutton method
#Override
public void onBackPressed() {
if (doubleBackToExit) {
//on double back button pressed
return;
}
this.doubleBackToExit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExit=false;
}
}, 2000);
}
Then do this.
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(MainActivityPhase2.this, GlobalSearch.class);
startActivity(intent);
finish();
}
Just don't call the super.onBackPressed() everytime.
#Override
public void onBackPressed() {
if (isFirstView()) {
super.onBackPressed();
} else {
switchToFirstView();
}
Call in only when there isn't any last view available. Or where you want to close the App. The code will finish your activity when you are on the first activity. And switch to first activity if you are on second activity.
Just replace my methods as per your code.
Overriding onBackPressed() of the activity and provide your screen where you want to go.
onBackpressed() check which is the current view you are showing and according to move to the first view.
in your second class Cocos2dxActivity, place this code.
#Override
public void onBackPressed() {
this.finish();
}
If you have just one activity with two View you can use Fragments.
Using Fragments, Activity.OnBackPressed() will remove last fragment in the stack and you can resolve your problem.
So, in the activity you have to put a container in xml layout file:
<FrameLayout android:id="#+id/container" android:layout_width="match_parent"
android:clickable="true" android:layout_height="match_parent"/>
In the Activity java file:
getFragmentManager().beginTransaction()
.add(R.id.container,new YourHomeFragment())
.commit();
So to add second Fragment you can use this code:
getFragmentManager().beginTransaction()
.add(R.id.container,new YourPlayFragment())
.addToBackStack("YourPlayFragment") //string what you want
.commit();
Pay attention: you can call this code or in YourHomeFragment class (into button clickListener) or in your Activity (using a callback system). For example:
In YourHomeFragment -->
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().beginTransaction()
.add(R.id.container,new YourPlayFragment())
.addToBackStack("YourPlayFragment") //string what you want
.commit();
}
});
In this way, you have to declare two layout xml file for fragments and one for Activity.
List of java and relative xml files:
MainActivity.java
activity_main.xml
YourHomeFragment.java
fragment_your_home.xml <-- insert here your first View
YourPlayFragment.java
fragment_your_play.xml <-- play view
I am building an OpenGL live wallpaper. I decided to have a Navigation Drawer in my main activity since there are a lot of features the user will have access to.
The problem/issue
If I press the "hardware" back button to normally close an app the initial fragment that is shown just refreshes and the app never closes. If I hit the home button and go back to the app everything is a black screen. I've searched all throughout Google thinking that maybe I wasn't destroying the MainActivity properly or for a way to terminate a fragment. I've tried calling finish() in the main activity's onDestroy method. I've tried utilizing the remove method from fragment manager in each fragments onDetach method per posts that I've found online. Nothing has worked. I'm stumped. I've set debug points in the main activity on the onDestroy method and on the fragments onDetach method with no error being produced or any information being given. At this point I am clueless. Here's my MainActivity class.
public class MainActivity extends AppCompatActivity implements OnNavigationItemSelectedListener, OnPostSelectedListener{
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
TextView usrTag, tagrEmail;
CircleImageView tagrPic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.add(R.id.cLMain, new PreviewFragment()).addToBackStack("PreviewFragment").commit();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
usrTag = (TextView)header.findViewById(R.id.usrName);
tagrEmail = (TextView)header.findViewById(R.id.usrEmail);
tagrPic = (CircleImageView)header.findViewById(R.id.usrImg);
Log.i("MainActivity: ", "User Photo: " + getProfilePic(this));
usrTag.setText(getUserName(getBaseContext()));
tagrEmail.setText(getUserEmail(getBaseContext()));
GlideUtils.loadProfileIcon(getProfilePic(getBaseContext()), tagrPic);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment = null;
Class fragmentClass = null;
int id = item.getItemId();
if (id == R.id.nav_home) {
fragmentClass = PreviewFragment.class;
} else if (id == R.id.nav_custom) {
startCustomLabelCreator();
} else if (id == R.id.nav_mylabels) {
} else if (id == R.id.nav_commLabels) {
fragmentClass = PostsFragment.class;
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.cLMain, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void startCustomLabelCreator(){
Intent cLC = new Intent(getBaseContext(), CreateLabel.class);
startActivity(cLC);
}
#Override
public void onPostComment(String postKey) {
}
#Override
public void onPostLike(String postKey) {
}
#Override
public void onPhotoSelected(String photoUrl) {
}
#Override
protected void onDestroy() {
super.onDestroy();
finish();
}
}
My Fragments
public class PostsFragment extends Fragment implements ConfirmSelectedPhotoListener{
public static final String TAG = "PostsFragment";
private static final String KEY_LAYOUT_POSITION = "layoutPosition";
private int mRecyclerViewPosition = 0;
private OnPostSelectedListener mListener;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter<PostViewHolder> mAdapter;
public PostsFragment() {
// Required empty public constructor
}
public static PostsFragment newInstance() {
PostsFragment fragment = new PostsFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_posts, container, false);
rootView.setTag(TAG);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
mRecyclerView.setLayoutManager(linearLayoutManager);
Log.d(TAG, "Restoring recycler view position (all): " + mRecyclerViewPosition);
Query allPostsQuery = FirebaseUtil.getPostsRef();
mAdapter = getFirebaseRecyclerAdapter(allPostsQuery);
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
// TODO: Refresh feed view.
}
});
mRecyclerView.setAdapter(mAdapter);
}
private FirebaseRecyclerAdapter<Post, PostViewHolder> getFirebaseRecyclerAdapter(Query query) {
return new FirebaseRecyclerAdapter<Post, PostViewHolder>(
Post.class, R.layout.post_item, PostViewHolder.class, query) {
#Override
public void populateViewHolder(final PostViewHolder postViewHolder,
final Post post, final int position) {
setupPost(postViewHolder, post, position, null);
}
#Override
public void onViewRecycled(PostViewHolder holder) {
super.onViewRecycled(holder);
// FirebaseUtil.getLikesRef().child(holder.mPostKey).removeEventListener(holder.mLikeListener);
}
};
}
private void setupPost(final PostViewHolder postViewHolder, final Post post, final int position, final String inPostKey) {
postViewHolder.setPhoto(post.getThumb_url());
Log.d(TAG, post.getThumb_url());
postViewHolder.setText(post.getText());
postViewHolder.setTimestamp(DateUtils.getRelativeTimeSpanString(
(long) post.getTimestamp()).toString());
final String postKey;
if (mAdapter instanceof FirebaseRecyclerAdapter) {
postKey = ((FirebaseRecyclerAdapter) mAdapter).getRef(position).getKey();
} else {
postKey = inPostKey;
}
Author author = post.getAuthor();
postViewHolder.setAuthor(author.getFull_name(), author.getUid());
postViewHolder.setIcon(author.getProfile_picture(), author.getUid());
ValueEventListener likeListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
postViewHolder.setNumLikes(dataSnapshot.getChildrenCount());
if (dataSnapshot.hasChild(FirebaseUtil.getCurrentUserId())) {
postViewHolder.setLikeStatus(PostViewHolder.LikeStatus.LIKED, getActivity());
} else {
postViewHolder.setLikeStatus(PostViewHolder.LikeStatus.NOT_LIKED, getActivity());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
FirebaseUtil.getLikesRef().child(postKey).addValueEventListener(likeListener);
postViewHolder.mLikeListener = likeListener;
postViewHolder.setPostClickListener(new PostViewHolder.PostClickListener() {
#Override
public void showComments() {
Log.d(TAG, "Comment position: " + position);
mListener.onPostComment(postKey);
}
#Override
public void toggleLike() {
Log.d(TAG, "Like position: " + position);
mListener.onPostLike(postKey);
}
#Override
public void savePhotoUrl() {
//mListener.onPhotoSelected(post.getFull_url());
showLabelConfirm(post.getFull_url());
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
if (mAdapter != null && mAdapter instanceof FirebaseRecyclerAdapter) {
((FirebaseRecyclerAdapter) mAdapter).cleanup();
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save currently selected layout manager.
int recyclerViewScrollPosition = getRecyclerViewScrollPosition();
Log.d(TAG, "Recycler view scroll position: " + recyclerViewScrollPosition);
savedInstanceState.putSerializable(KEY_LAYOUT_POSITION, recyclerViewScrollPosition);
super.onSaveInstanceState(savedInstanceState);
}
private int getRecyclerViewScrollPosition() {
int scrollPosition = 0;
// TODO: Is null check necessary?
if (mRecyclerView != null && mRecyclerView.getLayoutManager() != null) {
scrollPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager())
.findFirstCompletelyVisibleItemPosition();
}
return scrollPosition;
}
#Override
public void onSelectedPhoto(String selectPhoto) {
mListener.onPhotoSelected(selectPhoto);
}
public interface OnPostSelectedListener {
void onPostComment(String postKey);
void onPostLike(String postKey);
void onPhotoSelected(String photoUrl);
}
private void showLabelConfirm(String uriBmp) {
FragmentManager fm = getFragmentManager();
PhotoDialogFragment editNameDialogFragment = PhotoDialogFragment.newInstance(uriBmp);
// SETS the target fragment for use later when sending results
editNameDialogFragment.setTargetFragment(PostsFragment.this, 300);
editNameDialogFragment.show(fm, "fragment_edit_name");
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnPostSelectedListener) {
mListener = (OnPostSelectedListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnPostSelectedListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
Second Fragment:
public class PreviewFragment extends RajBaseFragment {
#Override
public ISurfaceRenderer createRenderer() {
return new PreviewRenderer(getContext());
}
}
Which extends:
public abstract class RajBaseFragment extends Fragment implements IDisplay, View.OnClickListener {
protected FrameLayout mLayout;
protected ISurface mRajawaliSurface;
protected ISurfaceRenderer mRenderer;
public RajBaseFragment(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
// Inflate the view
mLayout = (FrameLayout) inflater.inflate(getLayoutID(), container, false);
mLayout.findViewById(R.id.relative_layout_loader_container).bringToFront();
// Find the TextureView
mRajawaliSurface = (ISurface) mLayout.findViewById(R.id.rajwali_surface);
// Create the loader
mRenderer = createRenderer();
onBeforeApplyRenderer();
applyRenderer();
return mLayout;
}
protected void onBeforeApplyRenderer() {
}
protected void applyRenderer() {
mRajawaliSurface.setSurfaceRenderer(mRenderer);
}
#Override
public void onClick(View v) {
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (mLayout != null)
mLayout.removeView((View) mRajawaliSurface);
}
#Override
public int getLayoutID() {
return R.layout.rajawali_textureview_fragment;
}
}
I've tried all the recommendations below so far and the primary fragment that is set in the MainActivity's onCreate method still gets refreshed/reloaded when the back button is pressed rather than the app exiting/closing.
In your onNavigationItemSelected method, you are replacing the current fragment with fragment even in cases where fragment is null, which has undefined effects. You should not do that.
One fix is to replace this code block:
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
with this one:
if (fragmentClass != null) {
fragment = fragmentClass.newInstance();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.cLMain, fragment).addToBackStack().commit();
}
(and then leave out the fragment transaction below this point).
Also, there is a call to finish in the onDestroy method, which probably is not causing the problem but should be taken out because it does not make any sense there.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
}
return true;
}
replace your onOptionsItemSelected() with mine.
Don't include your first fragment into backstack.
Try to change you fragment transaction line code without addToBackStack
as below:
mFragmentTransaction.add(R.id.cLMain, new PreviewFragment()).commit();
While adding fragment with addToBackStack, this allows back
navigation for added fragment.Because of fragment in backstack,
empty(black) activity layout will be displayed.
Change onBackPressed() as below which automatically close app after if no any Fragment found in FragmentManager:
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
this.finish();
} else {
getSupportFragmentManager().popBackStack();
}
}
Also you can see some similar Q/A on below links which helps you get more idea to solve your problem:
Fragment pressing back button
In Fragment on back button pressed Activity is blank
Transaction of fragments in android results in blank screen
It's solved my blank screen problem. Hope its helps you.
Try this code, hope this helps you, take necessary stuffs which are required for you. Also, try running this project in Android studio, it works.
https://github.com/asifali22/Navigation_Health/blob/master/app/src/main/java/com/thenewboston/mynavigation/MainActivity.java
When user press to back button it'll check fragment manager's backstack and if backstack entity count is bigger than 0 (this means there's a fragment in backstack) it'll popBackStack else it'll finish activity.
If you add your initial fragment to backstack, when user press back button they'll see a blank screen.
Also when you init your activity if you need to put a fragment it's a best practice to check if saved instance state is null. Here i modified some part of your code.
if(savedInstanceState == null){
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.add(R.id.cLMain, new PreviewFragment()).commit();
}
I hope this'll help you. If you still have problem let me know.
Good luck.
create subclass for ISurface and override onKeyDown method like this
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.e("Custom View", "onKeyDown");
//return super.onKeyDown(keyCode, event);
return false;
}
Could be related with the lifecycle...
Try using GLSurfaceView. I believe is easier for what you want, is special for OpenGL rendering and there is plenty information about it. Examples, lifecycle among others. Let me know if helped. If not, please, provide more info.
I have 2 image views in a fragment set up as clickable and i am trying to play a sound when each one is clicked! i can do this in an activity but not in a fragment! i am trying to use to media player but this throws up an error.
public class HomeFragment extends Fragment {
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//giving me error cannot resolve method
final MediaPlayer mp = MediaPlayer.create(this, R.raw.music_marimba_chord);
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
ImageView share = (ImageView)view.findViewById(R.id.share);
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "");
startActivity(Intent.createChooser(sharingIntent, "Share via"));
ImageView send = (ImageView)view.findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(""));
startActivity(intent);
}
});
return view;
}
// set fragment to portrait
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser) {
Activity a = getActivity();
if(a != null) a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
}
If you want to use SoundPool, the following will play a different sound when click or select event are triggered on the fragment :
public abstract class MainFragment extends Fragment {
private SoundPool soundPool;
private HashMap<Integer, Integer> soundPoolMap;
public void onCreate() {
initSounds(getActivity().getApplicationContext());
}
public void initSounds(Context context) {
soundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 100);
soundPoolMap = new HashMap(1);
soundPoolMap.put(R.raw.music1, soundPool.load(context, R.raw.music1, 1));
soundPoolMap.put(R.raw.music2, soundPool.load(context, R.raw.music2, 1));
}
public void playSound(int soundID) {
float volume = 0.2f;
// play sound with same right and left volume, with a priority of 1,
// zero repeats (i.e play once), and a playback rate of 1f
soundPool.play(soundPoolMap.get(soundID), volume, volume, 1, 0, 1f);
}
private void playSoundClick() {
playSound(R.raw.music1);
}
private void playSoundSelect() {
playSound(R.raw.music2);
}
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
playSoundClick();
} else {
playSoundSelect();
}
}
return true;
}
}
The sound is played here :
soundPool.play(soundPoolMap.get(soundID), volume, volume, 1, 0, 1f);
where you can set volume left & right and priority in case you want this sound to prevail over other if another one is being played in the same SoundPool
To integrate with your work :
public class HomeFragment extends MainFragment {
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
super.onCreate();
ImageView share = (ImageView)view.findViewById(R.id.share);
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
playSound(R.raw.music1);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "");
startActivity(Intent.createChooser(sharingIntent, "Share via"));
ImageView send = (ImageView)view.findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
playSound(R.raw.music2);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(""));
startActivity(intent);
}
});
return view;
}
}