I'm working on PlaceAutocompleteFragment. I load this Fragment Simply in the first time and when the load in a second time then show some error and its crashed.
Error is : java.lang.IllegalArgumentException: Binary XML file line
11: Duplicate id 0x7f090251, tag null, or parent id 0x7f090193 with another fragment for
com.google.android.gms.location.places.ui.PlaceAutocompleteFragment
public class MakeReservationFragment extends BaseFragment implements
GoogleApiClient.OnConnectionFailedListener , PlaceSelectionListener {
View mMakeReservationView;
ProgressBar bar;
FrameLayout layout;
private static final LatLngBounds BOUNDS_GREATER_SYDNEY = new
LatLngBounds(
new LatLng(-34.041458, 150.790100), new LatLng(-33.682247, 151.383362));
#Override
public View setContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mMakeReservationView = inflater.inflate(R.layout.frag_make_reservation, container, false);
initView();
return mMakeReservationView;
}
private void initView() {
setHeaderBarTitle("RESERVATION");
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getActivity().getFragmentManager().findFragmentById(R.id.place_fragment1);
autocompleteFragment.setOnPlaceSelectedListener(MakeReservationFragment.this);
autocompleteFragment.setHint("Search a Location");
autocompleteFragment.setBoundsBias(BOUNDS_GREATER_SYDNEY);
layout=(FrameLayout)mMakeReservationView.findViewById(R.id.framereserve1);
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
setHeaderBarleftIcon(R.drawable.ic_home);
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
}
return false;
}
});
}
#Override
public void onPlaceSelected(Place place) {
}
#Override
public void onError(Status status) {
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode ==RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(getActivity(), data);
onPlaceSelected(place,0);
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(getActivity(), data);
this.onError(status,0);
}
}
else
{
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(getActivity(), data);
onPlaceSelected(place,1);
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(getActivity(), data);
onError(status,1);
}
}
}
private void onError(Status status, int i) {
Toast.makeText(getActivity(), "Place selection failed: " + status.getStatusMessage(),
Toast.LENGTH_SHORT).show();
}
private void onPlaceSelected(Place place, int i) {
try{
System.out.println("00000000 Place Darta IS 0 error" + place.getId()+","+place.getAddress()+","+place.getLatLng()+","+place.getLocale()+","+place.getName()+
","+place.getAttributions()+","+place.getViewport()+","+place.getPhoneNumber()+","+place.getPlaceTypes());
}
catch ( Exception e)
{
}
}
}
And XML code is:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="#+id/framereserve1"
android:background="#color/backgoound_dull"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/place_fragment1"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
android:layout_width="match_parent"
android:layout_height="50dp"/>
Related
I want to display a captured image in my fragment but it is not showing, e.g. though the callback code in the fragment appears to be running.
Here's my Activity -
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
// Views and Context
private View nav_header_view;
private Context context;
// Widgets
private TextView tvCompanyName, tvCompanyEmail, tvName;
private ImageView imageView;
private ViewPager mViewPager;
public TabLayout tabLayout;
// Data
private FragmentManager manager;
private int selectNavId;
private ArrayList<Category> categoryArrayList = new ArrayList<>();
private String uuId = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
setTitle("Home");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager = (ViewPager) findViewById(R.id.container);
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) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
switch (selectNavId) {
case R.id.nav_search:
openSearchFragment();
break;
case R.id.nav_home:
displayTabForHomeFragment();
break;
case R.id.nav_daily_sales:
openDailySalesFragment();
break;
case R.id.nav_store:
openCompanyFragment();
break;
case R.id.nav_purchase:
openOrderedFragment();
break;
case R.id.nav_account:
openAccountFragment();
break;
case R.id.nav_logout:
logoutSession();
}
}
};
drawer.addDrawerListener(toggle);
toggle.syncState();
initializeUI();
checkUserSession();
}
private void initializeUI() {
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
nav_header_view = navigationView.getHeaderView(0);
tvName = (TextView) nav_header_view.findViewById(R.id.tv_name);
tvCompanyName = (TextView) nav_header_view.findViewById(R.id.tvCompanyName);
tvCompanyEmail = (TextView) nav_header_view.findViewById(R.id.tvEmail);
imageView = (ImageView) nav_header_view.findViewById(R.id.iv_profile_picture);
}
#Override
public void onResume() {
super.onResume();
refreshFragment();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.content_main);
if (f instanceof DailySalesFragment) {
closeSession();
} else {
// openHomeFragment();
openDailySalesFragment();
}
}
}
private void checkUserSession() {
String authToken = UserSession.getToken(this);
if (authToken.length() <= 0 && UserAccount.checkUserCount(context) > 0) {
openUserActivity();
} else if (authToken.length() <= 0) {
Intent login_intent = new Intent(this, LoginActivity.class);
startActivity(login_intent);
this.finish();
} else {
updateNavName(context);
openDailySalesFragment();
}
}
public void updateNavName(Context context) {
tvName.setText(UserSession.getFirstName(context) + " " + UserSession.getLastName(context));
tvCompanyName.setText(UserSession.getCompany(this));
tvCompanyEmail.setText(UserSession.getEmployeeEmail(this));
showProfilePic();
}
public void showProfilePic() {
// if (UserSession.getProfilePicture(context).contains("media")) {
// RequestOptions myOption = new RequestOptions().circleCrop();
// Glide.with(context).load(UserSession.getProfilePicture(context)).apply(myOption).into(imageView);
// }
}
private void logoutSession() {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
UserSession.clearSession(context);
removeAllInCart();
checkUserSession();
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
PopUpProvider.buildConfirmationDialog(context, dialogClickListener, "Confirm logout", "Are you sure you want to log out?");
}
private void closeSession() {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
MainActivity.super.onBackPressed();
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
PopUpProvider.buildConfirmationDialog(context, dialogClickListener, "Are you sure you want to close application?", null);
}
private void removeAllInCart() {
Checkout checkout = new Checkout();
checkout.deleteAll(context);
}
#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) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
selectNavId = id;
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void refreshFragment() {
try {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.content_main);
if (f instanceof CompanyFragment) {
openCompanyFragment();
} else if (f instanceof OrderedFragment) {
openOrderedFragment();
} else if (f instanceof AccountFragment) {
openAccountFragment();
} else {
// openHomeFragment();
openDailySalesFragment();
}
} catch (Exception err) {
Toasty.error(context, err.toString()).show();
}
}
private void openUserActivity() {
Intent intent = new Intent();
intent.setClass(context, UserAccountActivity.class);
startActivity(intent);
this.finish();
}
private void openHomeFragment(String uuid) {
Bundle bundle = new Bundle();
bundle.putString("uuid", uuid);
HomeFragment homeFragment = new HomeFragment();
homeFragment.setArguments(bundle);
manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_main, homeFragment, homeFragment.getTag()).commit();
}
private void openOrderedFragment() {
setTitle("My Purchases");
OrderedFragment orderedFragment = new OrderedFragment();
manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_main, orderedFragment, orderedFragment.getTag()).commit();
}
private void openAccountFragment() {
setTitle("Account");
AccountFragment accountFragment = new AccountFragment();
manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_main, accountFragment, "ACCOUNT_TAG").commit();
}
private void openCompanyFragment() {
setTitle("Store");
CompanyFragment companyFragment = new CompanyFragment();
manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_main, companyFragment, companyFragment.getTag()).commit();
}
private void openDailySalesFragment() {
setTitle("Daily Sales");
DailySalesFragment dailySalesFragment = new DailySalesFragment();
manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_main, dailySalesFragment, dailySalesFragment.getTag()).commit();
}
private void openSearchFragment() {
setTitle("Select Category");
replaceFragment(SearchFragment.class, null);
}
public void replaceFragment(Class fragmentClass, Bundle bundle) {
Fragment fragment = null;
try {
fragment = (Fragment) fragmentClass.newInstance();
fragment.setArguments(bundle);
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_main, fragment).commit();
}
// Online functions
public void fetchCategory() {
try {
HttpClientProvider.get(context, "read_category/", null, new JsonHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
}
#Override
public void onPreProcessResponse(ResponseHandlerInterface instance, HttpResponse response) {
super.onPreProcessResponse(instance, response);
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
tabLayout.removeAllTabs();
categoryArrayList = new Gson().fromJson(response.getJSONArray("records").toString(), new TypeToken<ArrayList<Category>>() {
}.getType());
Category category = new Category();
category.setName("All");
categoryArrayList.add(0, category);
for (Category inventory : categoryArrayList) {
tabLayout.addTab(tabLayout.newTab().setText(inventory.getName()));
}
} catch (Exception err) {
Toasty.error(context, err.toString()).show();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Toasty.error(context, "Can't Connect to Server").show();
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Toasty.error(context, responseString).show();
}
#Override
public void onRetry(int retryNo) {
super.onRetry(retryNo);
}
#Override
public void onFinish() {
}
});
} catch (Exception err) {
Toasty.error(context, err.toString()).show();
}
}
public void displayTabForHomeFragment() {
fetchCategory();
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
for (int i = 0; i < categoryArrayList.size(); i++) {
if (position > 0) {
uuId = categoryArrayList.get(position).getUuId();
Bundle bundle = new Bundle();
bundle.putString("uuid", uuId);
openHomeFragment(uuId);
break;
} else {
openHomeFragment("");
break;
}
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
Here's my Fragment -
public class AccountFragment extends Fragment {
private static final int REQUEST_IMAGE_CAPTURE = 1;
// View and Context
private View view;
private Context context;
// Widget
private EditText tvFirstName, tvLastName, tvCode, tvEmail, tvEmployeeId;
private ImageView imageView;
private ProgressDialog progressDialog;
private Button btnUpdate, btnUpload;
private boolean updateSuccess = false;
//Data
private ArrayList<UserAccount> userAccountArrayList = new ArrayList<>();
private String mCurrentPhotoPath;
private Bitmap mImageBitmap;
// Handles Interface and Initialization Functions
// Parameters - Default
// Return - View mag display sa layout
public AccountFragment(){
super();
}
public static AccountFragment newInstance(int sectionNumber) {
AccountFragment fragment = new AccountFragment();
Bundle args = new Bundle();
args.putInt("ARG_SECTION_NUMBER", sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_account, container, false);
return view;
}
#Override
public void onStart() {
super.onStart();
setHasOptionsMenu(true);
context = getContext();
initializeUI();
}
// Initialize component from a layout file
private void initializeUI() {
tvFirstName = view.findViewById(R.id.tv_firstname);
tvLastName = view.findViewById(R.id.tv_lastname);
tvCode = view.findViewById(R.id.tv_code);
tvEmail = view.findViewById(R.id.tv_email);
tvEmployeeId = view.findViewById(R.id.tv_employee_id);
imageView = view.findViewById(R.id.iv_User);
btnUpdate = view.findViewById(R.id.btn_update);
btnUpload = view.findViewById(R.id.btn_UploadImage);
((MainActivity) context).tabLayout.setVisibility(View.GONE);
getUserProfile();
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateUserProfile();
}
});
// showProfilePic();
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
}
private void dispatchTakePictureIntent() {
Intent camIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camIntent, REQUEST_IMAGE_CAPTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
private void showProfilePic() {
if (UserSession.getProfilePicture(context).contains("media")) {
RequestOptions myOption = new RequestOptions().circleCrop();
Glide.with(context).load(UserSession.getProfilePicture(context)).apply(myOption).into(imageView);
}
}
private void displayEmployeeDetails() {
tvFirstName.setText(UserSession.getFirstName(getContext()));
tvLastName.setText(UserSession.getLastName(getContext()));
tvCode.setText(UserSession.getEmployeeCode(getContext()));
tvEmail.setText(UserSession.getEmployeeEmail(getContext()));
tvEmployeeId.setText(UserSession.getYpoEmployeeId(getContext()));
// showProfilePic();
}
public void getUserProfile() {
try {
HttpClientProvider.get(context, "customer_profile/", null, new JsonHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false); // disable dismiss by tapping outside of the dialog
progressDialog.show();
}
#Override
public void onPreProcessResponse(ResponseHandlerInterface instance, HttpResponse response) {
super.onPreProcessResponse(instance, response);
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
UserSession session = new Gson().fromJson(response.toString(), new TypeToken<UserSession>() {
}.getType());
session.saveUserSession2(context);
if (session.saveUserSession2(context)) {
displayEmployeeDetails();
((MainActivity) getActivity()).updateNavName(context);
}
if (updateSuccess) {
Toasty.success(context, "Update success", Toast.LENGTH_SHORT).show();
//Update account in database
String searchQuery;
searchQuery = " WHERE e_mail LIKE '%" + UserSession.getEmployeeEmail(context) + "%' ";
userAccountArrayList = UserAccount.read(context, searchQuery);
for (UserAccount userAccount : userAccountArrayList) {
userAccount.setFirstName(UserSession.getFirstName(getContext()));
userAccount.setLastName(UserSession.getLastName(getContext()));
userAccount.setEmail(UserSession.getEmployeeEmail(getContext()));
userAccount.setToken(UserSession.getToken(getContext()));
userAccount.save(context);
}
}
} catch (Exception err) {
Toasty.error(context, err.toString()).show();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Debugger.printO("JSONObject " + throwable.toString());
Toasty.error(context, "Server Error").show();
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Toasty.error(context, responseString).show();
}
#Override
public void onFinish() {
progressDialog.dismiss();
}
});
} catch (Exception err) {
Toasty.error(context, err.toString()).show();
}
}
private void updateUserProfile() {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("first_name", tvFirstName.getText().toString());
jsonObject.put("last_name", tvLastName.getText().toString());
jsonObject.put("code", tvCode.getText().toString());
jsonObject.put("ypo_employee_id", tvEmployeeId.getText().toString());
StringEntity stringEntity = new StringEntity(jsonObject.toString());
HttpClientProvider.post(context, "customer_profile/", stringEntity, new JsonHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false); // disable dismiss by tapping outside of the dialog
progressDialog.show();
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
super.onSuccess(statusCode, headers, response);
getUserProfile();
updateSuccess = true;
} catch (Exception err) {
Toasty.error(context, err.toString()).show();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Toasty.error(context, "Server Error").show();
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Toasty.error(context, errorResponse.toString()).show();
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Toasty.error(context, responseString).show();
}
#Override
public void onFinish() {
progressDialog.dismiss();
}
});
} catch (Exception err) {
Toasty.error(context, err.toString()).show();
}
}
//Hide item in Action bar
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem menuItem = menu.findItem(R.id.action_cart);
MenuItem quantityItem = menu.findItem(R.id.action_quantity);
MenuItem searchViewItem = menu.findItem(R.id.action_search);
MenuItem menuRemove = menu.findItem(R.id.action_remove_all);
menuRemove.setVisible(false);
menuItem.setVisible(false);
quantityItem.setVisible(false);
searchViewItem.setVisible(false);
}
Here's my Manifest -
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-feature android:name="android.hardware.camera" android:required="true"/>
When I clicked the Camera intent in the fragment, the imageview in my fragment wouldn't change. I don't know why is this happening because it works perfectly fine in an activity.
In Activity.onResume () you end up calling openAccountFragment (). This creates a new fragment and is run every time the screen becomes visible.(By the way a possibly unrelated bug is that you are not calling newInstance() here.)
Each time you create a new fragment, the old one is removed.
But your call back function is happening on the old fragment, which is no longer attached or therefore visible (note this ties in with Mike's comments)
The solution is to not replace the existing fragment with a new one if you already have the right type.
override onActivityResult into MainActivity. make imageView public and access imageView into activity result method as follow.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.content_main);
if (f instanceof AccountFragment) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
f.imageView.setImageBitmap(photo);
}
}
}
Hi I am using this library for my android bar code reader and it is working fine with activities but it give some what delay in initiate(Not smooth like when it use in the Activities)when use with the fragment any solution for this.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_gravity="top"
android:minHeight="?attr/actionBarSize"
android:background="#color/actionbar_opacity"
app:theme="#style/TransparentToolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<RelativeLayout
android:id="#+id/btn_enable_qr"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginBottom="55dp"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
android:gravity="bottom"
android:layout_alignParentBottom="true"
android:clickable="true"
android:layout_gravity="bottom"
android:background="#drawable/circle_layout_for_start_scan">
</RelativeLayout>
</RelativeLayout>
This is My Fragment & when application start I set this fragment to my main activity
public class ScannerFragment extends Fragment implements ZBarScannerView.ResultHandler {
private ZBarScannerView mScannerView;
private FrameLayout contentFrame;
RelativeLayout enableQR;
private static final int ZBAR_CAMERA_PERMISSION = 1;
public static ScannerFragment newInstance() {
return new ScannerFragment();
}
#SuppressLint("ClickableViewAccessibility")
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = null;
try {
rootView = inflater.inflate(R.layout.activity_full_scanner, container, false);
contentFrame = (FrameLayout) rootView.findViewById(R.id.content_frame);
enableQR = (RelativeLayout) rootView.findViewById(R.id.btn_enable_qr);
enableQR.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
launchActivity();
break;
}
case MotionEvent.ACTION_UP: {
releaseCamera();
}
}
return true;
}
});
} catch (Exception e) {
// Log.e(TAG, "onCreateView: " + e.toString());
}
return rootView;
}
#Override
public void onResume() {
super.onResume();
}
public void launchActivity() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.CAMERA}, ZBAR_CAMERA_PERMISSION);
} else {
setUpQrScanner();
}
}
public void setUpQrScanner() {
mScannerView = new ZBarScannerView(getActivity());
mScannerView.setFormats(BarcodeFormat.ALL_FORMATS);
contentFrame.addView(mScannerView);
mScannerView.setResultHandler(ScannerFragment.this);
mScannerView.startCamera(-1);
mScannerView.setAutoFocus(true);
}
public void releaseCamera() {
mScannerView.stopCamera();
contentFrame.removeView(mScannerView);
}
#Override
public void handleResult(Result rawResult) {
try {
scannerSoundAndVibration();
} catch (Exception e) {}
Toast.makeText(getActivity(), "Result" + rawResult.getContents()+" TYPE: "+rawResult.getBarcodeFormat().getId(), Toast.LENGTH_LONG).show();
}
#Override
public void onPause() {
super.onPause();
}
private void scannerSoundAndVibration() {
/**
* scanner sound alert time in millisecond
*/
final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 200);
tg.startTone(ToneGenerator.TONE_CDMA_KEYPAD_VOLUME_KEY_LITE);
/**
* scanner vibration alert time in millisecond
*/
Vibrator v = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(250);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case ZBAR_CAMERA_PERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setUpQrScanner();
} else {
Toast.makeText(getActivity(), "Please grant camera permission to use the QR Scanner", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
I am having trouble while using PlaceAutocompleteFragment with custom layout.
First time when i click on it it just get focus and another time click it popup.
i used that inside fragment class.
here is link that uploaded video on it .
i used EditText on custom layout.
Here is demo video
MainFragment.class
PlaceAutocompleteFragment placeAutocompleteFragment = (PlaceAutocompleteFragment) getActivity().getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
//.setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES)
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_REGIONS)
.build();
placeAutocompleteFragment.setFilter(typeFilter);
placeAutocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
//places.setText(""+place.getAddress());
Log.d("Filtered",""+place.getId());
Log.d("Filtered",""+place.getAddress());
Log.d("Filtered",""+place.getLocale());
Log.d("Filtered",""+place.getPlaceTypes());
}
#Override
public void onError(Status status) {
}
});
CustomPlaceAutoCompleteFragment.class :
public class CustomPlaceAutoCompleteFragment extends PlaceAutocompleteFragment {
private EditText editSearch;
private View zzaRh;
private View zzaRi;
private EditText zzaRj;
#Nullable
private LatLngBounds zzaRk;
#Nullable
private AutocompleteFilter zzaRl;
#Nullable
private PlaceSelectionListener zzaRm;
public CustomPlaceAutoCompleteFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View var4 = inflater.inflate(R.layout.custom_place_auto_complete_fragment, container, false);
editSearch = (EditText) var4.findViewById(R.id.editWorkLocation);
editSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
zzzG();
}
});
return var4;
}
public void onDestroyView() {
this.zzaRh = null;
this.zzaRi = null;
this.editSearch = null;
super.onDestroyView();
}
public void setBoundsBias(#Nullable LatLngBounds bounds) {
this.zzaRk = bounds;
}
public void setFilter(#Nullable AutocompleteFilter filter) {
this.zzaRl = filter;
}
public void setText(CharSequence text) {
this.editSearch.setText(text);
//this.zzzF();
}
public void setHint(CharSequence hint) {
this.editSearch.setHint(hint);
this.zzaRh.setContentDescription(hint);
}
public void setOnPlaceSelectedListener(PlaceSelectionListener listener) {
this.zzaRm = listener;
}
private void zzzF() {
boolean var1 = !this.editSearch.getText().toString().isEmpty();
//this.zzaRi.setVisibility(var1?0:8);
}
private void zzzG() {
int var1 = -1;
try {
Intent var2 = (new PlaceAutocomplete.IntentBuilder(2)).setBoundsBias(this.zzaRk).setFilter(this.zzaRl).zzh(this.editSearch.getText().toString()).zzg(1).build(this.getActivity());
this.startActivityForResult(var2, 1);
} catch (GooglePlayServicesRepairableException var3) {
var1 = var3.getConnectionStatusCode();
Log.e("Places", "Could not open autocomplete activity", var3);
} catch (GooglePlayServicesNotAvailableException var4) {
var1 = var4.errorCode;
Log.e("Places", "Could not open autocomplete activity", var4);
}
if (var1 != -1) {
GoogleApiAvailability var5 = GoogleApiAvailability.getInstance();
var5.showErrorDialogFragment(this.getActivity(), var1, 2);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == -1) {
Place var4 = PlaceAutocomplete.getPlace(this.getActivity(), data);
if (this.zzaRm != null) {
this.zzaRm.onPlaceSelected(var4);
}
this.setText(var4.getName().toString());
} else if (resultCode == 2) {
Status var5 = PlaceAutocomplete.getStatus(this.getActivity(), data);
if (this.zzaRm != null) {
this.zzaRm.onError(var5);
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Set input type of you city EditText
editText1= (EditText) super.getActivity().findViewById(R.id.editText1);
editText1.setInputType(InputType.TYPE_NULL);
In my form fragment Hardware "back" button work not correctly. For example when I opened fragment and when I didn't start typing, and I pressed Hardware "back" button it's work excellent. But when I started typing and after typing press to Hardware "back" button app crashed without any error logs.
my form fragment
public class D_Category_Login extends Fragment implements View.OnClickListener{
public static FragmentListItemClick fragmentListItemClick;
EditText edt_name,edt_lastname,edt_phone,edt_pass1,edt_pass2;
String name="";
DBHelper dbHelper;
public static final String REGISTER_URL = "http://admin.unimax.kz/api/Klientapi/AddClient?";
public static final String KEY_USERNAME = "first_name";
public static final String KEY_LASTNAME = "last_name";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.form_login, null);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Регистрация");
edt_name = (EditText) view.findViewById(R.id.edt_firstname);
edt_lastname = (EditText) view.findViewById(R.id.lastname);
edt_phone = (EditText) view.findViewById(R.id.login);
edt_pass1 = (EditText) view.findViewById(R.id.pass);
edt_pass2 = (EditText) view.findViewById(R.id.pass_repeet);
Button btn_submit = (Button) view.findViewById(R.id.btn_submit);
TextView tv_number = (TextView) view.findViewById(R.id.tv_number);
btn_submit.setOnClickListener(this);
tv_number.setOnClickListener(this);
edt_phone.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
if(!s.toString().contains("+7 ")){
edt_phone.setText("+7 ");
Selection.setSelection(edt_phone.getText(), edt_phone.getText().length());
}
}
});
return view;
}
void setfragmentclick(FragmentListItemClick fr){
fragmentListItemClick = fr;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_submit:{
if (edt_name.getText().toString().trim().isEmpty() || edt_lastname.getText().toString().trim().isEmpty()){
if (edt_name.getText().toString().trim().isEmpty()) {
edt_name.setError("Заполните это поле");
requestFocus(edt_name);
}
if (edt_lastname.getText().toString().trim().isEmpty()) {
edt_lastname.setError("Заполните это поле");
requestFocus(edt_lastname);
}
}
else {
CheckInternet();
}
}
break;
case R.id.tv_number:{
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "+77079300066"));
startActivity(intent);
}
break;
}
}
void CheckInternet(){
if (isOnline()){
registerUser();
}
else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
alertDialogBuilder.setMessage("Проверьте подключение к Интернету");
alertDialogBuilder.setPositiveButton("Закрыть", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
void registerUser(){
final String first_name = edt_name.getText().toString().trim();
final String last_name = edt_lastname.getText().toString().trim();
String fill_url = REGISTER_URL+"familia="+Uri.encode(last_name)+"&name="+Uri.encode(first_name);
StringRequest stringRequest = new StringRequest(Request.Method.POST, fill_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dbHelper = new DBHelper(getContext());
final ContentValues cv = new ContentValues();
final SQLiteDatabase db = dbHelper.getWritableDatabase();
name+= String.valueOf(edt_name.getText()+" "+String.valueOf(edt_lastname.getText()));
cv.put("id_user", Integer.valueOf(response));
cv.put("name", name);
db.execSQL("delete from form_login");
db.insert("form_login",null, cv);
db.close();
dbHelper.close();
getFragmentManager().popBackStack();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),"Ошибка сервера"+error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
}
My form fragment is child fragment. And this parent fragment where I implement backaction.
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
backAction();
return true;
}
return false;
}
});
}
public void backAction() {
if (getChildFragmentManager().getBackStackEntryCount() > 0) {
getChildFragmentManager().popBackStack();
}
else {
((MainActivity) getActivity()).setCurrentItem(0, true);
}
}
Create TextWatcher like
TextWatcher textWatcher=new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
if(!s.toString().contains("+7 ")){
edt_phone.setText("+7 ");
Selection.setSelection(edt_phone.getText(), edt_phone.getText().length());
}
};
Add it to edt_phone like
edt_phone.addTextChangedListener(textWatcher);
Then in the back press event remove the listener,
getView().setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
edt_phone.removeTextChangedListener(textWatcher);
return true;
}
}
return false;
}
});
In your foam fragment(child fragment)
Communicator communicator;
#Override
public void onBackPressed() {
super.onBackPressed();
communicator.exitFragment();
}
public void setCommunicator(Communicator communicator)
{
this.communicator = communicator;
}
public interface Communicator
{
void exitFragment();
}
in your parent fragment do this
public parentFragment extends Fragment implements childFragment.Communicator
{
#override
public void onCreatView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
childFragment.setCommunicator(this);
}
public void exitFragment()
{
getActivity().finish();
}
}
Fragments are managed by the Fragment Managers which are called by the Activity; so, to control what you want to do when the back button is clicked, you must do that in the activity;
Now, if you have more than one fragment set, you should use tags to find them, check to see if they are visible and if so, do what you mentioned above.
When setting your fragments, you should give them a tag and then use this tag later to findFragmentByTagName() and do an if check to see which fragment is set at the moment;
Let me know if you need any clarification on the same.
Using android studio
I am trying to sign in from a fragment
Activity Code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState==null)
{
Fragment fragment = null;
fragment=new LoginFragment();
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == LoginFragment.RC_SIGN_IN) {
LoginFragment fragment = (LoginFragment) getFragmentManager()
.findFragmentById(R.id.frameLayoutLogin);
fragment.onActivityResult(requestCode, resultCode, data);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
Fragment code:
public class LoginFragment extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, View.OnClickListener {
/* Request code used to invoke sign in user interactions. */
public static final int RC_SIGN_IN = 0;
/* Client used to interact with Google APIs. */
private GoogleApiClient mGoogleApiClient;
/* A flag indicating that a PendingIntent is in progress and prevents
* us from starting further intents.
*/
private boolean mIntentInProgress;
/**
* True if the sign-in button was clicked. When true, we know to resolve all
* issues preventing sign-in without waiting.
*/
private boolean mSignInClicked;
public LoginFragment() {
// Required empty public constructor
}
#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
View v = inflater.inflate(R.layout.fragment_login, container, false);
v.findViewById(R.id.sign_in_button).setOnClickListener(this);
mGoogleApiClient = new GoogleApiClient.Builder(((MainActivity)getActivity()))
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.build();
return v;
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onResume() {
super.onResume();
getActivity().setTitle("Login");
}
#Override
public void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(Bundle bundle) {
mSignInClicked = false;
Toast.makeText(getActivity(), "User is connected!", Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (!mIntentInProgress) {
if (mSignInClicked && connectionResult.hasResolution()) {
// The user has already clicked 'sign-in' so we attempt to resolve all
// errors until the user is signed in, or they cancel.
try {
connectionResult.startResolutionForResult(((MainActivity)getActivity()), RC_SIGN_IN);
mIntentInProgress = true;
} catch (IntentSender.SendIntentException e) {
// The intent was canceled before it was sent. Return to the default
// state and attempt to connect to get an updated ConnectionResult.
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode != MainActivity.RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnected()) {
mGoogleApiClient.reconnect();
}
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.sign_in_button && !mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
mGoogleApiClient.connect();
}
}
}
I getting null pointer exception when I select the email:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=null} to activity {com.rnit/com.rnit.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3447)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3490)
at android.app.ActivityThread.access$1300(ActivityThread.java:145)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1291)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5127)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.rnit.MainActivity.onActivityResult(MainActivity.java:45)
at android.app.Activity.dispatchActivityResult(Activity.java:5423)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3443)
Line no 45 is
fragment.onActivityResult(requestCode, resultCode, data);
What is the issue here? Any help?
Add this after your mGoogleApiClient initiated
Intent intent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(intent, requestCode);