onNewIntent never being called in Activity - android

I have asked multiple questions on SO regarding different problems I am having with onNewIntent method in both fragments and activities. My problem now is that onNewIntent in Activity is never being called no matter what I do. The Activity that has the onNewIntent contains multiple tabs. My tabs (Fragments) contain codes for writing and reading NFC tag.
This is the code for the Activity:
public class MyAppHome extends AppCompatActivity {
protected DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mtoggle;
NfcAdapter nfcAdapter;
private Toolbar mtoolbar;
private TextView mName;
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private NavigationView mNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_layout);
mtoolbar = (Toolbar) findViewById(R.id.nav_action);
setSupportActionBar(mtoolbar);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
mNavigationView= (NavigationView)findViewById(R.id.nav_view);
mDrawerLayout = findViewById(R.id.drawer_layout);
mtoggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mtoggle);
mtoggle.syncState();
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
tabLayout.setupWithViewPager(mViewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition())
{
case 0:
mViewPager.setCurrentItem(0);
mtoolbar.setTitle("Home");
break;
case 1:
mViewPager.setCurrentItem(1);
mtoolbar.setTitle("Writer");
break;
case 2:
mViewPager.setCurrentItem(2);
mtoolbar.setTitle("Reader");
break;
case 3:
mViewPager.setCurrentItem(3);
mtoolbar.setTitle("Others");
break;
case 4:
mViewPager.setCurrentItem(4);
mtoolbar.setTitle("Alarm");
break;
default:
mViewPager.setCurrentItem(tab.getPosition());
mtoolbar.setTitle("My APP");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
// set item as selected to persist highlight
menuItem.setChecked(true);
switch (menuItem.getItemId()){
case R.id.nav_home:
mViewPager.setCurrentItem(0);
mDrawerLayout.closeDrawers();
mtoolbar.setTitle("Home");
break;
case R.id.nav_writer:
mViewPager.setCurrentItem(1);
mDrawerLayout.closeDrawers();
mtoolbar.setTitle("Writer");
break;
case R.id.nav_medication:
mViewPager.setCurrentItem(2);
mDrawerLayout.closeDrawers();
mtoolbar.setTitle("Reader");
break;
case R.id.nav_missedPill:
mViewPager.setCurrentItem(3);
mDrawerLayout.closeDrawers();
mtoolbar.setTitle("Others");
break;
case R.id.nav_alarm:
mViewPager.setCurrentItem(4);
mDrawerLayout.closeDrawers();
mtoolbar.setTitle("Alarm");
break;
case R.id.nav_logout:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(getApplicationContext(),Login.class));
}
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
return true;
}
});
mDrawerLayout.addDrawerListener(
new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// Respond when the drawer's position changes
}
#Override
public void onDrawerOpened(View drawerView) {
// Respond when the drawer is opened
}
#Override
public void onDrawerClosed(View drawerView) {
// Respond when the drawer is closed
}
#Override
public void onDrawerStateChanged(int newState) {
// Respond when the drawer motion state changes
}
}
);
initNFC(getIntent());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_dosis_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mtoggle.onOptionsItemSelected(item)){
return true;
}
//noinspection SimplifiableIfStatement
if (item.getItemId()== R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
IntentFilter[] nfcIntentFilter = new IntentFilter[]{techDetected,tagDetected,ndefDetected};
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, new Intent(this.getApplicationContext(), this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
if(nfcAdapter !=null){
Log.d("W", "nfcadapter is not null");
nfcAdapter.enableForegroundDispatch(this, pendingIntent, nfcIntentFilter, null);
}
}
#Override
public void onPause() {
super.onPause();
if(nfcAdapter !=null){
disableForegroundDispatchSystem();
}
}
public boolean write2NFC(MyNfcMessage m ) {
NdefMessage ndefMessage = createNdefMessage(m.key1, m.key2,m.key3);
writeNdefMessage(tag, ndefMessage);
return true;
}
private void initNFC(Intent intent) {
if (intent.hasExtra(NfcAdapter.EXTRA_TAG)) {
// if (nfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
//Toast.makeText(getActivity(), "NfcIntent!", Toast.LENGTH_SHORT).show();
tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
}
}
protected void onNewIntent(Intent intent) {
System.out.print("I am here in Home");
Log.d("my tag", "I am here now");
initNFC(intent);
Log.d("my tag ", "onNewIntent: something ");
}
private void disableForegroundDispatchSystem() {
nfcAdapter.disableForegroundDispatch(this);
}
private void formatTag(Tag tag, Nde
fMessage ndefMessage) {
try {
NdefFormatable ndefFormatable = NdefFormatable.get(tag);
if (ndefFormatable == null) {
Toast.makeText(this, "Tag is not ndef formatable!", Toast.LENGTH_SHORT).show();
}
else{
ndefFormatable.connect();
ndefFormatable.format(ndefMessage);
ndefFormatable.close();
Toast.makeText(this, "Tag writen!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e("formatTag", e.getMessage());
}
}
private void writeNdefMessage(Tag tag, NdefMessage ndefMessage) {
try {
if (tag == null) {
Toast.makeText(this, "Tag object cannot be null", Toast.LENGTH_SHORT).show();
return;
}
Ndef ndef = Ndef.get(tag);
if (ndef == null) {
// format tag with the ndef format and writes the message.
formatTag(tag, ndefMessage);
} else {
ndef.connect();
if (!ndef.isWritable()) {
Toast.makeText(this, "Tag is not writable!", Toast.LENGTH_SHORT).show();
ndef.close();
return;
}
ndef.writeNdefMessage(ndefMessage);
ndef.close();
Toast.makeText(this, "Tag writen!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e("writeNdefMessage", e.getMessage());
}
}
private NdefRecord createTextRecord(String content) {
try {
byte[] language;
language = Locale.getDefault().getLanguage().getBytes("UTF-8");
final byte[] text = content.getBytes("UTF-8");
final int languageSize = la
nguage.length;
final int textLength = text.length;
final ByteArrayOutputStream payload = new ByteArrayOutputStream(1 + languageSize + textLength);
payload.write((byte) (languageSize & 0x1F));
payload.write(language, 0, languageSize);
payload.write(text, 0, textLength);
return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload.toByteArray());
} catch (UnsupportedEncodingException e) {
Log.e("createTextRecord", e.getMessage());
}
return null;
}
private NdefMessage createNdefMessage(String content, String content2, String content3) {
NdefRecord ndefRecord = createTextRecord(content);
NdefRecord ndefRecord2 = createTextRecord(content2);
NdefRecord ndefRecord3 = createTextRecord(content3);
NdefMessage ndefMessage = new NdefMessage(new NdefRecord[]{ndefRecord, ndefRecord2, ndefRecord3});
return ndefMessage;
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragments = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
mFragments.add(new Home());
mFragments.add(new Writer());
mFragments.add(new Reader());
mFragments.add(new Others());
mFragments.add(new Alarm());
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
/*to set text instead of icons*/
public CharSequence getPageTitle(int position){
return null;
}
}
}
My AndroidManifest looks something like this:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<uses-feature
android:name="android.hardware.fingerprint"
android:required="false" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:launchMode="singleTop"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".WelcomeActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".FingerPrint"
android:screenOrientation="portrait" />
<activity
android:name=".MyAppHome"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.nfc.action.TAG_DISCOVERED" />
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<data android:mimeType="text/plain" />
</intent-filter>
<meta-data
android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="#xml/nfc_tech_filter" />
</activity>
<activity
android:name=".Login"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar" />
</application>
Home Fragment (tab) is used to write information to NFC tag:
public class Home extends Fragment {
NfcAdapter nfcAdapter;
Button writebtn;
Tag tag;
EditText txtName, txtCountry, txtID;
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view,savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.home, container,false);
txtName = (EditText)view.findViewById(R.id.pName);
txtCountry= (EditText)view.findViewById(R.id.pCountry);
txtID= (EditText)view.findViewById(R.id.pID);
writebtn=(Button)view.findViewById(R.id.nfcWriteBtn);
writebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MyAppHome homeActivity = (MyAppHome)getActivity();
MyNfcMessage message = new MyNfcMessage(txtName.getText().toString(), txtCountry.getText().toString(), txtID.getText().toString());
homeActivity.write2NFC(message);
}
});
return v;
}
I don't Understand Why onNewIntent in the Activity is never being called (No Toasts are being displayed on screen). Does it have something to do with my layout?
Update: The problem was solved by creating a new project and copying all the code from the old project to the new one.

Check this:
http://www.helloandroid.com/tutorials/communicating-between-running-activities
In manifest.xml, in an activity tag set launchmode="singleTask"

Related

How to add Swipe Down Refresh feature in a Tab View Layout

This is the MainActivity of my Tab View Layout
package com.nitol.aust.cse.austclassmanager;
public class ResultCheckActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{
private TabLayout t1;
private ViewPager vp1;
Toolbar toolbar;
DrawerLayout drawerLayout;
NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navi_draw_result);
t1 = (TabLayout) findViewById(R.id.tab1);
vp1 = (ViewPager) findViewById(R.id.ViewPager1);
setUpMyViewPager(vp1);
t1.setupWithViewPager(vp1);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout) ;
navigationView = (NavigationView) findViewById(R.id.navigation_view);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle
(this,drawerLayout,toolbar, R.string.open_drawer, R.string.close_drawer);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
navigationView.getMenu().getItem(5).setChecked(true);
}
void setUpMyViewPager(ViewPager vp){
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addMyFragment(new WebViewEvents(),"News & Events");
viewPagerAdapter.addMyFragment(new WebViewAcademic(),"Academic Calendar");
viewPagerAdapter.addMyFragment(new WebViewTheory(),"Theory Results");
viewPagerAdapter.addMyFragment(new WebViewLab(),"Lab Results");
viewPagerAdapter.addMyFragment(new WebViewTeacher(),"Faculty Members");
vp.setAdapter(viewPagerAdapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> my_list = new ArrayList<Fragment>();
private final List<String> my_title = new ArrayList<String>();
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
return my_list.get(position);
}
#Override
public int getCount() {
return my_list.size();
}
void addMyFragment(Fragment f, String title){
my_list.add(f);
my_title.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return my_title.get(position);
}
}
#Override
public void onBackPressed() {
if(drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
else{
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.home:
Intent intent0 = new Intent(ResultCheckActivity.this, MenuActivity.class);
startActivity(intent0);
finish();
break;
case R.id.routine:
Intent intent = new Intent(ResultCheckActivity.this, ClassRoutineActivity.class);
startActivity(intent);
finish();
break;
case R.id.cgpa:
Intent intent2 = new Intent(ResultCheckActivity.this, CgpaCalculator.class);
startActivity(intent2);
finish();
break;
case R.id.details:
Toast.makeText(getApplicationContext(),"Class Details",Toast.LENGTH_SHORT).show();
break;
case R.id.quiz:
Toast.makeText(getApplicationContext(),"Quiz Reminder",Toast.LENGTH_SHORT).show();
break;
case R.id.result:
break;
case R.id.profile:
Intent intent3 = new Intent(ResultCheckActivity.this, ProfileActivity.class);
startActivity(intent3);
finish();
break;
case R.id.about:
Toast.makeText(getApplicationContext(),"About",Toast.LENGTH_SHORT).show();
break;
case R.id.settings:
Intent intent4 = new Intent(ResultCheckActivity.this, Settings.class);
startActivity(intent4);
finish();
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_tool,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.tool_settings){
Intent intent = new Intent(ResultCheckActivity.this, Settings.class);
startActivity(intent);
}
else if(id == R.id.tool_about){
Toast.makeText(getApplicationContext(),"This is About !", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
}
And this is my those tabs where i want to add refresh feature
void setUpMyViewPager(ViewPager vp){
ViewPagerAdapter viewPagerAdapter = new
ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addMyFragment(new WebViewEvents(),"News & Events");
viewPagerAdapter.addMyFragment(new WebViewAcademic(),"Academic Calendar");
viewPagerAdapter.addMyFragment(new WebViewTheory(),"Theory Results");
viewPagerAdapter.addMyFragment(new WebViewLab(),"Lab Results");
viewPagerAdapter.addMyFragment(new WebViewTeacher(),"Faculty Members");
vp.setAdapter(viewPagerAdapter);
}
Now suppose i want to add refresh on "WebViewEvents" class. The class is given below
package com.nitol.aust.cse.austclassmanager;
public class WebViewEvents extends Fragment {
View v;
WebView wb4;
private String currentUrl = "http://aust.edu/news_events.htm";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.webview_event, container,false);
wb4 = (WebView) v.findViewById(R.id.webView_event);
wb4.setInitialScale(1);
wb4.getSettings().setJavaScriptEnabled(true);
wb4.getSettings().setLoadWithOverviewMode(true);
wb4.getSettings().setUseWideViewPort(true);
wb4.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
wb4.setScrollbarFadingEnabled(false);
wb4.loadUrl(currentUrl);
wb4.setWebViewClient(new WebViewClient());
wb4.getSettings().setBuiltInZoomControls(true);
wb4.getSettings().setUseWideViewPort(true);
wb4.getSettings().setLoadWithOverviewMode(true);
wb4.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
return v;
}
}
I found some instructions here but maximum of those was said that i have to #Override onRefresh() method...but i declared my class as a non activity class. so in a non activity class , i can not override a method. that's why i am not finding my solutions...
You just need to read docs on SwipeRefreshLayout
First, add SwipeRefreshLayout to your activity layout:
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
// here is your content
</android.support.v4.widget.SwipeRefreshLayout>
Then find instance of swipe refresh layout in your activity:
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefresh);
And set refresh listener in which trigger your update method
/*
* Sets up a SwipeRefreshLayout.OnRefreshListener that is invoked when the user
* performs a swipe-to-refresh gesture.
*/
mSwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.i(LOG_TAG, "onRefresh called from SwipeRefreshLayout");
// This method performs the actual data-refresh operation.
// The method calls setRefreshing(false) when it's finished.
myUpdateOperation();
}
}
);
For more information read docs, link in the beginning of the answer.
Also you might look at google samples:
SwipeRefreshLayoutBasic
SwipeRefreshListFragment
List of all google samples you can find here
Hope it helps
Finally this is worked for me
package com.nitol.aust.cse.austclassmanager;
public class WebViewEvents extends Fragment{
View v;
WebView wb4;
SwipeRefreshLayout mySwipeRefreshLayout;
private String currentUrl = "http://aust.edu/news_events.htm";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.webview_event, container,false);
mySwipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swiperefresh);
wb4 = (WebView) v.findViewById(R.id.webView_event);
wb4.setInitialScale(1);
wb4.getSettings().setJavaScriptEnabled(true);
wb4.getSettings().setLoadWithOverviewMode(true);
wb4.getSettings().setUseWideViewPort(true);
wb4.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
wb4.setScrollbarFadingEnabled(false);
wb4.loadUrl(currentUrl);
wb4.setWebViewClient(new WebViewClient());
wb4.getSettings().setBuiltInZoomControls(true);
wb4.getSettings().setUseWideViewPort(true);
wb4.getSettings().setLoadWithOverviewMode(true);
wb4.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
wb4.setWebViewClient(new MyWebViewClient());
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
wb4.loadUrl(currentUrl);
}
}
);
return v;
}
public class MyWebViewClient extends WebViewClient{
#Override
public void onPageFinished(WebView view, String url) {
mySwipeRefreshLayout.setRefreshing(false);
currentUrl = url;
super.onPageFinished(view, url);
}
}
}
I added this override method inside my class
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
wb4.loadUrl(currentUrl);
}
}
);
Then added this to stop the refreshing animation
public class MyWebViewClient extends WebViewClient{
#Override
public void onPageFinished(WebView view, String url) {
mySwipeRefreshLayout.setRefreshing(false);
currentUrl = url;
super.onPageFinished(view, url);
}
}
Don't forget to add the instance of the last stopping animation impliment
wb4.setWebViewClient(new MyWebViewClient());

How to handle camera while switching between fragments?

I am switching between 2 different fragments using 2 buttons. One fragment has a camera view and opens pretty well for the first time, but when returning to the same fragment again from second fragment gives a blank screen. camera preview cannot be seen although camera hardware is free.I am NOT using camera2 api but needs a solution to this bug. i have added my complete code and images for assistance.
MAnifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.root.meeransunday" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar"
android:screenOrientation="portrait"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<supports-screens android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:xlargeScreens="true"
android:anyDensity="true"
android:resizeable="true"/>
</application>
<activity android:name="meeranSunday"
android:configChanges="orientation|keyboardHidden"
/>
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.CAMERA">
</uses-permission>
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature android:name="android.hardware.camera" />
</manifest>
Fragment java class
public class scan extends Fragment implements ZXingScannerView.ResultHandler {
private ZXingScannerView zXingScannerView;
private SurfaceView mySurfaceView;
private Camera mCamera;
private CameraPreview mPreview;
private String m_Text = "";
private String number = "";
private OnFragmentInteractionListener mListener;
public scan() {}
#Override
public void handleResult(Result rawResult) {
// Do something with the result here
Log.e("handler", rawResult.getText()); // Prints scan results
Log.e("handler", rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode)
// show the scanner result into dialog box.
AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
builder.setTitle("Scan Result");
builder.setMessage(rawResult.getText());
number = rawResult.getText().substring(rawResult.getText().length() - 13);
//
final EditText input = new EditText(this.getActivity());
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(number, null, m_Text + " Transferred To Your Account From MTM Account", null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
//
AlertDialog alert1 = builder.create();
alert1.show();
// If you would like to resume scanning, call this method below:
zXingScannerView.resumeCameraPreview(this);
}
// TODO: Rename and change types and number of parameters
public static scan newInstance() {
scan fragment = new scan();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_scan, container, false);
if (checkCameraHardware(getActivity().getApplicationContext())) {
Toast.makeText(this.getActivity(), "camera hardware is free", Toast.LENGTH_SHORT).show();
zXingScannerView = new ZXingScannerView(this.getActivity().getApplicationContext());
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera(0);
} else {
Toast.makeText(this.getActivity(), "camera hardware is NOT free", Toast.LENGTH_SHORT).show();
}
FrameLayout preview = (FrameLayout) view.findViewById(R.id.camera_preview);
preview.addView(zXingScannerView);
return view;
}
#Override
public void onPause() {
super.onPause();
try {
mCamera = Camera.open();
} catch (RuntimeException e) {
Log.d("camera opening attempt:", e.getMessage());
} finally {
if (mCamera != null) {
Log.d("camera opening attempt:", "yups ");
mCamera.release();
zXingScannerView.stopCamera();
zXingScannerView.stopCameraPreview();
}
}
}
#Override
public void onResume() {
super.onResume();
zXingScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
zXingScannerView.startCamera(0); // Start camera on resume
}
public boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return true;
} else {
return false;
}
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString() +
" must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
Log.d("aa", "sdsdssdsddssssd");
try {
mCamera = Camera.open();
} catch (RuntimeException e) {
Log.d("camera opening attempt:", e.getMessage());
} finally {
if (mCamera != null) {
mCamera.release();
zXingScannerView.stopCamera();
zXingScannerView.stopCameraPreview();
}
}
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name\
void onFragmentInteraction(Uri uri);
}
}
MAinactivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public int check = 0;
#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();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
message frags = new message();
fragmentTransaction.add(R.id.content_main, frags, "text");
fragmentTransaction.commit();
check += 1;
}
public void message(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
message sms = new message();
fragmentTransaction.replace(R.id.content_main, sms, "text");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
public void scan(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
scan scan = new scan();
fragmentTransaction.replace(R.id.content_main, scan, "scan");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
public void loadooncreate() {
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();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
message frags = new message();
fragmentTransaction.add(R.id.content_main, frags, "text");
fragmentTransaction.commit();
check += 1;
}
#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);
Toolbar toolbar2 = (Toolbar) findViewById(R.id.toolbar1);
toolbar2.inflateMenu(R.menu.notify);
toolbar2.getMenu().findItem(R.id.notifications).setIcon(buildCounterDrawable(2, R.drawable.notification));
toolbar2.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem arg0) {
if (arg0.getItemId() == R.id.notifications) {
arg0.setIcon(buildCounterDrawable(0, R.drawable.notification));
((RelativeLayout) findViewById(R.id.content_main)).removeAllViews();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
BlankFragment frag = new BlankFragment();
fragmentTransaction.add(R.id.content_main, frag, "first");
fragmentTransaction.commit();
}
return false;
}
});
check = 1;
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//code to reset view
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (fragmentManager.findFragmentByTag("first") != null) {
fragmentTransaction.remove(fragmentManager.findFragmentByTag("first"));
fragmentTransaction.commit();
loadooncreate();
} else {
finish();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
private Drawable buildCounterDrawable(int count, int backgroundImageId) {
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.counter_menuitem_layout, null);
view.setBackgroundResource(backgroundImageId);
if (count == 0) {
View counterTextPanel = view.findViewById(R.id.counterValuePanel);
counterTextPanel.setVisibility(View.GONE);
} else {
// TextView textView = (TextView) view.findViewById(count);
// textView.setText("1");
}
view.measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.setDrawingCacheEnabled(true);
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return new BitmapDrawable(getResources(), bitmap);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (check > 3) {
Toast.makeText(this.getApplicationContext(), "sdsdsdfdsfsd", Toast.LENGTH_SHORT).show();
MenuItem item = menu.getItem(R.id.notifications);
item.setIcon(buildCounterDrawable(2, R.drawable.notification));
}
//MenuItem item = (MenuItem)findViewById(R.id.notifications);
// item.setIcon(buildCounterDrawable(2, R.drawable.notification));
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.Home) {
//close current fragment;
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (fragmentManager.findFragmentByTag("first") != null)
fragmentTransaction.remove(fragmentManager.findFragmentByTag("first"));
fragmentTransaction.commit();
loadooncreate();
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
last stack error
W/MessageQueue: Handler (android.hardware.Camera$EventHandler) {428e2000} sending message to a Handler on a dead thread
java.lang.RuntimeException: Handler (android.hardware.Camera$EventHandler) {428e2000} sending message to a Handler on a dead thread
at android.os.MessageQueue.enqueueMessage(MessageQueue.java:294)
at android.os.Handler.sendMessageAtTime(Handler.java:473)
at android.os.Handler.sendMessageDelayed(Handler.java:446)
at android.os.Handler.sendMessage(Handler.java:383)
at android.hardware.Camera.postEventFromNative(Camera.java:852)
at dalvik.system.NativeStart.run(Native Method)
Can you try this, remove onAttach and onDetach. Also replace this code in onCreate
if (checkCameraHardware(getActivity().getApplicationContext())) {
Toast.makeText(this.getActivity(), "camera hardware is free", Toast.LENGTH_SHORT).show();
zXingScannerView = new ZXingScannerView(this.getActivity().getApplicationContext());
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera(0);
} else {
Toast.makeText(this.getActivity(), "camera hardware is NOT free", Toast.LENGTH_SHORT).show();
}
with this.
zXingScannerView = new ZXingScannerView(this.getActivity().getApplicationContext());
And change onPause and onResume like this.
#Override
public void onPause()
super.onPause(); {
if (zXingScannerView != null) {
zXingScannerView.stopCamera();
zXingScannerView.stopCameraPreview();
}
}
#Override
public void onResume() {
super.onResume();
if (checkCameraHardware(getActivity().getApplicationContext())) {
Toast.makeText(this.getActivity(), "camera hardware is free", Toast.LENGTH_SHORT).show();
zXingScannerView.setResultHandler(this); // Register ourselves as a
zXingScannerView.startCamera(0); // Start camera on resume
}
}
Also remove all these objects
private SurfaceView mySurfaceView;
private Camera mCamera;
private CameraPreview mPreview;
No need for them ,it's there in your zXingScannerView.
Actually you are not release objects when switch to other fragment first release all object in onPause() method and onResume() reconnect with camera. try this one :
#Override
public void onResume() {
super.onResume();
if (zXingScannerView!= null) {
zXingScannerView.stopCameraPreview();
zXingScannerView.resumeCameraPreview(this);
}
}

Changing to Landscape crashes my Android app

I am developing an app and want users to be able to use their phones horizontally or vertically, however, if I start in portrait and switch to landscape, the app crashes. It also crashes if I start landscape and switch to portrait.
Here is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<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-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme.NoActionBar"
android:screenOrientation="sensor">
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/facebook_app_id"/>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar"
android:configChanges="screenSize|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="net.sourceforge.zbar.android.CameraTest.CameraTestActivity" />
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
android:label="#string/app_name" />
</application>
I have already tried this this, but then the app cannot go to landscape as described here.
Here is the activity that it crashed in (MainActivity):
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, UserDelegate {
private static final int SCAN_COUPONS = 1;
public GoogleApiClient googleApiClient;
private Location lastLocation;
EditText zip;
public static User user;
public SharedPreferences sharedPreferences;
public static SQLiteDatabase database;
#Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nav_bar_container);
/*
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
actionBar.setCustomView(R.layout.actionbar);
}
*/
sharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
database = openOrCreateDatabase("CouponWallet", MODE_PRIVATE, null);
/*Typeface iconFont = FontManager.getTypeface(getApplicationContext(), FontManager.FONTAWESOME);
FontManager.markAsIconContainer(findViewById(R.id.content_main), iconFont);
FontManager.markAsIconContainer(findViewById(R.id.drawer_layout), iconFont);
//FontManager.markAsIconContainer(findViewById(R.id.nav_drawer), iconFont);
FontManager.markAsIconContainer(findViewById(R.id.top_toolbar), iconFont);
FontManager.markAsIconContainer(findViewById(R.id.bottom_toolbar), iconFont);*/
FontIconTypefaceHolder.init(getAssets(), "fonts/FontAwesome.ttf"); //allows for icons
// set up toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.top_toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("Coupon Wallet");
toolbar.hideOverflowMenu();
FontManager.setFont(findViewById(R.id.top_toolbar), FontManager.getTypeface(this, FontManager.CANDY));
googleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
Log.v("onCreate", "api client created");
//set up drawer
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
new Thread(new Runnable() {
#Override
public void run() { // does ouside of ui thread
setIcons();
}
}).start();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
/*if(sharedPreferences.getInt("user_id", 0) == 0){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, new LoginFragment());
ft.addToBackStack(null);
ft.commit();
getSupportActionBar().setTitle("Login");
}*/
//user = new User(sharedPreferences.getInt("user_id", 1), database);
//if (Functions.isOnline()) {
Log.v("onCreate", "creating user " + sharedPreferences.getInt("user_id", 1));
this.user = new User(1, this);
//}
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
FragmentManager fm = getFragmentManager();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
} 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);
LayerDrawable layerDrawable = (LayerDrawable) menu.findItem(R.id.action_barcode).getIcon();
layerDrawable.setDrawableByLayerId(R.id.main_icon, Functions.getFAIcons(this).get("barcode"));
Functions.setBadgeCount(this, layerDrawable, 2, R.id.num_circle);
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();
if (id == R.id.action_barcode) {
final AlertDialog dialog = new AlertDialog.Builder(this).setView(R.layout.redeem_code_layout).create();
dialog.show();
Toolbar toolbar = (Toolbar) dialog.findViewById(R.id.redeem_toolbar);
toolbar.inflateMenu(R.menu.redeem_menu);
toolbar.setTitle("Redeem Codes");
toolbar.setNavigationIcon(Functions.getFAIcons(this).get("times"));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
toolbar.inflateMenu(R.menu.redeem_menu);
toolbar.hideOverflowMenu();
toolbar.setTitleTextColor(getResources().getColor(R.color.colorBlack));
FontManager.setFont(toolbar, FontManager.getTypeface(this, FontManager.CHAMPAGNE));
MenuItem help = toolbar.getMenu().add("Help");
help.setIcon(Functions.getFAIcons(this).get("question"));
help.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Toast.makeText(getApplicationContext(), "Help Clicked", Toast.LENGTH_LONG).show();
return false;
}
});
final ImageView code = (ImageView) dialog.findViewById(R.id.redeem_code);
code.setImageDrawable(user.barcode);
Spinner spinner = (Spinner) dialog.findViewById(R.id.redeem_scan_type);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_item, new String[]{"Barcode", "QR Code", "PDF417", "Aztec"});
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (i) {
case 0:
code.setImageDrawable(user.barcode);
break;
case 1:
code.setImageDrawable(user.qr_code);
break;
case 2:
code.setImageDrawable(user.pdf417);
break;
case 3:
code.setImageDrawable(user.aztec);
break;
}
/*for(int j = 0; j < 4; j++){
if (i != j) {
TextView item = ((TextView) adapterView.getChildAt(j));
item.setBackgroundColor(getResources().getColor(R.color.colorWhite));
item.setTextColor(getResources().getColor(R.color.colorGray));
} else {
TextView item = ((TextView) adapterView.getChildAt(j));
item.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
item.setTextColor(getResources().getColor(R.color.colorWhite));
}
}*/
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
code.setImageDrawable(user.barcode);
}
});
TextView textView = (TextView) dialog.findViewById(R.id.redeem_num);
long uid = user.id;
textView.setText(String.format(Locale.US, "%s%011d", "891", uid));
}
return super.onOptionsItemSelected(item);
}
/**
* #param item item selected in nav menu
* #return if view switch was successful
*/
//#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
String title = "";
Toolbar toolbar = (Toolbar) findViewById(R.id.bottom_toolbar);
toolbar.getMenu().clear();
switch (id) { //based on which section was selected
case R.id.nav_search:
title = "Search";
fragment = new SearchFragment();
toolbar.setVisibility(View.VISIBLE);
toolbar.setNavigationIcon(Functions.getFAIcons(getApplicationContext()).get("gear"));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("bottom_toolbar", "horizontal clicked");
}
});
toolbar.inflateMenu(R.menu.my_wallet);
MenuItem map1 = toolbar.getMenu().getItem(0); //only item in the menu
map1.setIcon(Functions.getFAIcons(getApplicationContext()).get("map"));
map1.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Log.v("bottom_toolbar", "map clicked");
return true;
}
});
break;
case R.id.nav_profile:
title = "Profile";
break;
case R.id.nav_notifications:
title = "Notifications";
break;
case R.id.nav_categories:
try {
lastLocation = getLastKnownLocation();
if (lastLocation != null) {
Log.v("categories", "Location accessed");
Bundle bundle2 = new Bundle();
bundle2.putDouble("lat", lastLocation.getLatitude());
bundle2.putDouble("lon", lastLocation.getLongitude());
bundle2.putString("type", "loc");
fragment = new CategoriesFragment();
fragment.setArguments(bundle2);
title = "Categories";
toolbar.setVisibility(View.VISIBLE);
toolbar.setNavigationIcon(Functions.getFAIcons(getApplicationContext()).get("gear"));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("bottom_toolbar", "horizontal clicked");
}
});
toolbar.inflateMenu(R.menu.categories);
break;
}
} catch (SecurityException e) { // if can't get location go straight to search
}
Log.v("categories", "Location not accessable");
Toast.makeText(this, "Turn on location services get faster results", Toast.LENGTH_LONG).show();
AlertDialog dialog2 = new AlertDialog.Builder(this).setView(R.layout.get_zip_dialog).setPositiveButton("Set", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
}).create();
dialog2.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialogInterface) {
dialogInterface.dismiss();
Toast.makeText(getApplicationContext(), "Cannot get local categories without location", Toast.LENGTH_LONG).show();
}
});
zip = (EditText) findViewById(R.id.zip_code);
dialog2.show();
break;
case R.id.nav_wallet:
fragment = new MyWalletFragment(); //sets up view
// setting up toolbars
title = "My Wallet";
toolbar.setVisibility(View.VISIBLE);
toolbar.setNavigationIcon(Functions.getFAIcons(getApplicationContext()).get("columns"));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("bottom_toolbar", "horizontal clicked");
}
});
toolbar.inflateMenu(R.menu.my_wallet);
MenuItem map = toolbar.getMenu().getItem(0); //only item in the menu
map.setIcon(Functions.getFAIcons(getApplicationContext()).get("map"));
map.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Log.v("bottom_toolbar", "map clicked");
return true;
}
});
//toolbar.setLogo(R.id.horizontal);
break;
case R.id.nav_scan:
title = "Scan Coupons";
Intent intent = new Intent(this, CameraTestActivity.class);
startActivityForResult(intent, SCAN_COUPONS);
break;
case R.id.nav_map:
title = "Map";
break;
case R.id.nav_settings:
fragment = new SettingFragment(); //sets up view
title = "Settings";
break;
case R.id.nav_help:
title = "Help";
// Assuming the Help in the nav bar is the same as the settings menu
fragment = new HelpSettingsFragment();
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.commit();
}
FontManager.setFont(findViewById(R.id.content_frame), FontManager.getTypeface(this, FontManager.CHAMPAGNE));
//noinspection ConstantConditions
getSupportActionBar().setTitle(title);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onLocationChanged(Location location) {
Log.v("onLocationChanged", "Location changed");
lastLocation = location;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.v("onConnected", "connected");
try {
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
} catch (SecurityException e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
/**
* Process a coupon scan
*
* #param requestCode Type of activity
* #param resultCode if result ok
* #param data the returned data
*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_CANCELED) {
Log.e("onActivityResult", "result canceled");
} else if (resultCode == RESULT_OK) {
if (requestCode == SCAN_COUPONS) {
String result = data.getStringExtra("result");
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
Log.v("onActivityResult", result);
}
}
}
/**
* Set the icons in the drawer
*/
private void setIcons() {
Map<String, Drawable> map = Functions.getFAIcons(getApplicationContext());
int[] sections = {R.id.nav_search, R.id.nav_profile, R.id.nav_notifications, R.id.nav_categories, R.id.nav_wallet,
R.id.nav_scan, R.id.nav_map, R.id.nav_settings, R.id.nav_help};
Drawable[] icons = {map.get("search"), map.get("user"), map.get("bookmark"), map.get("list"), map.get("barcode"),
map.get("camera"), map.get("map_o"), map.get("gear"), map.get("question")};
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
Menu m = navigationView.getMenu();
for (int i = 0; i < sections.length; i++) {
MenuItem item = m.findItem(sections[i]);
item.setIcon(icons[i]);
}
}
/**
* Gets the last known Location
*
* #return The last known location
* #throws SecurityException if proper permissions not given
*/
private Location getLastKnownLocation() throws SecurityException {
LocationManager mLocationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
Log.v("getLastKnownLocation", "looping through providers");
for (String provider : providers) {
Log.v("getLastKnownLocation", provider);
Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
public void settingOnClick(View v) {
/*
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo_shortcut)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, MainActivity.class);
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
// Sets an ID for the notification
int mNotificationId = 001;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mBuilder.setAutoCancel(true);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
*/
Fragment fragment = null;
switch (v.getId()) {
case R.id.setting_account:
case R.id.setting_userIcon:
fragment = new AccountSettingsFragment();
break;
case R.id.setting_location:
case R.id.setting_locationArrow:
fragment = new LocationSettingsFragment();
break;
case R.id.setting_notifications:
case R.id.setting_notificationIcon:
fragment = new NotificationSettingsFragment();
break;
case R.id.setting_help:
case R.id.setting_helpIcon:
fragment = new HelpSettingsFragment();
break;
case R.id.setting_contact:
case R.id.setting_contactIcon:
fragment = new ContactUsSettingsFragment();
break;
case R.id.setting_privacy:
case R.id.setting_privacyIcon:
fragment = new PrivacyPolicySettingsFragment();
break;
case R.id.setting_about:
case R.id.setting_aboutIcon:
fragment = new AboutSettingsFragment();
break;
case R.id.tutorial_loc_enterAnotherLocation:
fragment = new EnterAnotherLocation();
break;
case R.id.tutorial_1_saving:
case R.id.tutorial_2_saving:
case R.id.tutorial_3_saving:
fragment = new FirstTimeLocation();
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.commit();
}
}
#Override
public void userFinished(User user) {
this.user = user;
Log.v("UserFinished", user.toString());
}
}
And the error that i get is here. It is a link to a .txt file as it brings the question over the character limit.
Hii for working in landscape and portrait mode, you have to use saved instance and restore saved instance or else your application values
googleApiClient,lastLocation,zip,user values may have null value and causes this issue
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
savedInstanceState.putParcelable("parcelable", "");
savedInstanceState.putSerializable("serializable", "");
}
The Bundle is essentially a way of storing a NVP ("Name-Value Pair") map, and it will get passed in to onCreate() and also onRestoreInstanceState() where you'd extract the values like this:
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}

Calling function from a Fragment ..No activity to handle error

I saw many question related to this one but none solved my problem yet so I apologize if it was duplicated.
I'm creating a contact book. I've created a fragment to display all contacts.
Now what I want to do is to created an imageview (Call Button) to enable calling the contact when clicked.
I keep getting the error (No Activity found to handle Intent { act android.intent.action.CALL }and when I run on my device it crashed although I've added the intent to the manifest.
What am I doing wrong ?
Fragment Class:
public class DetailFragment extends Fragment
implements LoaderManager.LoaderCallbacks<Cursor> {
public interface DetailFragmentListener {
void onContactDeleted();
void onEditContact(Uri contactUri);
}
private static final int CONTACT_LOADER = 0;
private DetailFragmentListener listener; // MainActivity
private Uri contactUri;
private TextView nameTextView;
private TextView phoneTextView;
private TextView emailTextView;
private TextView streetTextView;
private TextView cityTextView;
private TextView stateTextView;
private TextView zipTextView;
private ImageButton callButton; //The image View for the calling
#Override
public void onAttach(Context context) {
super.onAttach(context);
listener = (DetailFragmentListener) context;
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
// called when DetailFragmentListener's view needs to be created
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
setHasOptionsMenu(true); // this fragment has menu items to display
// get Bundle of arguments then extract the contact's Uri
Bundle arguments = getArguments();
if (arguments != null)
contactUri = arguments.getParcelable(MainActivity.CONTACT_URI);
// inflate DetailFragment's layout
View view =
inflater.inflate(R.layout.fragment_detail, container, false);
// get the EditTexts
nameTextView = (TextView) view.findViewById(R.id.nameTextView);
phoneTextView = (TextView) view.findViewById(R.id.phoneTextView);
emailTextView = (TextView) view.findViewById(R.id.emailTextView);
streetTextView = (TextView) view.findViewById(R.id.streetTextView);
cityTextView = (TextView) view.findViewById(R.id.cityTextView);
stateTextView = (TextView) view.findViewById(R.id.stateTextView);
zipTextView = (TextView) view.findViewById(R.id.zipTextView);
callButton = (ImageButton) view.findViewById(R.id.callButton);/Get the image view
// load the contact
getLoaderManager().initLoader(CONTACT_LOADER, null, this);
addListenerOnButton(view);//Call the Listener
return view;
}
// display this fragment's menu items
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_details_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:
listener.onEditContact(contactUri);
return true;
case R.id.action_delete:
deleteContact();
return true;
}
return super.onOptionsItemSelected(item);
}
private void deleteContact() {
confirmDelete.show(getFragmentManager(), "confirm delete");
}
private final DialogFragment confirmDelete =
new DialogFragment() {
#Override
public Dialog onCreateDialog(Bundle bundle) {
AlertDialog.Builder builder =
new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.confirm_title);
builder.setMessage(R.string.confirm_message);
// provide an OK button that simply dismisses the dialog
builder.setPositiveButton(R.string.button_delete,
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog, int button) {
getActivity().getContentResolver().delete(
contactUri, null, null);
listener.onContactDeleted(); // notify listener
}
}
);
builder.setNegativeButton(R.string.button_cancel, null);
return builder.create(); // return the AlertDialog
}
};
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader cursorLoader;
switch (id) {
case CONTACT_LOADER:
cursorLoader = new CursorLoader(getActivity(),
contactUri,
null,
null,
null,
null);
break;
default:
cursorLoader = null;
break;
}
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data != null && data.moveToFirst()) {
// get the column index for each data item
int nameIndex = data.getColumnIndex(Contact.COLUMN_NAME);
int phoneIndex = data.getColumnIndex(Contact.COLUMN_PHONE);
int emailIndex = data.getColumnIndex(Contact.COLUMN_EMAIL);
int streetIndex = data.getColumnIndex(Contact.COLUMN_STREET);
int cityIndex = data.getColumnIndex(Contact.COLUMN_CITY);
int stateIndex = data.getColumnIndex(Contact.COLUMN_STATE);
int zipIndex = data.getColumnIndex(Contact.COLUMN_ZIP);
// fill TextViews with the retrieved data
nameTextView.setText(data.getString(nameIndex));
phoneTextView.setText(data.getString(phoneIndex));
emailTextView.setText(data.getString(emailIndex));
streetTextView.setText(data.getString(streetIndex));
cityTextView.setText(data.getString(cityIndex));
stateTextView.setText(data.getString(stateIndex));
zipTextView.setText(data.getString(zipIndex));
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
/////Add listener to the image view
public void addListenerOnButton(View v) {
callButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String phone_number = phoneTextView.getText().toString();//nUHA
Intent callIntent =new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse(phone_number));
startActivity(callIntent);
}
});
}
}
This is specifically the part of the on click method
#Override
public void onClick(View arg0) {
String phone_number = phoneTextView.getText().toString();//nUHA
Intent callIntent =new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse(phone_number));
startActivity(callIntent);
My main
public class MainActivity extends AppCompatActivity
implements ContactsFragment.ContactsFragmentListener,
DetailFragment.DetailFragmentListener,
AddEditFragment.AddEditFragmentListener {
public static final String CONTACT_URI = "contact_uri";
private ContactsFragment contactsFragment; // displays contact list
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (savedInstanceState == null &&
findViewById(R.id.fragmentContainer) != null) {
// create ContactsFragment
contactsFragment = new ContactsFragment();
// add the fragment to the FrameLayout
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragmentContainer, contactsFragment);
transaction.commit(); // display ContactsFragment
}
else {
contactsFragment =
(ContactsFragment) getSupportFragmentManager().
findFragmentById(R.id.contactsFragment);
}
}
#Override
public void onContactSelected(Uri contactUri) {
if (findViewById(R.id.fragmentContainer) != null) // phone
displayContact(contactUri, R.id.fragmentContainer);
else { // tablet
getSupportFragmentManager().popBackStack();
displayContact(contactUri, R.id.rightPaneContainer);
}
}
#Override
public void onAddContact() {
if (findViewById(R.id.fragmentContainer) != null) // phone
displayAddEditFragment(R.id.fragmentContainer, null);
else // tablet
displayAddEditFragment(R.id.rightPaneContainer, null);
}
private void displayContact(Uri contactUri, int viewID) {
DetailFragment detailFragment = new DetailFragment();
Bundle arguments = new Bundle();
arguments.putParcelable(CONTACT_URI, contactUri);
detailFragment.setArguments(arguments);
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.replace(viewID, detailFragment);
transaction.addToBackStack(null);
transaction.commit(); // causes DetailFragment to display
}
private void displayAddEditFragment(int viewID, Uri contactUri) {
AddEditFragment addEditFragment = new AddEditFragment();
if (contactUri != null) {
Bundle arguments = new Bundle();
arguments.putParcelable(CONTACT_URI, contactUri);
addEditFragment.setArguments(arguments);
}
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.replace(viewID, addEditFragment);
transaction.addToBackStack(null);
transaction.commit(); // causes AddEditFragment to display
}
#Override
public void onContactDeleted() {
// removes top of back stack
getSupportFragmentManager().popBackStack();
contactsFragment.updateContactList(); // refresh contacts
}
// display the AddEditFragment to edit an existing contact
#Override
public void onEditContact(Uri contactUri) {
if (findViewById(R.id.fragmentContainer) != null) // phone
displayAddEditFragment(R.id.fragmentContainer, contactUri);
else // tablet
displayAddEditFragment(R.id.rightPaneContainer, contactUri);
}
// update GUI after new contact or updated contact saved
#Override
public void onAddEditCompleted(Uri contactUri) {
// removes top of back stack
getSupportFragmentManager().popBackStack();
contactsFragment.updateContactList(); // refresh contacts
if (findViewById(R.id.fragmentContainer) == null) { // tablet
// removes top of back stack
getSupportFragmentManager().popBackStack();
// on tablet, display contact that was just added or edited
displayContact(contactUri, R.id.rightPaneContainer);
}
}
}
My Manifest
<uses-permission android:name="android.permission.CALL_PHONE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.CALL"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<provider
android:name=".data.AddressBookContentProvider"
android:authorities="com.deitel.addressbook.data"
android:enabled="true"
android:exported="false" >
</provider>
</application>
</manifest>
Use
Uri.parse("tel:" + phone_number)
instead of
Uri.parse(phone_number)

Notification does not open the fragment?

I created a Notification and I want it to open a Fragment when clicked. It works in general, but when I have another Fragment open in my application at the time, it does not work.
For example, I have two Fragments: NoticiaFrag and EventoFrag. If I open my application and open the NoticiaFrag after pressing the home button of the device to minimize the application and receiving a notification to EventoFrag, when I click the notification opens NoticiaFrag and not EventoFrag.
To make this work I need close the application with the back button. After the application closes it works fine. I think I need to reopen the application when I click the Notification, but I don't know how.
The method that opens the Fragments from the Notification is in CustomDrawerLayout and called openFrag().
How can I solve this issue?
Notification
public class SendNotification {
public SendNotification(Context context, String title, String tickerText, String message, String url) {
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent;
Intent intent = new Intent(context, CustomDrawerLayout.class);
Bundle bd = new Bundle();
bd.putString("url", url);
intent.putExtras(bd);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.logo)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setTicker(tickerText)
.setContentTitle(title)
.setShowWhen(true)
.setWhen(System.currentTimeMillis())
.setContentText(message);
mBuilder.setContentIntent(contentIntent);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.vibrate = new long[]{150, 300, 150, 600};
mNotificationManager.notify(AndroidSystemUtil.randInt(), notification);
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="br.com.ferpapps.santaluzapp" >
<!--Internet -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--GCM Permissions -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name=".permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name=".permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.VIBRATE"></uses-permission>
<!---->
<!-- permissoes extra -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:name=".cv.CustomVolleySingleton"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
>
<!-- GCM -->
<receiver
android:name=".push.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="br.com.ferpapps" />
</intent-filter>
</receiver>
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<service
android:name=".push.GcmIntentService" >
</service>
<!-- close GCM -->
<activity
android:name=".act.SplashView"
android:label="#string/app_name"
android:windowSoftInputMode="adjustPan|adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".menu.CustomDrawerLayout"/>
<activity android:name=".act.AreaAlunoMainActivity" />
</application>
</manifest>
ActionBarActivity
public class CustomDrawerLayout extends ActionBarActivity implements OnItemClickListener{
private ActionBar ab;
private DrawerLayout dl;
private ListView lv;
private ActionBarDrawerToggle tg;
private LinearLayout navdrawer;
private List<ItensListView> fragments;
private CharSequence tl; //titulo principal
private CharSequence tlf; //titulo fragment
public static final String APP_NAME = "App";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_drawerlayout);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.action_bar)));
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.actionbar_custom);
init();
openFrag();
}
private void openFrag(){
//verifica notificacao e abre o fragment correspondente
String url = getIntent().getStringExtra("url") != null ? getIntent().getStringExtra("url") : null;
Log.i("URL_NOTIFICACAO->", url != null ? url : "");
if(url != null) {
//Open By Notification
if (url.equals("Noticias")) {
selectedItem(0);
} else if (url.equals("Eventos")) {
selectedItem(1);
} else if (url.equals("Tarefas") ||
url.equals("Advertencias") ||
url.equals("Agendas")) {
Log.i("Notificacao", url);
Log.i("LOGADO NA SESSION", SessionUsuario.isLogged(this) + "");
if(SessionUsuario.isLogged(this)){
Log.i("Notificao Logado", "esta logado na area do aluno");
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment frag = AreaAlunoFrag.newInstance();
frag.getArguments().putString("url", url);
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
}
}
}else{
Log.i("ENTREI FIRST FRAG->","ENTREEIII");
//if(savedInstanceState == null){
selectedItem(0);
//}
}
}
private void init(){
//actionbar
onConfigActionBar();
//listview
configItensListView();
//drawerlayout
dl = (DrawerLayout)findViewById(R.id.dl);
navdrawer = (LinearLayout)findViewById(R.id.navdrawer);
//listview
lv = (ListView)findViewById(R.id.lv);
lv.setAdapter(new DrawerLayoutListViewAdapter(this, fragments));
lv.setOnItemClickListener(this);
//drawerlayout
//dl = (DrawerLayout)findViewById(R.id.dl);
//mDrawerRelativeLayout = (RelativeLayout)findViewById(R.id.left_drawer);
//actionbardrawertoggle
tg = new ActionBarDrawerToggle(this, dl, R.drawable.ic_launcher, R.string.drawer_open){
public void onDrawerClosed(View view) {
ab.setTitle(tl);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View view) {
ab.setTitle(tlf);
supportInvalidateOptionsMenu();
}
};
dl.setDrawerListener(tg);
tl = tlf = getTitle();
}
/** ativa actionbar e botao home na action bar */
private void onConfigActionBar(){
ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
ab.setHomeButtonEnabled(true);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
tg.onConfigurationChanged(newConfig);
}
/** necessario */
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
tg.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (tg.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/** necessario */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.custom_drawer_layout, menu);
return true;
}
/** necessario */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean status = dl.isDrawerOpen(navdrawer);
//menu.findItem(R.id.action_settings).setVisible(!status);
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Log.i("POSITION->", position + "");
selectedItem(position);
}
/** seleciona o fragment q sera usado */
private void selectedItem(int position){
FragmentTransaction ft;
Fragment frag;
switch (position){
case 0:
ft = getSupportFragmentManager().beginTransaction();
frag = NoticiaFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 1:
ft = getSupportFragmentManager().beginTransaction();
frag = EventoFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 2:
ft = getSupportFragmentManager().beginTransaction();
frag = LoginFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 3:
ft = getSupportFragmentManager().beginTransaction();
frag = ContatoFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 4:
ft = getSupportFragmentManager().beginTransaction();
frag = CompartilhaFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 5:
ft = getSupportFragmentManager().beginTransaction();
frag = SobreFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
default:
closeApp();
break;
}
lv.setItemChecked(position, true);
setCustomTitle(fragments.get(position).getTexto());
dl.closeDrawer(navdrawer);
}
/** define o titulo da actionbar */
private void setCustomTitle(String title){
//SpannableString s = new SpannableString(title);
// s.setSpan(new TypefaceSpan(this, BatalhaConfigs.FONT), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//ab.setTitle(s);
//tl = s;
}
#Override
public void onBackPressed() {
//if(getSupportFragmentManager().getBackStackEntryCount() > 0){
// getSupportFragmentManager().popBackStackImmediate();
// }else{
super.onBackPressed();
//}
}
#Override
protected void onResumeFragments() {
super.onResumeFragments();
}
/** Configura o List com as informacoes **/
private void configItensListView(){
fragments = new ArrayList<ItensListView>();
//define
ItensListView itens0 = new ItensListView("Noticias", R.drawable.setavermelha);
ItensListView itens1 = new ItensListView("Eventos", R.drawable.setavermelha);
ItensListView itens2 = new ItensListView("Área do Aluno", R.drawable.setavermelha);
ItensListView itens3 = new ItensListView("Contato", R.drawable.setavermelha);
ItensListView itens4 = new ItensListView("Redes Sociais", R.drawable.setavermelha);
ItensListView itens5 = new ItensListView("Sobre", R.drawable.setavermelha);
ItensListView itens6 = new ItensListView("Sair", R.drawable.setavermelha);
//add
fragments.add(itens0);
fragments.add(itens1);
fragments.add(itens2);
fragments.add(itens3);
fragments.add(itens4);
fragments.add(itens5);
fragments.add(itens6);
//AreaAlunoFrag
}
private void closeApp(){
System.exit(0);
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
//super.onSaveInstanceState(outState, outPersistentState);
getSupportFragmentManager().beginTransaction().commitAllowingStateLoss();
}
private void removeAllFrags(){
FragmentManager fm = getSupportFragmentManager();
for(int x = 0; x < fm.getBackStackEntryCount(); x++){
//getSupportFragmentManager().beginTransaction().remove(fm.findFragmentById(x)).commit();
fm.popBackStackImmediate();
}
}
#Override
protected void onStart() {
new SendProjectId(getApplicationContext());
super.onStart();
}
#Override
protected void onResume() {
PushControl.setIsVisible(true);
new SendProjectId(getApplicationContext());
super.onResume();
}
#Override
protected void onPause() {
PushControl.setIsVisible(false);
super.onPause();
}
#Override
protected void onStop() {
PushControl.setIsVisible(false);
//removeAllFrags();
super.onStop();
}
#Override
protected void onDestroy() {
PushControl.setIsVisible(false);
super.onDestroy();
CustomVolleySingleton.getInstance().cancelPendingRequests(CustomVolleySingleton.TAG);
}
}
Update CustomDrawerLayout and Manifest - It works fine.
CustomDrawerLayout
public class CustomDrawerLayout extends ActionBarActivity implements OnItemClickListener{
private ActionBar ab;
private DrawerLayout dl;
private ListView lv;
private ActionBarDrawerToggle tg;
private LinearLayout navdrawer;
private List<ItensListView> fragments;
private CharSequence tl; //titulo principal
private CharSequence tlf; //titulo fragment
public static final String APP_NAME = "App";
private static String URL_NOTIFICATION = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_drawerlayout);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.action_bar)));
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.actionbar_custom);
init();
if(savedInstanceState == null){
selectedItem(0);
}
}
/** open fragment by notification */
private void openFragByNotification(){
if(!URL_NOTIFICATION.isEmpty()) {
//Open By Notification
if (URL_NOTIFICATION.equals("Noticias")) {
selectedItem(0);
} else if (URL_NOTIFICATION.equals("Eventos")) {
selectedItem(1);
} else if (URL_NOTIFICATION.equals("Tarefas") ||
URL_NOTIFICATION.equals("Advertencias") ||
URL_NOTIFICATION.equals("Agendas")) {
Log.i("Notificacao", URL_NOTIFICATION);
Log.i("LOGADO NA SESSION", SessionUsuario.isLogged(this) + "");
if(SessionUsuario.isLogged(this)){
Log.i("Notificao Logado", "esta logado na area do aluno");
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment frag = AreaAlunoFrag.newInstance();
frag.getArguments().putString("url", URL_NOTIFICATION);
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
}
}
}
}
private void init(){
//actionbar
onConfigActionBar();
//listview
configItensListView();
//drawerlayout
dl = (DrawerLayout)findViewById(R.id.dl);
navdrawer = (LinearLayout)findViewById(R.id.navdrawer);
//listview
lv = (ListView)findViewById(R.id.lv);
lv.setAdapter(new DrawerLayoutListViewAdapter(this, fragments));
lv.setOnItemClickListener(this);
//drawerlayout
//dl = (DrawerLayout)findViewById(R.id.dl);
//mDrawerRelativeLayout = (RelativeLayout)findViewById(R.id.left_drawer);
//actionbardrawertoggle
tg = new ActionBarDrawerToggle(this, dl, R.drawable.ic_launcher, R.string.drawer_open){
public void onDrawerClosed(View view) {
ab.setTitle(tl);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View view) {
ab.setTitle(tlf);
supportInvalidateOptionsMenu();
}
};
dl.setDrawerListener(tg);
tl = tlf = getTitle();
}
/** ativa actionbar e botao home na action bar */
private void onConfigActionBar(){
ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
ab.setHomeButtonEnabled(true);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
tg.onConfigurationChanged(newConfig);
}
/** necessario */
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
tg.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (tg.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/** necessario */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.custom_drawer_layout, menu);
return true;
}
/** necessario */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean status = dl.isDrawerOpen(navdrawer);
//menu.findItem(R.id.action_settings).setVisible(!status);
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Log.i("POSITION->", position + "");
selectedItem(position);
}
/** seleciona o fragment q sera usado */
private void selectedItem(int position){
FragmentTransaction ft;
Fragment frag;
switch (position){
case 0:
ft = getSupportFragmentManager().beginTransaction();
frag = NoticiaFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 1:
ft = getSupportFragmentManager().beginTransaction();
frag = EventoFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 2:
ft = getSupportFragmentManager().beginTransaction();
frag = LoginFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 3:
ft = getSupportFragmentManager().beginTransaction();
frag = ContatoFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 4:
ft = getSupportFragmentManager().beginTransaction();
frag = CompartilhaFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 5:
ft = getSupportFragmentManager().beginTransaction();
frag = SobreFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
default:
closeApp();
break;
}
lv.setItemChecked(position, true);
setCustomTitle(fragments.get(position).getTexto());
dl.closeDrawer(navdrawer);
}
/** define o titulo da actionbar */
private void setCustomTitle(String title){
//SpannableString s = new SpannableString(title);
// s.setSpan(new TypefaceSpan(this, BatalhaConfigs.FONT), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//ab.setTitle(s);
//tl = s;
}
#Override
public void onBackPressed() {
//if(getSupportFragmentManager().getBackStackEntryCount() > 0){
// getSupportFragmentManager().popBackStackImmediate();
// }else{
super.onBackPressed();
//}
}
#Override
protected void onResumeFragments() {
super.onResumeFragments();
}
/** Configura o List com as informacoes **/
private void configItensListView(){
fragments = new ArrayList<ItensListView>();
//define
ItensListView itens0 = new ItensListView("Noticias", R.drawable.setavermelha);
ItensListView itens1 = new ItensListView("Eventos", R.drawable.setavermelha);
ItensListView itens2 = new ItensListView("Área do Aluno", R.drawable.setavermelha);
ItensListView itens3 = new ItensListView("Contato", R.drawable.setavermelha);
ItensListView itens4 = new ItensListView("Redes Sociais", R.drawable.setavermelha);
ItensListView itens5 = new ItensListView("Sobre", R.drawable.setavermelha);
ItensListView itens6 = new ItensListView("Sair", R.drawable.setavermelha);
//add
fragments.add(itens0);
fragments.add(itens1);
fragments.add(itens2);
fragments.add(itens3);
fragments.add(itens4);
fragments.add(itens5);
fragments.add(itens6);
//AreaAlunoFrag
}
private void closeApp(){
System.exit(0);
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
//super.onSaveInstanceState(outState, outPersistentState);
getSupportFragmentManager().beginTransaction().commitAllowingStateLoss();
}
private void removeAllFrags(){
FragmentManager fm = getSupportFragmentManager();
for(int x = 0; x < fm.getBackStackEntryCount(); x++){
//getSupportFragmentManager().beginTransaction().remove(fm.findFragmentById(x)).commit();
fm.popBackStackImmediate();
}
}
#Override
protected void onNewIntent(Intent intent) {
URL_NOTIFICATION = intent.getStringExtra("url");
Log.i("URL_NOTIFICATION", URL_NOTIFICATION);
super.onNewIntent(intent);
}
#Override
protected void onStart() {
new SendProjectId(getApplicationContext());
super.onStart();
}
#Override
protected void onResume() {
PushControl.setIsVisible(true);
new SendProjectId(getApplicationContext());
openFragByNotification();
super.onResume();
}
#Override
protected void onPause() {
PushControl.setIsVisible(false);
URL_NOTIFICATION = "";
super.onPause();
}
#Override
protected void onStop() {
PushControl.setIsVisible(false);
URL_NOTIFICATION = "";
super.onStop();
}
#Override
protected void onDestroy() {
PushControl.setIsVisible(false);
super.onDestroy();
CustomVolleySingleton.getInstance().cancelPendingRequests(CustomVolleySingleton.TAG);
}
}
Manifest
<activity android:name=".menu.CustomDrawerLayout" android:launchMode="singleTop"/>
The problem is that Android by default doesn't deliver a new Intent to an Activity that is already running. If you close your app via the back button, the Activity is destroyed and the next time startActivity() is called a new instance is created and the new Intent delivered. If you leave the Activity via the home button, the Activity is not destroyed. When you call startActivity() in this case, the already running instance of the Activity is brought to the foreground, but a new Intent is not delivered.
To change this behaviour you can define your activity in the manifest with launchMode="singleTop":
<activity
...
android:launchMode="singleTop"
...
>
</activity>
In this case Android will deliver a new Intent via onNewIntent(), which you can override:
This is called for activities that set launchMode to "singleTop" in their package, or if a client used the FLAG_ACTIVITY_SINGLE_TOP flag when calling startActivity(Intent). In either case, when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.
Just noticed the flags you're passing into your Intent. In that case you probably just have to override onNewIntent() in your Activity.
I've run into this problem myself before and asked a question here. There's some more background in that question, the accepted answer, and the comments.

Categories

Resources