no permissions allowed auto android studio - android

I am trying to get weather information using gps location, but the problem is getting value for my location 0,0 ("latitude , longitude"). When I go to setting for my phone -> " permission " found no permissions allowed, and I have to activate the permission manually. Then app start working fine .
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ionicframework.myapp574503">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature android:name="android.hardware.location.gps"/>
<uses-permission android:name="android.permission.INTERNET" />
<application android:name="android.support.multidex.MultiDexApplication"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
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>
</activity>
</application>
</manifest>
MainActivity
package com.ionicframework.myapp574503;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
RequestQueue rq;
TextView timeDesc, windspeedDesc;
String wind;
GPSTracker gps;
LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
windspeedDesc = (TextView) findViewById(R.id.textView1);
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);
// create class object
gps = new GPSTracker(MainActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
String url = "http://api.wunderground.com/api/xxxxxxxxxxx/conditions/hourly/forecast10day/geolookup/q/"+latitude+","+longitude+".json";
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
rq = Volley.newRequestQueue(this);
sendjsonrequest(url);
// \n is for new line
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
public void sendjsonrequest(String url) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onResponse(JSONObject response) {
try {
JSONObject stationsJO = response.getJSONObject("location");
JSONArray array = stationsJO.optJSONArray("days");
wind= stationsJO.getString("city");
windspeedDesc.setText(wind);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
rq.add(jsonObjectRequest);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// 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
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
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;
}
}
I tested on version 4.4.2 and it worked fine and permission auto allowed but on version 7.0 I have to activate permission manually from setting
any ideas ?

Try this code for Runtime Permission in Android Version 6.0 or above
private int PERMISSIONS_REQUEST_LOCATION = 100;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(MainFragmentActivity.this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainFragmentActivity.this,ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(MainFragmentActivity.this, new String[]{ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_LOCATION);
}
}
}
}

You need to request the runtime permission.
You do that using ActivityCompat.requestPermissions
There is a tutorial on doing this here

Related

Can't display my activity from navigation drawer

I have a navigation drawer with some options (Home, Bluetooth, Alarm, Tips). I linked an activity to Bluetooth and Alarm but I got some problems with Home.
When I run the application I have a splash screen which is connected to the Home.java, in this activity I can click on my drawer and select the others alarm.java anche bluetooth.java but, when I link an activity to home, using the same method, my app stops working.
Thank you so much!
This is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.progetto.app">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<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:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".SplashScreen"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Home"
android:label="#string/Home"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Alarm"
android:label="#string/title_activity_alarm"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Bluetooth"
android:label="#string/title_activity_bt"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Tips"
android:label="#string/title_activity_tips"
android:theme="#style/AppTheme.NoActionBar" />
<activity android:name=".AlarmActivity" />
<receiver android:name=".Alarm_Receiver" />
<activity android:name=".DeviceListActivity" />
<activity android:name=".ArduinoMain"/>
<service
android:name=".RingtonePlayingService"
android:enabled="true" />
</application>
</manifest>
This is my Home.java with drawer navigation
package com.progetto.app;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer;
NavigationView navigationView;
Toolbar toolbar = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, 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
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
switch (id){
case R.id.nav_home:
Intent h = new Intent(Home.this,ArduinoMain.class);
startActivity(h);
break;
case R.id.nav_bt:
Intent i = new Intent(Home.this,DeviceListActivity.class);
startActivity(i);
break;
case R.id.nav_alarm:
Intent g = new Intent(Home.this,AlarmActivity.class);
startActivity(g);
break;
case R.id.nav_tips:
Intent s = new Intent(Home.this,Tips.class);
startActivity(s);
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
This is the activity I'm trying to connect to Home, I want to see this activity when the spash screen is over
package com.progetto.app;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class ArduinoMain extends Activity {
//Declare buttons & editText
Button functionOne, functionTwo;
private EditText editText;
//Memeber Fields
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// UUID service - This is the type of Bluetooth device that the BT module is
// It is very likely yours will be the same, if not google UUID for your manufacturer
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module
public String newAddress = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_arduino_main);
addKeyListener();
//Initialising buttons in the view
//mDetect = (Button) findViewById(R.id.mDetect);
functionOne = (Button) findViewById(R.id.functionOne);
functionTwo = (Button) findViewById(R.id.functionTwo);
//getting the bluetooth adapter value and calling checkBTstate function
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
/**************************************************************************************************************************8
* Buttons are set up with onclick listeners so when pressed a method is called
* In this case send data is called with a value and a toast is made
* to give visual feedback of the selection made
*/
functionOne.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("1");
Toast.makeText(getBaseContext(), "Function 1", Toast.LENGTH_SHORT).show();
}
});
functionTwo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("2");
Toast.makeText(getBaseContext(), "Function 2", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResume() {
super.onResume();
// connection methods are best here in case program goes into the background etc
//Get MAC address from DeviceListActivity
Intent intent = getIntent();
newAddress = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Set up a pointer to the remote device using its address.
BluetoothDevice device = btAdapter.getRemoteDevice(newAddress);
//Attempt to create a bluetooth socket for comms
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e1) {
Toast.makeText(getBaseContext(), "ERROR - Could not create Bluetooth socket", Toast.LENGTH_SHORT).show();
}
// Establish the connection.
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close(); //If IO exception occurs attempt to close socket
} catch (IOException e2) {
Toast.makeText(getBaseContext(), "ERROR - Could not close Bluetooth socket", Toast.LENGTH_SHORT).show();
}
}
// Create a data stream so we can talk to the device
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
Toast.makeText(getBaseContext(), "ERROR - Could not create bluetooth outstream", Toast.LENGTH_SHORT).show();
}
//When activity is resumed, attempt to send a piece of junk data ('x') so that it will fail if not connected
// i.e don't wait for a user to press button to recognise connection failure
sendData("x");
}
#Override
public void onPause() {
super.onPause();
//Pausing can be the end of an app if the device kills it or the user doesn't open it again
//close all connections so resources are not wasted
//Close BT socket to device
try {
btSocket.close();
} catch (IOException e2) {
Toast.makeText(getBaseContext(), "ERROR - Failed to close Bluetooth socket", Toast.LENGTH_SHORT).show();
}
}
//takes the UUID and creates a comms socket
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
//same as in device list activity
private void checkBTState() {
// Check device has Bluetooth and that it is turned on
if(btAdapter==null) {
Toast.makeText(getBaseContext(), "ERROR - Device does not support bluetooth", Toast.LENGTH_SHORT).show();
finish();
} else {
if (btAdapter.isEnabled()) {
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
// Method to send data
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
try {
//attempt to place data on the outstream to the BT device
outStream.write(msgBuffer);
} catch (IOException e) {
//if the sending fails this is most likely because device is no longer there
Toast.makeText(getBaseContext(), "ERROR - Device not found", Toast.LENGTH_SHORT).show();
finish();
}
}
public void addKeyListener() {
// get edittext component
editText = (EditText) findViewById(R.id.editText1);
// add a keylistener to keep track user input
editText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// if keydown and send is pressed implement the sendData method
if ((keyCode == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
//I have put the * in automatically so it is no longer needed when entering text
sendData('*' + editText.getText().toString());
Toast.makeText(getBaseContext(), "Sending text", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
}
}
This is the splash screen
package com.progetto.app;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
public class SplashScreen extends AppCompatActivity {
private ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
iv=(ImageView) findViewById(R.id.iv);
Animation myanim= AnimationUtils.loadAnimation(this,R.anim.mytransition);
iv.startAnimation(myanim);
final Intent i=new Intent(this, Home.class);
Thread timer =new Thread(){
public void run(){
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally{
startActivity(i);
finish();
}
}
};
timer.start();
}
}
This is the project
DropBox
This is the apk
Apk

Back button on Action Bar crashing app android

Synposis: I have 3 activity (LoginActivity, MainActivity and EditProfileActivity). After Facebook login in my LoginActivity I srart the MainActivity. (Till this point the app is working perfectly correct with no error). I have a NavigationDrawer for my navigations, When I click on Edit Profile link from the NavigationDrawer it starts the EditProfileActivity.
Problem: When I click on the LeftArrow in the Top blue bar, the app crashes.
Please see the images:
MainActivity
Navigation Drawer
EditProfileActivity
App Crash on clicking the top left arrow
Here is my Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.example">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="#string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
<activity android:name=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="com.facebook.FacebookContentProvider"
android:authorities="com.facebook.app.FacebookContentProvider"
android:exported="true" />
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
android:theme="#style/AppTheme.NoActionBar">
</activity>
<activity android:name=".EditProfileActivity"
android:parentActivityName=".MainActivity" >
<!-- The meta-data tag is required if you support API level 15 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</activity>
</application>
</manifest>
Here is my MainActivity.java
package com.example.example;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
Bundle inBundle = getIntent().getExtras();
String first_name = inBundle.get("first_name").toString();
String last_name = inBundle.get("last_name").toString();
String imageUrl = inBundle.get("imageUrl").toString();
TextView nameView = (TextView)findViewById(R.id.nameView);
nameView.setText("" + first_name + " " + last_name);
new DownloadImage((ImageView)findViewById(R.id.imageView)).execute(imageUrl);
return true;
}
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
#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
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
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) {
} else if(id == R.id.nav_user_edit){
Intent intent = new Intent(this, EditProfileActivity.class);
startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
You have to define your activities parent in the manifest file like this
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="fully qualified activity name" />
Make sure that you keep this meta data of your activity containing back button. Other wise its just like you are not telling you back button where to go !!
You have to add these two lines in your MainActivity.java file:
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Add this in your onOptionsItemSelected(MenuItem item) method:
if (id==android.R.id.home)
{
NavUtils.navigateUpFromSameTask(this);
}
In your toolbar.xml set an imageview. Do like this i your toolbar.xml
<ImageView
android:id="#+id/tv_header_title2"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:src="#drawable/backbutton"
android:layout_marginLeft="15dp"/>
In MainActivity
ImageView img= (ImageView) findViewById(R.id.tv_header_title2);
and
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});

Developed app with navigation menu, it shows "Unfortunately App name Has Stopped" even before opening app

I have developed app with sliding navigation menu. it doesnt contain any error in the project. I have successfully build signed apk but after installing it on phone it shows "unfortunately Appname has stopped" even before opening the app.
Manifest:
<?xml version="1.1" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wAashiqeRasool.HamareNabi" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<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.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
android:hardwareAccelerated="true"
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name="com.wAashiqeRasool.HamareNabi.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>
</activity>
</application>
</manifest>
MainActivity:
package com.wAashiqeRasool.HamareNabi;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.KeyEvent;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//initializing WebView
private WebView mwebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton)
findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action",
Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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);
//WebView
mwebView = (WebView) findViewById(R.id.myWebView);
WebSettings webSettings = mwebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//improve webView performance
mwebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
mwebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
mwebView.getSettings().setAppCacheEnabled(true);
mwebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
mwebView.loadUrl("www.hamarenabi.in?m=1");
//force links open in webview only
mwebView.setWebViewClient(new MyWebviewClient());
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// 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
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_us) {
// Handle the camera action
mwebView.loadUrl("http://www.hamarenabi.in/search/label/Asma-E-
Husna?m=1");
} else if (id == R.id.nav_world) {
mwebView.loadUrl("http://www.hamarenabi.in/p/nikah-in-islam-
assalamu-alaikum-wa.html?m=1");
} else if (id == R.id.nav_tech) {
mwebView.loadUrl("http://www.hamarenabi.in/search/label/aqaid-e-
ahle%20sunnat?m=1");
} else if (id == R.id.nav_sports) {
mwebView.loadUrl("http://www.hamarenabi.in/p/ramzan.html?m=1");
} else if (id == R.id.nav_share) {
mwebView.loadUrl("http://www.hamarenabi.in/p/contact.html?m=1");
} else if (id == R.id.nav_send) {
mwebView.loadUrl("http://www.hamarenabi.in/p/contact-us.html?m=1");
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private class MyWebviewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.hamarenabi.in?m=1")) {
//open url contents in webview
return false;
} else {
//here open external links in external browser or app
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
//ProgressDialogue
ProgressDialog pd = null;
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
pd=new ProgressDialog(MainActivity.this);
pd.setTitle("Please Wait..");
pd.setMessage("Website is Loading..");
pd.show();
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
pd.dismiss();
super.onPageFinished(view, url);
}
}
//goto previous page when pressing back button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mwebView.canGoBack()) {
mwebView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
Build.Gradle (Modular App):
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion '25.0.0'
defaultConfig {
applicationId "com.wAashiqeRasool.HamareNabi"
minSdkVersion 21
targetSdkVersion 23
versionCode 1
versionName "1.1"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.0.0'
compile 'com.android.support:design:23.0.0'
}
The crash is because the variable 'pd' is null in your onPageFinished() call. Add a null check as shown below and you won't see any crash in onPageFinished().
#Override
public void onPageFinished(WebView view, String url) {
if( pd != null )
pd.dismiss();
super.onPageFinished(view, url);
}

OnOptionsItemSelected Method not called on click of back button android.R.id.home

I have an app with single activity (HomeActivity) and 3 fragments . When i traverse from Home Fragment to Second Fragment , i replace Hammburger icon with Back button by(setDisplayHomeAsUpEnabled(true)).But when i press back button it does nothing and even onOptionsItemSelected() method is not called.I have spend my entire day behind this error.Please help
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.propelbit.jaydeepsaress">
<uses-permission android:name="android.permission.INTERNET" />
<!-- Include following permission if you want to cache images on SD card -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name="com.propelbit.jaydeepsaress.JaydeepSarees"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".ui.activity.HomeActivity"
android:parentActivityName=".ui.activity.HomeActivity"
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>
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.propelbit.jaydeepsaress.ui.activity.HomeActivity"/>
</activity>
</application>
</manifest>
HomeActivity
package com.propelbit.jaydeepsaress.ui.activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.propelbit.jaydeepsaress.R;
import com.propelbit.jaydeepsaress.ui.fragment.HomeFragment;
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public ActionBarDrawerToggle toggle;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
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);
if (savedInstanceState == null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
toggle.setDrawerIndicatorEnabled(true);
ft.replace(R.id.content_frame, new HomeFragment());
ft.commit();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
FragmentManager fm = getSupportFragmentManager();
int backStackEntryCount = fm.getBackStackEntryCount();
Log.d("BSEC",backStackEntryCount+"");
if (backStackEntryCount > 0) {
fm.popBackStack();
if (fm.getBackStackEntryCount() > 0) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toggle.setDrawerIndicatorEnabled(false);
} else {
//drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
// Display the Drawer Icon
toggle.setDrawerIndicatorEnabled(true);
}
} else {
//drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
// Display the Drawer Icon
toggle.setDrawerIndicatorEnabled(true);
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
toggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("TAG",item.getItemId()+"");
switch (item.getItemId()) {
case android.R.id.home:
// Do nothing handled by fragment.
return false;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
HomeFragment
package com.propelbit.jaydeepsaress.ui.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import com.propelbit.jaydeepsaress.R;
import com.propelbit.jaydeepsaress.ui.activity.HomeActivity;
/**
* Created by ankit on 05/09/16.
*/
public class HomeFragment extends Fragment implements View.OnClickListener {
private Button btnDyedWork, btnFancyPrint, btnBridalcollection, btnBlouse;
private LinearLayout linearTypeDyedWork, linearTypeFancyPrint;
private boolean flagDyedWork = false;
private boolean flagFancyPrint = false;
private Button btnDyedWorkCatalogue;
CoordinatorLayout.Behavior behavior;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View vi = inflater.inflate(R.layout.fragment_home, container, false);
btnDyedWork = (Button) vi.findViewById(R.id.btn_dyed_work);
btnFancyPrint = (Button) vi.findViewById(R.id.btn_fancy_print);
btnDyedWork.setOnClickListener(this);
linearTypeDyedWork = (LinearLayout) vi.findViewById(R.id.type_dyed_work);
linearTypeFancyPrint = (LinearLayout) vi.findViewById(R.id.type_fancy_print);
btnDyedWorkCatalogue = (Button) vi.findViewById(R.id.btn_dyed_work_catalogue);
btnDyedWorkCatalogue.setOnClickListener(this);
return vi; }
public void onClick (View v){
switch (v. getId()){
case R.id.btn_dyed_work:
if(!flagDyedWork){
linearTypeDyedWork.setVisibility(View.VISIBLE);
linearTypeFancyPrint.setVisibility(View.GONE);
flagDyedWork=true;
flagFancyPrint=false;
btnDyedWork.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.ic_keyboard_arrow_up),null);
}else{
linearTypeDyedWork.setVisibility(View.GONE);
linearTypeFancyPrint.setVisibility(View.GONE);
flagDyedWork=false;
flagFancyPrint=false;
btnDyedWork.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.ic_keyboard_arrow_down),null);
}
break;
case R.id.btn_fancy_print:
if(!flagFancyPrint){
linearTypeDyedWork.setVisibility(View.VISIBLE);
linearTypeFancyPrint.setVisibility(View.GONE);
flagFancyPrint=true;
flagDyedWork=false;
btnFancyPrint.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.ic_keyboard_arrow_up),null);
}else{
linearTypeDyedWork.setVisibility(View.GONE);
linearTypeFancyPrint.setVisibility(View.GONE);
flagFancyPrint=false;
flagDyedWork=false;
btnFancyPrint.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.ic_keyboard_arrow_down),null);
}
break;
case R.id.btn_dyed_work_catalogue:
Bundle bundle=new Bundle();
bundle.putString("category_id","1");
CatalogueFragment cf=new CatalogueFragment();
cf.setArguments(bundle);
FragmentManager fm=getActivity().getSupportFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.replace(R.id.content_frame,cf,"catalogue_fragment");
//ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
break;
}
}
}
CatalogueFragment
package com.propelbit.jaydeepsaress.ui.fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TextView;
import com.propelbit.jaydeepsaress.R;
import com.propelbit.jaydeepsaress.core.cons.Constants;
import com.propelbit.jaydeepsaress.core.parser.JsonParser;
import com.propelbit.jaydeepsaress.core.pojo.CatalogueDetails;
import com.propelbit.jaydeepsaress.ui.activity.HomeActivity;
import com.propelbit.jaydeepsaress.ui.adapter.AdapterCatalogue;
import org.json.JSONException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by ankit on 07/09/16.
*/
public class CatalogueFragment extends Fragment {
String categoryId;
String serverResponse;
GridView gridview;
TextView noDataFound;
ArrayList<CatalogueDetails> listCatalogue;
AdapterCatalogue adapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
((HomeActivity) getActivity()).toggle.setDrawerIndicatorEnabled(false);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View vi = inflater.inflate(R.layout.fragment_catalogue, container, false);
if (this.getArguments() != null) {
categoryId = this.getArguments().getString("category_id");
}
listCatalogue=new ArrayList<CatalogueDetails>();
adapter=new AdapterCatalogue(getActivity(),listCatalogue);
gridview = (GridView) vi.findViewById(R.id.gridview);
noDataFound = (TextView) vi.findViewById(R.id.no_data_found);
gridview.setAdapter(adapter);
new GetCatalogueDetails().execute(Constants.BASE_URL+"getCatalogueDetails");
return vi;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("TAG",item.getItemId()+"");
switch (item.getItemId()) {
case android.R.id.home:
Log.d("Called","Back Button");
getActivity().onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
private class GetCatalogueDetails extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.readTimeout(60, TimeUnit.SECONDS);
Log.d("CatalogueF",categoryId);
OkHttpClient client = builder.build();
RequestBody formBody = new FormBody.Builder()
.add("category_id", categoryId)
.build();
Request request = new Request.Builder()
.url(params[0])
.post(formBody)
.build();
Response response = null;
response = client.newCall(request).execute();
serverResponse = response.body().string();
Log.d("response", serverResponse);
return JsonParser.parseResponseCode(serverResponse);
} catch (IOException e) {
e.printStackTrace();
return "102";
} catch (JSONException e) {
e.printStackTrace();
return "103";
}
}
#Override
protected void onPostExecute(String responseCode) {
try {
if (responseCode.equals("100")) {
ArrayList<CatalogueDetails> temp= JsonParser.parseCatalogueDetails(serverResponse);
int size=temp.size();
Log.d("size",size+""+temp.get(0).getCatalogueName());
if(size>0){
listCatalogue.addAll(temp);
Log.d("listCatalogue",listCatalogue.size()+"");
gridview.setVisibility(View.VISIBLE);
noDataFound.setVisibility(View.GONE);
adapter.notifyDataSetChanged();
}else{
gridview.setVisibility(View.GONE);
noDataFound.setVisibility(View.VISIBLE);
noDataFound.setText("No data found");
}
}else if(responseCode.equals("101")){
gridview.setVisibility(View.GONE);
noDataFound.setVisibility(View.VISIBLE);
noDataFound.setText("SQL Exception.Please try again");
}else if(responseCode.equals("102")){
gridview.setVisibility(View.GONE);
noDataFound.setVisibility(View.VISIBLE);
noDataFound.setText("IO Exception.Please try again");
}else if(responseCode.equals("103")){
gridview.setVisibility(View.GONE);
noDataFound.setVisibility(View.VISIBLE);
noDataFound.setText("JSON Exception.Please try again.");
}
} catch (JSONException e) {
e.printStackTrace();
gridview.setVisibility(View.GONE);
noDataFound.setVisibility(View.VISIBLE);
noDataFound.setText("JSON Exception..Please try again.");
}
}
}
}
setHasOptionsMenu(true);
include this in fragment so that onOptionItemSelected() can be called.
Finally solved.
Now, if you want to listen to clicks on any type of NavigationIcon in your custom toolbar (be it a Hamburger or up-caret or some fancy icon) then use setToolbarNavigationClickListener(). No need to use onOptionsItemSelected Method.
Thanks Protino for suggestion
// Add the backstack listener
getSupportFragmentManager().addOnBackStackChangedListener(this);
// Handle clicks on the up arrow since this isnt handled by the
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getSupportFragmentManager();
// Pop the backstack all the way back to the initial fragment. Customize if needed
//fm.popBackStack(fm.getBackStackEntryAt(0).getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
if(fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
toggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
toggle.setDrawerIndicatorEnabled(true);
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
}
});
/**
* Called everytime we add or remove something from the backstack
*/
#Override
public void onBackStackChanged() {
if(getSupportFragmentManager().getBackStackEntryCount() > 0) {
Log.d("Called >0","false");
toggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
} else {
Log.d("Called <0","true");
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
toggle.setDrawerIndicatorEnabled(true);
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
}
/**
* If you need to move backwards inside the app using the back button, and want to override the
* the default behaviour which could take you outside the app before you've popped the entire stack
*/
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStackImmediate();
} else {
super.onBackPressed();
}
}
Well to call the activity method, you should use something like this
((YourActivityName)getActivity()).onBackPressed();
and for the log to work you need to include the tag too.
Log.d(TAG, "Your message");

How to use onOptionsItemSelected with Single Activity having multiple fragments

The problem i am facing is as i set setDisplayHomeUpAsEnabled(true), on clicking back button onOptionsItemSelected dosent not get called.I doubt if my manifest file is correct.Below i am putting my manifest file.Please suggest .Thank you.
MANIFEST FILE
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.propelbit.jaydeepsaress">
<uses-permission android:name="android.permission.INTERNET" />
<!-- Include following permission if you want to cache images on SD card -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name="com.propelbit.jaydeepsaress.JaydeepSarees"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".ui.activity.HomeActivity"
android:parentActivityName=".ui.activity.HomeActivity"
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>
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.propelbit.jaydeepsaress.ui.activity.HomeActivity"/>
</activity>
</application>
</manifest>
Home Activity
package com.propelbit.jaydeepsaress.ui.activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.propelbit.jaydeepsaress.R;
import com.propelbit.jaydeepsaress.ui.fragment.HomeFragment;
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public ActionBarDrawerToggle toggle;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
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);
if (savedInstanceState == null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
toggle.setDrawerIndicatorEnabled(true);
ft.replace(R.id.content_frame, new HomeFragment());
ft.commit();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
FragmentManager fm = getSupportFragmentManager();
int backStackEntryCount = fm.getBackStackEntryCount();
Log.d("BSEC",backStackEntryCount+"");
if (backStackEntryCount > 0) {
fm.popBackStack();
if (fm.getBackStackEntryCount() > 0) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toggle.setDrawerIndicatorEnabled(false);
} else {
//drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
// Display the Drawer Icon
toggle.setDrawerIndicatorEnabled(true);
}
} else {
//drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
// Display the Drawer Icon
toggle.setDrawerIndicatorEnabled(true);
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
toggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("TAG",item.getItemId()+"");
switch (item.getItemId()) {
case android.R.id.home:
// Do nothing handled by fragment.
return false;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Home Fragment
package com.propelbit.jaydeepsaress.ui.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import com.propelbit.jaydeepsaress.R;
import com.propelbit.jaydeepsaress.ui.activity.HomeActivity;
/**
* Created by ankit on 05/09/16.
*/
public class HomeFragment extends Fragment implements View.OnClickListener {
private Button btnDyedWork, btnFancyPrint, btnBridalcollection, btnBlouse;
private LinearLayout linearTypeDyedWork, linearTypeFancyPrint;
private boolean flagDyedWork = false;
private boolean flagFancyPrint = false;
private Button btnDyedWorkCatalogue;
CoordinatorLayout.Behavior behavior;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View vi = inflater.inflate(R.layout.fragment_home, container, false);
btnDyedWork = (Button) vi.findViewById(R.id.btn_dyed_work);
btnFancyPrint = (Button) vi.findViewById(R.id.btn_fancy_print);
btnDyedWork.setOnClickListener(this);
linearTypeDyedWork = (LinearLayout) vi.findViewById(R.id.type_dyed_work);
linearTypeFancyPrint = (LinearLayout) vi.findViewById(R.id.type_fancy_print);
btnDyedWorkCatalogue = (Button) vi.findViewById(R.id.btn_dyed_work_catalogue);
btnDyedWorkCatalogue.setOnClickListener(this);
return vi; }
public void onClick (View v){
switch (v. getId()){
case R.id.btn_dyed_work:
if(!flagDyedWork){
linearTypeDyedWork.setVisibility(View.VISIBLE);
linearTypeFancyPrint.setVisibility(View.GONE);
flagDyedWork=true;
flagFancyPrint=false;
btnDyedWork.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.ic_keyboard_arrow_up),null);
}else{
linearTypeDyedWork.setVisibility(View.GONE);
linearTypeFancyPrint.setVisibility(View.GONE);
flagDyedWork=false;
flagFancyPrint=false;
btnDyedWork.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.ic_keyboard_arrow_down),null);
}
break;
case R.id.btn_fancy_print:
if(!flagFancyPrint){
linearTypeDyedWork.setVisibility(View.VISIBLE);
linearTypeFancyPrint.setVisibility(View.GONE);
flagFancyPrint=true;
flagDyedWork=false;
btnFancyPrint.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.ic_keyboard_arrow_up),null);
}else{
linearTypeDyedWork.setVisibility(View.GONE);
linearTypeFancyPrint.setVisibility(View.GONE);
flagFancyPrint=false;
flagDyedWork=false;
btnFancyPrint.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.ic_keyboard_arrow_down),null);
}
break;
case R.id.btn_dyed_work_catalogue:
Bundle bundle=new Bundle();
bundle.putString("category_id","1");
CatalogueFragment cf=new CatalogueFragment();
cf.setArguments(bundle);
FragmentManager fm=getActivity().getSupportFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.replace(R.id.content_frame,cf,"catalogue_fragment");
//ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
break;
}
}
}
Catalogue Fragment
package com.propelbit.jaydeepsaress.ui.fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TextView;
import com.propelbit.jaydeepsaress.R;
import com.propelbit.jaydeepsaress.core.cons.Constants;
import com.propelbit.jaydeepsaress.core.parser.JsonParser;
import com.propelbit.jaydeepsaress.core.pojo.CatalogueDetails;
import com.propelbit.jaydeepsaress.ui.activity.HomeActivity;
import com.propelbit.jaydeepsaress.ui.adapter.AdapterCatalogue;
import org.json.JSONException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by ankit on 07/09/16.
*/
public class CatalogueFragment extends Fragment {
String categoryId;
String serverResponse;
GridView gridview;
TextView noDataFound;
ArrayList<CatalogueDetails> listCatalogue;
AdapterCatalogue adapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
((HomeActivity) getActivity()).toggle.setDrawerIndicatorEnabled(false);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View vi = inflater.inflate(R.layout.fragment_catalogue, container, false);
if (this.getArguments() != null) {
categoryId = this.getArguments().getString("category_id");
}
listCatalogue=new ArrayList<CatalogueDetails>();
adapter=new AdapterCatalogue(getActivity(),listCatalogue);
gridview = (GridView) vi.findViewById(R.id.gridview);
noDataFound = (TextView) vi.findViewById(R.id.no_data_found);
gridview.setAdapter(adapter);
new GetCatalogueDetails().execute(Constants.BASE_URL+"getCatalogueDetails");
return vi;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("TAG",item.getItemId()+"");
switch (item.getItemId()) {
case android.R.id.home:
Log.d("Called","Back Button");
getActivity().onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
private class GetCatalogueDetails extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.readTimeout(60, TimeUnit.SECONDS);
Log.d("CatalogueF",categoryId);
OkHttpClient client = builder.build();
RequestBody formBody = new FormBody.Builder()
.add("category_id", categoryId)
.build();
Request request = new Request.Builder()
.url(params[0])
.post(formBody)
.build();
Response response = null;
response = client.newCall(request).execute();
serverResponse = response.body().string();
Log.d("response", serverResponse);
return JsonParser.parseResponseCode(serverResponse);
} catch (IOException e) {
e.printStackTrace();
return "102";
} catch (JSONException e) {
e.printStackTrace();
return "103";
}
}
#Override
protected void onPostExecute(String responseCode) {
try {
if (responseCode.equals("100")) {
ArrayList<CatalogueDetails> temp= JsonParser.parseCatalogueDetails(serverResponse);
int size=temp.size();
Log.d("size",size+""+temp.get(0).getCatalogueName());
if(size>0){
listCatalogue.addAll(temp);
Log.d("listCatalogue",listCatalogue.size()+"");
gridview.setVisibility(View.VISIBLE);
noDataFound.setVisibility(View.GONE);
adapter.notifyDataSetChanged();
}else{
gridview.setVisibility(View.GONE);
noDataFound.setVisibility(View.VISIBLE);
noDataFound.setText("No data found");
}
}else if(responseCode.equals("101")){
gridview.setVisibility(View.GONE);
noDataFound.setVisibility(View.VISIBLE);
noDataFound.setText("SQL Exception.Please try again");
}else if(responseCode.equals("102")){
gridview.setVisibility(View.GONE);
noDataFound.setVisibility(View.VISIBLE);
noDataFound.setText("IO Exception.Please try again");
}else if(responseCode.equals("103")){
gridview.setVisibility(View.GONE);
noDataFound.setVisibility(View.VISIBLE);
noDataFound.setText("JSON Exception.Please try again.");
}
} catch (JSONException e) {
e.printStackTrace();
gridview.setVisibility(View.GONE);
noDataFound.setVisibility(View.VISIBLE);
noDataFound.setText("JSON Exception..Please try again.");
}
}
}
}
First, you need to remove parenting metadata from the manifest. It's incorrect.
<activity
android:name=".ui.activity.HomeActivity"
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>
</activity>
Now, if you want to listen to clicks on any type of NavigationIcon in your custom toolbar (be it a Hamburger or up-caret or some fancy icon) then use setToolbarNavigationClickListener().
In your HomeActivity do this :
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* do whatever you want like popping the fragment from backstack
getSupportFragmentManager().popBackStackImmediate(); */
}
});
I had this problem too. Check this thread : Cannot listen clicks on up caret
The best way to do that is to handle back presses in the activity. In the fragments make put this or remove the onOptionsItemSelected method entirely:
case android.R.id.home:
return false;
In Your activity:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("TAG",item.getItemId()+"");
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}

Categories

Resources