An error showing incompatible types Android widget toolbar cannot be converted in Java compiler while working on Android Studio.
Toolbar toolbar = (Toolbar)findViewById(R.id.toolBar);
toolbar.setTitle("GPS PRESENCE SYSTEM");
setSupportActionBar(toolbar);
Error: incompatible types: android.widget.Toolbar cannot be converted
to androidx.appcompat.widget.Toolbar
Try to replace this:
import android.widget.Toolbar;
With this:
import androidx.appcompat.widget.Toolbar;
By the way, if you are using androidx. Run it's migration process.
The android support libraries will not be supported in the future.
You can read about it here:
AndroidX
Migrating to AndroidX
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar); //No Problerm
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
we must import androidx.appcompat.widget.Toolbar;
don't import android.widget.Toolbar;
This error because your Toolbar created using android.widget.Toolbar .
But you are using androidX.
This also a same kind of error.
java.lang.ClassCastException: androidx.appcompat.widget.Toolbar cannot be cast to android.widget.Toolbar
To solve this kind of you can add these to lines in to your MainActivity.java file (to import).
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
Make sure to remove or comment out this android.widget.Toolbar .
Then again check for error like this. because sometime you may have to import more.
AndroidX is the new and improved support library
import androidx.appcompat.widget.Toolbar;
you can check more about from here here
Androidx's toolbar is designed for backwards compatibility while
android.widget.Toolbar
is the current plattform type
You are using androidx and Android both at the same time. That is throwing an error. Either use androidx or use android appcompat.
Change your activity toolbar import to:
import android.support.v7.widget.Toolbar;
You can invoke ActivityCompat#requireViewById which allows to omit the type cast and returns a #NonNull Toolbar reference:
Toolbar toolbar = ActivityCompat.requireViewById(this, R.id.toolbar);
setSupportActionBar(toolbar);
The title can be set on the #Nullable ActionBar reference returned by AppCompatActivity#getSupportActionBar:
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle("GPS PRESENCE SYSTEM");
}
simply delete
import android.widget.Toolbar;
and add
import androidx.appcompat.widget.Toolbar;
As reported by everyone else
import android.widget.Toolbar
is creating the issue.
Replace it with
import androidx.appcompat.widget.Toolbar
Mostly on android's recommendation we go for the tool and don't notice the android or androidx dependability.
That causes this error.
Related
I am learning Kotlin and recently have jumped upon a certain problem. As soon as I click on any button in my app, I get a similar error as shown in the title. Here's the complete error code
java.lang.IllegalStateException: Could not find method buRequestEvent(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'buRequest'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:423)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:380)
at android.view.View.performClick(View.java:5646)
at android.view.View$PerformClick.run(View.java:22473)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
I have tried a lot of fixes given on other questions but most of them are in Java and I am programming in Kotlin. None of them have worked yet.
Here's the code of one of the buttons
from MainActivity.kt
protected fun buRequestEvent(view: View){
var userEmail = etEmail.text.toString()
myRef.child("Users").child(splitString(userEmail)).child("Request").push().setValue(myEmail)
}
I have a rough idea that the problem might be due to the imports in my project file so here's the list of the imports
from MainActivity.kt
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
import kotlin.collections.HashMap
P.S. - I have checked the XML file, the button has an onClick attribute added to it
from activity_main.xml
<Button
android:id="#+id/buRequest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="buRequestEvent"
android:text="REQUEST" />
The issue is , the onclick method should have public access modifier, so use
public fun buRequestEvent(view: View){
var userEmail = etEmail.text.toString()
myRef.child("Users").child(splitString(userEmail)).child("Request").push().setValue(myEmail)
}
From docs
Be public // violation here
Return void
Define a View as its only parameter (this will be the View that was clicked)
I'm dipping my toes into Android Development by following along examples from this book. I am unable to get the example below to work, though. Instructions are: 1) New project named Dialog 2) Empty Activity 3) Paste/edit to look like the code below.
The message is that Studio can't resolve: R.id.toolbar, R.id.fab, R.menu, and R.id.action_settings.
I'm running Android Studio 3.1.3 on macOS High Sierra. My best guess is that that either the instructions are missing steps or since the book is ~2 years old Android Studio has changed behavior causing this example to break. I don't know enough about this development process to even know how to start to diagnose this.
In AndroidManifest.xml add this line to the activity block:
android:theme="#style/Theme.AppCompat.Dialog"
And this is the only code file to change (DialogActivity.java) for the project:
package com.example.sample.dialog;
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;
public class DialogActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with an action",
Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_dialog, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_dialog.xml file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DialogActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
The reason you are getting those errors is because Java is looking for references in XML that have not been created. For example, it is looking for a reference called "R.id.fab" which was never created.
To fix this, you are going to have to go into the res folder and create the necessary files. Inside of the res -> layout -> "activity_dialog.xml" file, you will have to create a FAB in order to get rid of that error. You can copy/paste this code.
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"/>
Here, I create the necessary View in XML, and give it an id called fab so you can reference it in the java code. You will also need to create a menu folder and file, so to do that right click on the res folder, and go to "new Android Resource File". Set the file name to "menu" and the resource type should also be menu. Then when you hit "OK", you will see a new folder called menu, and inside of that a file called "menu.xml".
Inside that "menu.xml" file, you're going to have to create your menu options with an id of "action_settings". You can do that by using the code:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/action_settings" android:title="Settings"/>
</menu>
Lastly, you can create your toolbar by right clicking on the layout folder and selecting new layout resource file. You can name it 'toolbar', and set the root element to android.support.v7.widget.Toolbar. This will generate the appropriate code for you, and you can edit it however you'd like. After that go back into the "activity_dialog.xml" file and use this code:
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
This should get rid of all 4 errors
Double check the id's in the R.layout.activity_dialog file. Android studio will output that message when the id that you are looking for is not found in the inflated layout.
EDIT:
You do not have a Toolbar declared in your XML file. When you want to search for a layout element to use in a Fragment or Activity, you use the id parameter you set in the XML file. If you forget to set the id or use the wrong id, it will tell you that the symbol cannot be resolved. There are too many items to add to your code, but follow the links below and you'll pick it up quickly enough. Let me know if you need more information. Also, CodePath is an excellent resource that I heavily relied on when I started learning Android development.
Look at this for a tutorial for adding a toolbar to a layout file and this for more miscellaneous information.
You have not gotten a reference to the view from the xml.
Get the reference from the xml for example if have a button defined in xml with an id of myBtn i would get the reference as Button button = findViewById(R.id.myBtn).
On the main menu, choose File. Invalidate Caches/Restart. The Invalidate Caches message appears informing you that the caches will be invalidated and rebuilt on the next start. Use buttons in the dialog to invalidate caches.
My code below works when placed in a class extending Activity class but addRule gives compile error saying it is undefined when I am extending ActionBarActivity.
Error:
The method addRule(int) is undefined for the type ActionBar.LayoutParams
Question: What is the alternative to addRule(int) in RelativeLayout.LayoutParams in ActionBar.LayoutParams??
private void initializeSlidingLayer() {
LayoutParams myrlp = (LayoutParams) mySlidingLayer.getLayoutParams();
getResources().getDrawable(R.drawable.ic_launcher);
//for bottom
mySlidingLayer.setStickTo(SlidingLayer.STICK_TO_BOTTOM);
myrlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); //THIS LINE THROWS ERROR WITH ACTIONBARACTIVITY
myrlp.width = LayoutParams.MATCH_PARENT;
myrlp.height = getResources().getDimensionPixelSize(R.dimen.layer_width);
//Adding Shadow
mySlidingLayer.setShadowWidthRes(R.dimen.shadow_width);
mySlidingLayer.setShadowDrawable(R.drawable.sidebar_shadow);
//mSlidingLayer.setOffsetWidth(0);
mySlidingLayer.setOffsetWidth(getResources().getDimensionPixelOffset(R.dimen.offset_width));
}
Probably not relevant to the question, but I am trying to this SlidingLayer Library
Are you sure action bar uses a relative layout? If not, then you can't treat it as a relative layout layout params and can ONLY use the base layoutParams functions
I hate to answer my own questions - but I just thought of something to try (that worked) after I hit Submit.
Instead of importing:
import android.app.ActionBar.LayoutParams;
I needed to import:
import android.widget.RelativeLayout.LayoutParams;
I am still able to import extend ActionBarActivity.
I would like to remove ActionBarSherlock from my application and replace it with the standard ActionBarCompat.
How do I implement ActionBarCompat?
How do I migrate the Activites?
Which imports replace the ActionBarSherlock imports?
What are typical problems?
I did some migrating and wrote down all the issues I encountered. None were serious but took time to research. I was able to migrate a quite big application in a couple hours after knowing all this. May this help to speed up migration process.
How do I convert from ActionBarSherlock to ActionBarCompat?
Note: Since the Support Library's v22.1.0, the class ActionBarActivity is deprecated. You should use AppCompatActivity instead. Read here for more information: What's the enhancement of AppCompatActivity over ActionBarActivity?
== Switch the libraries ==
Go to app properties and remove ActionBarSherlock and add ActionBarCompat instead. This requires the v7 appcompat library to be present, see http://developer.android.com/tools/support-library/setup.html for details. Follow the instructions precisely, ActionBarCompat needs to be a library project.
Parallel does not work (easily) as a lot of attributes are in both libraries.
Do not be discouraged by hundreds of errors after replacing the libraries. The vast majority goes away automatically.
== Fix XML errors ==
First thing is to fix all XML errors to allow compiling and find other errors.
Replace the sherlock theme with ActionBarCompat Theme, e.g.
<style name="AppBaseTheme" parent="#style/Theme.AppCompat.Light.DarkActionBar">
Remove double attr, e.g. <attr name="buttonBarStyle" format="reference" />.
For now remove all your individual action bar styles. See further down how to handle these.
== Fix build errors ==
Pick the easiest activities first. ActionBarCompat does not distinguish Activity and FragmentActivity, both are now ActionBarActivity.
Remove the ActionBarSherlock imports and extend to ActionBarActivity (import android.support.v7.app.ActionBarActivity;)
After saving, this should dramatically reduce errors in the activity.
Fix the errors around the menues first and disregard fragment errors for now, they should be going away later.
== Replacements ==
Imports:
import com.actionbarsherlock.app.SherlockActivity; -> import android.support.v7.app.ActionBarActivity;
import com.actionbarsherlock.app.SherlockFragmentActivity; -> import android.support.v7.app.ActionBarActivity;
import com.actionbarsherlock.app.SherlockFragment; -> import android.support.v4.app.Fragment;
import com.actionbarsherlock.app.SherlockListFragment; -> import android.support.v4.app.ListFragment;
import com.actionbarsherlock.app.SherlockListActivity; -> import android.support.v7.app.ActionBarActivity; (see ListActivity / SherlockListActivity)
import com.actionbarsherlock.view.Menu; -> import android.view.Menu;
import com.actionbarsherlock.view.MenuItem; -> import android.view.MenuItem;
import com.actionbarsherlock.view.MenuInflater; -> import android.view.MenuInflater;
import com.actionbarsherlock.view.Window; -> import android.view.Window;
import com.actionbarsherlock.widget.SearchView; -> import android.support.v7.widget.SearchView;
import com.actionbarsherlock.widget.SearchView.OnQueryTextListener -> import android.support.v7.widget.SearchView.OnQueryTextListener;
Code Replacements:
SherlockActivity -> ActionBarActivity
SherlockFragmentActivity -> ActionBarActivity
SherlockListActivity -> ListActivity (see ListActivity / SherlockListActivity)
SherlockListFragment -> ListFragment;
getSupportMenuInflater -> getMenuInflater
getSherlockActivity() -> getActivity()
com.actionbarsherlock.widget.SearchView.OnQueryTextListener() -> OnQueryTextListener (see SearchView)
m.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); -> MenuItemCompat.setShowAsAction(m, MenuItem.SHOW_AS_ACTION_ALWAYS);
Typical Code changes for ActionBarCompat
getActionBar() -> getSupportActionBar()
invalidateOptionsMenu() -> supportInvalidateOptionsMenu()
== Fragment ==
The fragment does not cater for ActionBarCompat functionality. This is a problem when trying to call getSupportActionBar.
This can be solved by using the onAttach method:
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((ActionBarActivity)activity).getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
Usually this is better controlled in the FragmentActivity.
== SearchView ==
This turned out to be a bit of a hassle.
Replace something like this:
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
with
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
You also have to adjust your menu:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/action_search"
android:actionViewClass="com.actionbarsherlock.widget.SearchView"
android:icon="#android:drawable/ic_menu_search"
android:orderInCategory="80"
android:showAsAction="always|collapseActionView"
android:title="#string/action_search"/>
</menu>
with
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >
<item
android:id="#+id/action_search"
android:icon="#android:drawable/ic_menu_search"
android:orderInCategory="80"
android:title="#string/action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always|collapseActionView"/>
</menu>
app: needs to be defined to have compatibility with android versions before 11.
SearchView needs to be support class v7.
== ListActivity / SherlockListActivity ==
The ListActivity is not supported ActionBarCompat, therefore the crucial functions of the ListActivity need to be implemented manual, which is rather simple:
private ListView mListView;
protected ListView getListView() {
if (mListView == null) {
mListView = (ListView) findViewById(android.R.id.list);
}
return mListView;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
} else {
return adapter;
}
}
== Styles ==
A styled action bar can be achieved, see original google posting:
http://android-developers.blogspot.de/2013/08/actionbarcompat-and-io-2013-app-source.html
A styled searchView box is more difficult:
This works:
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
SearchView.SearchAutoComplete theTextArea = (SearchView.SearchAutoComplete) searchView.findViewById(R.id.search_src_text);
theTextArea.setTextColor(getResources().getColor(R.color.yourColor));
See these posts:
Changing the cursor color in SearchView without ActionBarSherlock
Change appcompat's SearchView text and hint color
== Example ==
Google Navigation Drawer with Action Bar Sherlock includes all original code (now aiming to support library) and formatting. Only some attributes had to be replaced with similar ones as they are only available from v11 onwards.
Download at: https://github.com/GunnarBs/NavigationDrawerWithActionBarCompat
== See also ==
http://android-developers.blogspot.de/2013/08/actionbarcompat-and-io-2013-app-source.html
http://developer.android.com/reference/android/support/v7/app/ActionBar.html
http://www.grokkingandroid.com/migrating-actionbarsherlock-actionbarcompat/
It is worth mentioning that there is no support version of the PreferenceActivity, so if you are using SherlockPreferenceActivity, you need to refactor to a support PreferenceFragment.
More info: How to add Action Bar from support library into PreferenceActivity?
For some reason, the "id" in the argument is underlined in red and is "not resolved and or not a field"
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.os.Bundle;
import android.widget.Button;
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button toggleButton = (Button)findViewById(R.id.toggleButton);
toggleButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
}
}
Check your gen[Generated Java Files] folder in package explorer.
It may be empty, try
Project --> Clean
This will Generate files
Hope This Helps
It is one of the problems everyone faces with EclipseIDE.
Clean your project and build it once again.
P.S. : Also make sure that the id of the Button in your mail.xml is android:id="#+id/toggleButton"
It is a problem faced in eclipse IDE. I had this problem
When there was an error in one of my xml files
When the package definition in my manifest file has changed
When my generated file is in another package.
Check if any of the above is your problem. May be it will help
Cleaning and building the project might also help you
Just Click on Build Button (Green Hammer).
//Done