When I rotate my screen, the WebView reloads the whole page. So I disabled rotation in Android_Manifest.xml file, but it would be really cool if I could make rotation possible.
SkateTube.java -
package com.example.skatetube.skatetube;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class SkateTube extends AppCompatActivity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_skatetube);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
if (savedInstanceState == null)
{
mWebView.loadUrl("http://skatetube.sytes.net/");
mWebView.setWebViewClient(new WebViewClient());
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} 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.menu_skate_tube, 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);
}
}
Android_manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.skatetube.skatetube">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".SkateTube"
android:theme="#style/AppTheme.NoActionBar"
android:configChanges="keyboard|keyboardHidden|orientation"
android:label="State preserving implementation"/>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
There are 3 points must be done. This is a full solution for me.
AndroidManifest.xml need config both orientation and screenSize in android:configChanges for target activity
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.skatetube.skatetube">
<application
<activity android:name=".WebViewActivity"
android:configChanges="orientation|screenSize">
</activity>
</application>
</manifest>
Need to override onSaveInstanceState and onRestoreInstanceState of Activity to make state can be restore when rotated
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
mWebView.restoreState(savedInstanceState);
}
Not loading URL again when screen rotate, use savedInstanceState to know current status in onCreate() of target activity
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
mWebView = (WebView) findViewById(R.id.webView_h5);
if (savedInstanceState == null) {
mWebView.loadUrl(url);
}
}
Miss any one of those three, my activity still reload.
All you need to do is Override onSaveInstanceState and onRestoreInstanceState.
#Override
protected void onSaveInstanceState(Bundle outState ){
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
mWebView.restoreState(savedInstanceState);
}
and one other solution could be to update your Activity tag in manifest to
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
well no need of java code just copy this code in place of your activity tag in Manifest.xml
<activity
android:name=".SkateTube"
android:theme="#style/AppTheme.NoActionBar"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:label="State preserving implementation"/>
Related
I created a simple example application that creates a button in MainActivity to call the SecondActivity.
The application works well.
But I found something strange.
If I press the home key to go outside and run the launcher of the application, it returns to Main Activity, not SecondActivity.
Through a search, I got the following guide:
Intent intent = new Intent(MainActivity.this, SecondMainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); //<- add option
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //<- add option
startActivity(intent);
This confirmed that the Activity was maintained as I wanted.
However, when using the back key, the application program ended without returning to MainActivity!
The questions I want to ask are as follows.
How to maintain SecondActivity when I press the home key to go outside and run the program again without terminating the program in SecondActivity.
How to return to Main Activity when I press the back key in Second Activity.
I hope 1) and 2) will be satisfied at once.
Source code is as follows
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication2">
<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=".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=".SecondMainActivity"
android:label="SecondMainActivity"></activity>
</application>
</manifest>
MainActivity
package com.example.myapplication2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button GoToNewActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GoToNewActivity = (Button)findViewById(R.id.button1);
GoToNewActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent code for open new activity through intent.
Intent intent = new Intent(MainActivity.this, SecondMainActivity.class);
// //[1]
// //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//
// //[2]
// intent.addFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
}
}
SecondMainActivity
package com.example.myapplication2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class SecondMainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second_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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can download the application source.
1.If you going to home screen that because of your app is restarting
android system clear memory automatically after some time.
2.You don't need "intent.flag" tags , just start the activity and as Gunesh Shanbhag said in comment activity are arranged in stack. You
don't need to write code for that is automatic process but you can
ovveride the onbackpressed method to do something else like press
back button twice to exit the app.
I'm working on a university project for blind people who use Android phones (a Braille Keyboard) .
So i need disable talkback when user use the keyboard and then enable it again. (for using multitouch on the screen). So I created a new sample simple project for android 8.0, empty activity and I added a couple things.
My sample android manifest:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<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=".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>
And my simple MainActivity:
package com.jaime.prueba;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
updateTalkBackState(true);
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();
}
});
}
private static final String TALKBACK_SERVICE_NAME = "com.google.android.marvin.talkback/.TalkBackService";
private void updateTalkBackState(boolean enableTalkBack) {
if (enableTalkBack) {
enableAccessibilityService(TALKBACK_SERVICE_NAME);
} else {
disableAccessibilityServices();
}
}
private void enableAccessibilityService(String name) {
Settings.Secure.putString(getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, name);
Settings.Secure.putString(getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED, "1");
}
private void disableAccessibilityServices() {
Settings.Secure.putString(getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, "");
Settings.Secure.putString(getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED, "0");
}
#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
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
So...
Firstly: I checked this answer: https://stackoverflow.com/a/44461236/10802519
// It's not possible to turn TalkBack on or off from within your app unless you have been granted the system permission WRITE_SECURE_SETTINGS (via ADB) by the user.
private static final String TALKBACK_SERVICE_NAME = "com.google.android.marvin.talkback/.TalkBackService";
private void updateTalkBackState(boolean enableTalkBack) {
if (enableTalkBack) {
enableAccessibilityService(TALKBACK_SERVICE_NAME);
} else {
disableAccessibilityServices();
}
}
private void enableAccessibilityService(String name) {
Settings.Secure.putString(getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, name);
Settings.Secure.putString(getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED, VALUE_ENABLED);
}
private void disableAccessibilityServices() {
Settings.Secure.putString(getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, "");
Settings.Secure.putString(getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED, VALUE_DISABLED);
}
Secondly: In my Terminal I typed:
adb shell pm grant com.jaime.prueba android.permission.WRITE_SECURE_SETTINGS
Thirdly: But I got the following:
java.lang.SecurityException: Package com.jaime.prueba has not requested permission android.permission.WRITE_SECURE_SETTINGS
at com.android.server.pm.permission.BasePermission.enforceDeclaredUsedAndRuntimeOrDevelopment(BasePermission.java:379)
at com.android.server.pm.permission.PermissionManagerService.grantRuntimePermission(PermissionManagerService.java:1404)
at com.android.server.pm.permission.PermissionManagerService.access$900(PermissionManagerService.java:89)
at com.android.server.pm.permission.PermissionManagerService$PermissionManagerInternalImpl.grantRuntimePermission(PermissionManagerService.java:2093)
at com.android.server.pm.PackageManagerService.grantRuntimePermission(PackageManagerService.java:5411)
at com.android.server.pm.PackageManagerShellCommand.runGrantRevokePermission(PackageManagerShellCommand.java:1730)
at com.android.server.pm.PackageManagerShellCommand.onCommand(PackageManagerShellCommand.java:217)
at android.os.ShellCommand.exec(ShellCommand.java:103)
at com.android.server.pm.PackageManagerService.onShellCommand(PackageManagerService.java:21330)
at android.os.Binder.shellCommand(Binder.java:634)
at android.os.Binder.onTransact(Binder.java:532)
at android.content.pm.IPackageManager$Stub.onTransact(IPackageManager.java:2821)
at com.android.server.pm.PackageManagerService.onTransact(PackageManagerService.java:3856)
at android.os.Binder.execTransact(Binder.java:731)
Fourthly I build my app on Android Studio, Everything fine, nothing red, so I run the app on my phone... and my app does not open, it does not work.
I hope my question is understandable. Let me know, if my questions need something more -First question, and in foreign language- Thank you!
Notice in manifest file:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
but in terminal you input:
adb shell pm grant com.jaime.prueba android.permission.WRITE_SECURE_SETTINGS
WRITE_SETTINGS and WRITE_SECURE_SETTINGS are two different permissions.
and about WRITE_SECURE_SETTINGS, you could read this post.
I have a problem when opening a new activity, when clicking on element 0 sends me the activity but this does not show the content and does not send me some error, and adds the new activity in androidManifest.xml.
I will leave my code:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ivann.diuxgridmain" >
<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=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".leon">
</activity>
</application>
</manifest>
MainActivity.java
package com.example.ivann.diuxgridmain;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
GridView androidGridView;
String[] gridViewString = {
"Leon1", "Ave1", "Perro1", "Cara1", "Corazòn1", "Enojado1",
"Leon2", "Ave2", "Perro2", "Cara2", "Corazòn2", "Enojado2",
"Leon3", "Ave3", "Perro3", "Cara3", "Corazòn3", "Enojado3",
} ;
int[] gridViewImageId = {
R.drawable.leon, R.drawable.bird, R.drawable.cachorro, R.drawable.fb, R.drawable.heart, R.drawable.angry,
R.drawable.leon, R.drawable.bird, R.drawable.cachorro, R.drawable.fb, R.drawable.heart, R.drawable.angry,
R.drawable.leon, R.drawable.bird, R.drawable.cachorro, R.drawable.fb, R.drawable.heart, R.drawable.angry,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomGridViewActivity adapterViewAndroid = new CustomGridViewActivity(MainActivity.this, gridViewString, gridViewImageId);
androidGridView=(GridView)findViewById(R.id.grid_view_image_text);
androidGridView.setAdapter(adapterViewAndroid);
androidGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int i, long id) {
Intent intent=null;
switch (i){
case 0:
// I think here is the error *******
intent = new Intent(MainActivity.this, leon.class);
startActivity(intent);
break;
}
Toast.makeText(MainActivity.this, "GridView Item: " + gridViewString[+i ], Toast.LENGTH_LONG).show();
}
});
}
}
leon.java
package com.example.ivann.diuxgridmain;
import android.app.Activity;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
/**
* Created by ivann on 09/06/2017.
*/
public class leon extends Activity {
#Override
public void onCreate(Bundle savedInstanceState, #Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.leonactividad);
}
}
just remove
this
#Override
public void onCreate(Bundle savedInstanceState, #Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.leonactividad);
}
with
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.leonactividad);
}
Because you use also PersistableBundle in onCreate method and PersistableBundle use from API Level 21. So you can replace onCreate method as below:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.leonactividad);
}
Button or ImageButton has a higher priority level than itemView. If your item view contains those, it might be the reason, and you can use TextView/ImageView instead.
I builded an app with simply webview and mDrawer slide menu. But after seeing that it's not working on > 3 android i have added a support library and made some changes but it's still not working.
here is the code
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
#SuppressLint("NewApi")
public class MainActivity extends ActionBarActivity {
private LayoutInflater mInflater;
private DrawerLayout mDrawerLayout;
WebView browser;
// ListView represents Navigation Drawer
private ListView mDrawerList;
// ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar
private ActionBarDrawerToggle mDrawerToggle;
private String mTitle = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView browser = (WebView) findViewById(R.id.webView1);
browser.loadUrl("");
browser.setWebViewClient(new WebViewClient());
WebSettings webSettings = browser.getSettings();
webSettings.setJavaScriptEnabled(true);
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting reference to the ActionBarDrawerToggle
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle("Menu");
invalidateOptionsMenu();
}
};
browser.setOnKeyListener(new OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if(event.getAction() == KeyEvent.ACTION_DOWN)
{
WebView webView = (WebView) v;
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack())
{
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(),
R.layout.drawer_list_item, getResources().getStringArray(R.array.menus));
// Setting the adapter on mDrawerList
mDrawerList.setAdapter(adapter);
// Enabling Home button
getSupportActionBar().setHomeButtonEnabled(true);
// Enabling Up navigation
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Getting an array of rivers
String[] menuItems = getResources().getStringArray(R.array.menus);
// Currently selected river
mTitle = menuItems[position];
// Creating a fragment object
// Passing selected item information to fragment
Bundle data = new Bundle();
data.putInt("position", position);
data.putString("url", getUrl(position));
// Getting reference to the FragmentManager
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.addOnBackStackChangedListener(new OnBackStackChangedListener() {
public void onBackStackChanged() {
if(getSupportFragmentManager().getBackStackEntryCount() == 0)
finish();
}
});
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
// Committing the transaction
ft.commit();
// Closing the drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
});
}
I have tried to change getActionBar() to getSupportActionBar() but i got next error:
The method getSupportActionBar() is undefined for the type new ActionBarDrawerToggle(){}
Logcat:
04-03 14:39:29.237: E/AndroidRuntime(687): FATAL EXCEPTION: main
04-03 14:39:29.237: E/AndroidRuntime(687): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.com/com.example.com.MainActivity}: java.lang.ClassNotFoundException: com.example.com.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.com-2.apk]
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.com"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.com.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>
</application>
</manifest>
If you have not added these two functions in your code, then add it and try. It will work.
#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);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return false;
}
I've tried to develop my own app but now that i wanna see how it looks on my phone it says "Appname has stopped". Im installing the app via dropbox.
Here's a copy of the MainActivity.java
package com.example.aikk;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mBtn1 = (Button) findViewById(R.id.northpowerramsor);
mBtn1.setOnClickListener((OnClickListener) 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.main, menu);
return true;
}
/** Called when the user clicks the Send button */
public void onClick(View view) {
Log.i("clicks","You Clicked B1");
Intent i=new Intent(MainActivity.this, Ramsor.class);
startActivity(i);
// Do something in response to button
}
}
And here's a copy of Ramsor.java
public class Ramsor extends Activity {
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_Ramsor);
//Vettefan var det här är till med när jag skulle göra quick fix på den kom jag till nån knas layout sida
// Make sure we're running on Honeycomb or higher to use ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
And the Android.Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.aikk"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="1"
android:targetSdkVersion="19"
android:maxSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.aikk.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="com.example.aikk.Ramsor"
android:label="#string/title_activity_ramsor"
android:parentActivityName="com.example.AIKK.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.AIKK.MainActivity" /> >
</activity>
</application>
</manifest>
Any thoughts would be GREATLY appreciated!
The problem is here , you are trying to cast the activity(this) to OnClickListener
mBtn1.setOnClickListener((OnClickListener) this);
The solution is to make your activity implements OnClickListener and create the unimplemented method
public class MainActivity extends Activity {
should be
public class MainActivity extends Activity implements OnClickListener {
There can be other reasons for the crash as well in which case it is better you post the stacktrace.
You can do as below using annonymous inner class
mBtn1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// do something
}
});
Change your class definition to implement OnClickListener:
public class MainActivity extends Activity implements OnClickListener {
...and set the click listener on mBtn1 as follows:
mBtn1.setOnClickListener(this);
try below this instead of mBtn1.setOnClickListener((OnClickListener) this);
mBtn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// Activity to do onclick .
}
});
return true;