Can't display my activity from navigation drawer - android

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

Related

no permissions allowed auto android studio

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

Activity not starting, another activity is starting instead

I am facing a very weird issue. I am trying to launch one activity but instead of that, another activity is opening. I am trying to open RegActivity, I do have specified it in manifest and also made it Launcher activity but instead of that when I run the app "MainActivity" is calling.
MainActivity is not even a Launcher or Default activity. I cleaned up the project, Rebuilt it. But still, nothing works.
My Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.solodroid.ecommerce" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="#drawable/ic_launcher"
android:label="Frizzy"
android:theme="#style/AppTheme2" >
<activity
android:name="com.solodroid.ecommerce.RegActivity"
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>
<activity
android:name="com.solodroid.ecommerce.MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.solodroid.ecommerce.ActivityCategoryList"
android:screenOrientation="portrait" />
<activity
android:name="com.solodroid.ecommerce.ActivityMenuList"
android:configChanges="keyboardHidden|orientation"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateHidden" />
<activity
android:name="com.solodroid.ecommerce.ActivityMenuDetail"
android:screenOrientation="portrait" />
<activity
android:name="com.solodroid.ecommerce.ActivityCart"
android:screenOrientation="portrait" />
<activity
android:name="com.solodroid.ecommerce.ActivityCheckout"
android:configChanges="keyboardHidden|orientation"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateHidden" />
<activity
android:name="com.solodroid.ecommerce.ActivityConfirmMessage"
android:screenOrientation="portrait" />
<activity
android:name="com.solodroid.ecommerce.ActivityContactUs"
android:screenOrientation="portrait" />
<activity
android:name="com.solodroid.ecommerce.ActivityProfile"
android:screenOrientation="portrait" />
<activity
android:name="com.solodroid.ecommerce.ActivityInformation"
android:screenOrientation="portrait" />
<activity
android:name="com.solodroid.ecommerce.ActivityAbout"
android:screenOrientation="portrait" />
<activity
android:name="com.solodroid.ecommerce.LoginActivity"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar"/>
<service android:name="com.parse.PushService" />
<receiver android:name="com.parse.ParseBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"
/>
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
</application>
</manifest>
RegActivity.java
package com.solodroid.ecommerce;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import java.io.IOException;
import java.util.HashMap;
public class RegActivity extends AppCompatActivity {
private EditText etid, etname, etstorename, etemail, etphone, etdoj;
Button btnregister;
TextView tvlogin;
private ParseContent parseContent;
PreferenceHelper preferenceHelper;
private final int RegTask = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reg);
preferenceHelper = new PreferenceHelper(this);
parseContent = new ParseContent(this);
if(preferenceHelper.getIsLogin()){
Intent intent = new Intent(RegActivity.this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
this.finish();
}
//etid = (EditText) findViewById(R.id.etmi_id);
etname = (EditText) findViewById(R.id.etname);
//etstorename = (EditText) findViewById(R.id.etstore_name);
etemail = (EditText) findViewById(R.id.etemail);
etphone = (EditText) findViewById(R.id.etphone);
// etdoj = (EditText) findViewById(R.id.etdoj);
btnregister = (Button) findViewById(R.id.btn);
tvlogin = (TextView) findViewById(R.id.tvlogin);
tvlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(RegActivity.this,LoginActivity.class);
startActivity(intent);
}
});
btnregister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
register();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
private void register() throws IOException, JSONException {
if (!AndyUtils.isNetworkAvailable(RegActivity.this)) {
Toast.makeText(RegActivity.this, "Internet is required!", Toast.LENGTH_SHORT).show();
return;
}
AndyUtils.showSimpleProgressDialog(RegActivity.this);
final HashMap<String, String> map = new HashMap<>();
// map.put(AndyConstants.Params.MI_ID, etid.getText().toString());
map.put(AndyConstants.Params.NAME, etname.getText().toString());
// map.put(AndyConstants.Params.STORE_NAME, etstorename.getText().toString());
map.put(AndyConstants.Params.EMAIL, etemail.getText().toString());
map.put(AndyConstants.Params.PHONE, etphone.getText().toString());
//map.put(AndyConstants.Params.DOJ, etdoj.getText().toString());
new AsyncTask<Void, Void, String>(){
protected String doInBackground(Void[] params) {
String response="";
try {
HttpRequest req = new HttpRequest(AndyConstants.ServiceType.REGISTER);
response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
} catch (Exception e) {
response=e.getMessage();
}
return response;
}
protected void onPostExecute(String result) {
//do something with response
Log.d("newwwss", result);
onTaskCompleted(result, RegTask);
}
}.execute();
}
private void onTaskCompleted(String response,int task) {
Log.d("responsejson", response.toString());
AndyUtils.removeSimpleProgressDialog(); //will remove progress dialog
switch (task) {
case RegTask:
if (parseContent.isSuccess(response)) {
parseContent.saveInfo(response);
Toast.makeText(RegActivity.this, "Registered Successfully!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(RegActivity.this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
this.finish();
}else {
Toast.makeText(RegActivity.this, parseContent.getErrorMessage(response), Toast.LENGTH_SHORT).show();
}
}
}
}
LoginActivity.java
package com.solodroid.ecommerce;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import java.io.IOException;
import java.util.HashMap;
public class LoginActivity extends AppCompatActivity {
private EditText etemail, etpassword;
Button btnlogin;
TextView tvreg;
private ParseContent parseContent;
private final int LoginTask = 1;
PreferenceHelper preferenceHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
parseContent = new ParseContent(this);
preferenceHelper = new PreferenceHelper(this);
etemail = (EditText) findViewById(R.id.etusername);
etpassword = (EditText) findViewById(R.id.etpassword);
btnlogin = (Button) findViewById(R.id.btn);
tvreg = (TextView) findViewById(R.id.tvreg);
tvreg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, RegActivity.class);
startActivity(intent);
}
});
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
login();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
private void login() throws IOException, JSONException {
if (!AndyUtils.isNetworkAvailable(LoginActivity.this)) {
Toast.makeText(LoginActivity.this, "Internet is required!", Toast.LENGTH_SHORT).show();
return;
}
AndyUtils.showSimpleProgressDialog(LoginActivity.this);
final HashMap<String, String> map = new HashMap<>();
map.put(AndyConstants.Params.EMAIL, etemail.getText().toString());
map.put(AndyConstants.Params.PASSWORD, etpassword.getText().toString());
new AsyncTask<Void, Void, String>(){
protected String doInBackground(Void[] params) {
String response="";
try {
HttpRequest req = new HttpRequest(AndyConstants.ServiceType.LOGIN);
response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
} catch (Exception e) {
response=e.getMessage();
}
return response;
}
protected void onPostExecute(String result) {
//do something with response
Log.d("newwwss", result);
onTaskCompleted(result,LoginTask);
}
}.execute();
}
private void onTaskCompleted(String response, int task) {
Log.d("responsejson", response.toString());
AndyUtils.removeSimpleProgressDialog(); //will remove progress dialog
switch (task) {
case LoginTask:
if (parseContent.isSuccess(response)) {
parseContent.saveInfo(response);
Toast.makeText(LoginActivity.this, "Login Successfully!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LoginActivity.this,RegActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
this.finish();
}else {
Toast.makeText(LoginActivity.this, parseContent.getErrorMessage(response), Toast.LENGTH_SHORT).show();
}
}
}
}
MainActivity.java
package com.solodroid.ecommerce;
import java.io.IOException;
import java.util.ArrayList;
import com.parse.Parse;
import com.parse.ParseAnalytics;
import com.parse.ParseInstallation;
import com.parse.PushService;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.database.SQLException;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
#SuppressLint("NewApi")
public class MainActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private AdapterNavDrawerList adapter;
// declare dbhelper and adapter object
static DBHelper dbhelper;
AdapterMainMenu mma;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nav_drawer_main);
// Parse push notification
Parse.initialize(this, getString(R.string.parse_application_id), getString(R.string.parse_client_key));
ParseAnalytics.trackAppOpened(getIntent());
PushService.setDefaultPushCallback(this, MainActivity.class);
ParseInstallation.getCurrentInstallation().saveInBackground();
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
mDrawerLayout.setDrawerShadow(R.drawable.navigation_drawer_shadow, GravityCompat.START);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons.getResourceId(7, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[8], navMenuIcons.getResourceId(8, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[9], navMenuIcons.getResourceId(9, -1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new AdapterNavDrawerList(getApplicationContext(), navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.header)));
// get screen device width and height
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
// checking internet connection
if (!Constant.isNetworkAvailable(MainActivity.this)) {
Toast.makeText(MainActivity.this, getString(R.string.no_internet), Toast.LENGTH_SHORT).show();
}
mma = new AdapterMainMenu(this);
dbhelper = new DBHelper(this);
// create database
try {
dbhelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
// then, the database will be open to use
try {
dbhelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
// if user has already ordered food previously then show confirm dialog
if (dbhelper.isPreviousDataExist()) {
showAlertDialog();
}
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, // nav
// menu
// toggle
// icon
R.string.app_name, // nav drawer open - description for
// accessibility
R.string.app_name // nav drawer close - description for
// accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
// show confirm dialog to ask user to delete previous order or not
void showAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.confirm);
builder.setMessage(getString(R.string.db_exist_alert));
builder.setCancelable(false);
builder.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
// delete order data when yes button clicked
dbhelper.deleteAllData();
dbhelper.close();
}
});
builder.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
// close dialog when no button clicked
dbhelper.close();
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
dbhelper.deleteAllData();
dbhelper.close();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
/**
* Slide menu item click listener
*/
private class SlideMenuClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.rate_app:
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + getPackageName())));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
}
return true;
case R.id.more_app:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.more_apps))));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/*
* * Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.ic_menu).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
*/
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new ActivityHome();
break;
case 1:
startActivity(new Intent(getApplicationContext(), ActivityCategoryList.class));
overridePendingTransition(R.anim.open_next, R.anim.close_next);
break;
case 2:
startActivity(new Intent(getApplicationContext(), ActivityCart.class));
overridePendingTransition(R.anim.open_next, R.anim.close_next);
break;
case 3:
startActivity(new Intent(getApplicationContext(), ActivityCheckout.class));
overridePendingTransition(R.anim.open_next, R.anim.close_next);
break;
case 4:
startActivity(new Intent(getApplicationContext(), ActivityProfile.class));
overridePendingTransition(R.anim.open_next, R.anim.close_next);
break;
case 5:
startActivity(new Intent(getApplicationContext(), ActivityInformation.class));
overridePendingTransition(R.anim.open_next, R.anim.close_next);
break;
case 6:
startActivity(new Intent(getApplicationContext(), ActivityAbout.class));
overridePendingTransition(R.anim.open_next, R.anim.close_next);
break;
case 7:
Intent sendInt = new Intent(Intent.ACTION_SEND);
sendInt.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
sendInt.putExtra(Intent.EXTRA_TEXT, "E-Commerce Android App\n\"" + getString(R.string.app_name)
+ "\" \nhttps://play.google.com/store/apps/details?id=" + getPackageName());
sendInt.setType("text/plain");
startActivity(Intent.createChooser(sendInt, "Share"));
break;
case 8:
startActivity(new Intent(getApplicationContext(), ActivityContactUs.class));
overridePendingTransition(R.anim.open_next, R.anim.close_next);
break;
case 9:
dbhelper.deleteAllData();
dbhelper.close();
MainActivity.this.finish();
overridePendingTransition(R.anim.open_next, R.anim.close_next);
break;
default:
break;
}
if (fragment != null) {
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
What is wrong here? I don't find anything.
What about this code in your onCreate()
if(preferenceHelper.getIsLogin()){
Intent intent = new Intent(RegActivity.this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
this.finish();
}
if preferenceHelper.getIsLogin() is true you wont be able to see your RegActivity beacause it will instantly start MainActivity.

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);
}

The startactivity(intent) method causes an error. Why?

I want after a click on the OK button the MenuActivity to be shown. I have already searched on the Internet to find an answer and tried everything. I haave the activity declared in the AndroidManifest and I also tried to use Intent(this, MenuActivity.class) and also the one with the action inside but it doesn't work.
MainActivity:
package com.jamesjohnson.chronos;
import android.app.AlertDialog;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.jamesjohnson.chronos.R;
public class MainActivity extends ActionBarActivity implements OnClickListener {
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setTitle("Willkommen");
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
#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_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
switch(id) {
case R.id.action_mainmenu:
startActivity(new Intent("com.jamesjohnson.chronos.MenuActivity"));
return true;
case R.id.action_settings:
showMessageBox("Es gibt leider noch keine Einstellungen. Wir arbeiten daran!", true, true);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
Context ctx = this;
intent.setClassName(ctx, "com.jamesjohnson.chronos.MenuActivity");
intent.setAction("com.jamesjohnson.chronos.MenuActivity");
if ((intent.getAction() == "com.jamesjohnson.chronos.MenuActivity") || (intent.getClass() != null)) {
MainActivity.this.startActivity(intent);
showMessageBox("Button has been pressed " + intent.toString(), true, true);
}
else {
showMessageBox("Error : Hauptmenü ist nicht erreichbar", true, true);
}
}
catch (ActivityNotFoundException an) {
showMessageBox("Error :" + an.getMessage(), true, true);
}
catch (Exception e) {
showMessageBox("Error :" + e.getMessage(), true, true);
}
}
protected void showMessageBox(String message, boolean showOKbutton, boolean canceable) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(MainActivity.this);
dlgAlert.setMessage(message);
dlgAlert.setTitle("Chronos");
if (showOKbutton) {
dlgAlert.setPositiveButton("OK", null);
}
if (canceable) {
dlgAlert.setCancelable(true);
}
dlgAlert.create().show();
}
}
Here's my AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jamesjohnson.chronos"
android:versionCode="1"
android:versionName="1.0.1
" >
<application
android:allowBackup="true"
android:debuggable="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
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=".MenuActivity"
android:label="#string/title_activity_menu"
android:parentActivityName=".MainActivity" >
<intent-filter>
<action android:name="com.jamesjohnson.chronos.MenuActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.jamesjohnson.chronos.MainActivity" />
</activity>
</application>
</manifest>
And finally here's the MenuActivity:
package com.jamesjohnson.chronos;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MenuActivity extends ListActivity {
private static final String TAG = "MenuActivity";
static final String[] ENTRIES = new String[] {"Kunden", "Projekte", "Leistungen", "Zeiten"};
ListView listView = getListView();
#Override
protected void onCreate(Bundle savedInstanceState) {
showMessageBox("Activity is beeing created", true, true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
this.setTitle("Hauptmenü");
this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ENTRIES));
listView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
showMessageBox("Kunden", true, true);
break;
case 1:
showMessageBox("Projekte", true, true);
break;
case 2:
showMessageBox("Leistungen", true, true);
break;
case 3:
showMessageBox("Zeiten", true, true);
break;
default:
showMessageBox("Error: Undefined index", true, true);
}
}
});
}
#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_menu, 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);
}
protected void showMessageBox(String message, boolean showOKbutton, boolean canceable) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(MenuActivity.this);
dlgAlert.setMessage(message);
dlgAlert.setTitle("Chronos");
if (showOKbutton) {
dlgAlert.setPositiveButton("OK", null);
}
if (canceable) {
dlgAlert.setCancelable(true);
}
dlgAlert.create().show();
}
}
Unfortunately I can't show you my Logcat because it doesn't work on my computer. (I always have to export the APK to test the App).
P.S. I am working with Android Studio 1.0.1
...Please HELP ME !
To open a new activity you simply have to call it like this inside the onClick method.
Intent intent = new Intent(v.getContext(), MenuActivity.class);
startActivity(intent);
So your onClick method will look like this.
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), MenuActivity.class);
startActivity(intent);
}
Hope this helps.
Is because you say MainActivity.this, but you aren't in the MainActivity context.
You could make a reference of your current context in onCreate() and save it in a field:
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
context = this;
//rest of your code here
}
and use it as:
Intent intent = new Intent(context, MenuActivity.class);
//Something else
context.startActivity(intent);
Go to your manifest file, you will for your MainActivity manifest:
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
Just copy them and paste them for your MenuActivity.
I had the same same problem than you and it worked for me, but I don't know why.
Good luck!
first make sure your AndroidManifest.xml file contain declaration of all Activities in your app, like
<activity android:name=".MenuActivity"/>
then you create new intent and start it where you need to start the second Activity
Intent intent = new Intent(v.getContext(), MenuActivity.class);
startActivity(intent);

android activity stack- back navigation

I am developing an app which has a home screen consisting of list view(Home Activity).User clicks on list item and new activity is started named as Topic.This activity also consist of list view. Home is set as parent activity for Topic.
Now in Topic class i am again calling Topic class using intent.
So a user clicks on a list item in Home activity,which opens a new Topic activity.User again clicks on list item ,and another new activity Topic is created,so we are at rd level. My app is working fine till here, but as Parent for Topic is Home,so as soon as i press back or up button,irrespective of where i am in my app,it is always the Home class which opens.
How to handle this so that all user can traverse back to each activity.
The code is given below:
Home.java
package com.example.guninder.home;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import java.util.List;
import static android.widget.AdapterView.*;
public class Home extends AppCompatActivity implements FetchDataListener {
private ProgressDialog dialog;
private ListView HomeListview;
private DrawerLayout home_drawer_layout;
private ListView Menu_option_list;
private String[] Menu_list;
private ActionBarDrawerToggle drawerToggle;
private ApplicationAdaptor adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
HomeListview = (ListView) findViewById(R.id.listView1);
itemClickListener(HomeListview);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
Menu_list = getResources().getStringArray(R.array.Menu_options);
home_drawer_layout = (DrawerLayout) findViewById(R.id.home_drawable);
Menu_option_list = (ListView) findViewById(R.id.home_menu_option);
Menu_option_list.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_expandable_list_item_1, Menu_list));
// home_Toolbar.setNavigationIcon(R.drawable.ic_drawer);
drawerToggle = new ActionBarDrawerToggle(this, home_drawer_layout, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
drawerToggle.setDrawerIndicatorEnabled(true);
home_drawer_layout.setDrawerListener(drawerToggle);
initView();
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity_actions, menu);
return true;
}
private void initView() {
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
// String url = "http://dexterous.comuv.com/connect.php";
String url = "http://192.168.0.25/connect.php";
FetchDataTask task = new FetchDataTask(this);
task.execute(url,null);
}
#Override
public void onFetchComplete(List<Application> data) {
// dismiss the progress dialog
if (dialog != null) dialog.dismiss();
// create new adapter
adapter = new ApplicationAdaptor(this, data);
HomeListview.setAdapter(adapter);
// set the adapter to list
//setListAdapter(adapter);
}
public void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if (dialog != null) dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
#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;
}
if(drawerToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
public void itemClickListener(final ListView HomeListview) {
HomeListview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Application app = adapter.getItem(position);
Intent intent = new Intent(Home.this, Topic.class);
intent.putExtra("topic_name",app.getTitle());
intent.putExtra("topic_id", app.getTopic_id());
intent.putExtra("Content", app.getParentContent());
Toast toast=Toast.makeText(Home.this,app.getParentContent(),Toast.LENGTH_LONG);
startActivity(intent);
}
});
}
}
Topic.java
package com.example.guninder.home;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class Topic extends AppCompatActivity implements FetchDataListener {
String topicName, ParentContent;
int topic_id;
//TextView txv;
ProgressDialog Topicdialog;
ListView topiclistView;
ApplicationAdaptor tAdaptor;
TextView txv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_topic);
Bundle extras = getIntent().getExtras();
if (extras == null) {
topicName = null;
}
topicName = extras.getString("topic_name");
topic_id = extras.getInt("topic_id");
ParentContent = extras.getString("Content");
txv = (TextView) findViewById(R.id.content);
txv.setMovementMethod(ScrollingMovementMethod.getInstance());
if (ParentContent.isEmpty()) {
txv.setVisibility(txv.GONE);
} else {
txv.setText(ParentContent);
}
setTitle(topicName);
topiclistView = (ListView) findViewById(R.id.topiclistView1);
itemClickListener(topiclistView);
topicinitView();
}
#Override
public void onPause(){
super.onPause();
}
public void onResume(){
super.onResume();
}
private void topicinitView() {
// show progress dialog
Topicdialog = ProgressDialog.show(this, "", "Loading...");
// String url = "http://dexterous.comuv.com/Topic.php";
String url = "http://192.168.0.25/Topic.php";
FetchDataTask task = new FetchDataTask(this);
task.execute(url, String.valueOf(topic_id));
}
#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_topic, 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);
}
#Override
public void onFetchComplete(List<Application> data) {
if (Topicdialog != null) Topicdialog.dismiss();
// create new adapter
tAdaptor = new ApplicationAdaptor(this, data);
topiclistView.setAdapter(tAdaptor);
// set the adapter to list
//setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if (Topicdialog != null) Topicdialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
public void itemClickListener(final ListView TopicListview) {
TopicListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Application app = tAdaptor.getItem(position);
if (app.getChildExist()) {
Intent intent = new Intent(Topic.this, Topic.class);
intent.putExtra("topic_name", app.getTitle());
intent.putExtra("topic_id", app.getTopic_id());
intent.putExtra("Content", app.getParentContent());
// Toast toast = Toast.makeText(Topic.this, app.getTopic_id(), Toast.LENGTH_LONG);
//toast.show();
startActivity(intent);
finish();
}
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.guninder.home" >
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Home"
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=".Topic"
android:label="#string/title_activity_topic"
android:parentActivityName=".Home" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.guninder.home.Home" />
</activity>
<activity
android:name=".SetNotification"
android:label="#string/title_activity_set_notification"
android:theme="#android:style/Theme.Dialog" >
</activity>
</application>
</manifest>
Please help.Thanks in advance
Comment finish() inside the listitem click in topic class. it will solve your problem.
What you could do is, do not set Home as the parent of Topic.
This way when user presses back, the previous activity that was open will be shown to the user.

Categories

Resources