I know this has been asked a lot, already have done search on this particular topic. and all of them returns the same answer but doesn't solve my problem, I have a button created on separate xml, used as a fragment. TabbedActivity just wont fire up, App is crashing when button is clicked, even throws NPE on first code used. just don't know what to do.
import android.content.Intent;
import android.content.res.Configuration;
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;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set HomeFragment as user starts the app.
if (savedInstanceState == null){
InitStartFrag();
}
//-----BUG!-----//
1st:Code Used
android.support.v7.widget.AppCompatButton myButton = (android.support.v7.widget.AppCompatButton)findViewById(R.id.myButton);
myButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent intent = new Intent(MainActivity.this, TabbedActivity.class);
startActivity(intent);
}
});
2nd Code:
public void doThis(View view){
Intent intent = new Intent(this, TabbedActivity.class);
MainActivity.this.startActivity(intent);
}
3rd Code:
public void doThis(View view){
setContentView(R.layout.activity_tabbed);
}
//-----Bug Ends-----//
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void InitStartFrag() {
android.app.FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
.....
.....
}
The Log Cat:
Process: com.my_app.app_one, PID: 3799
java.lang.IllegalStateException: Could not find a method doThis(View) in the activity class android.support.v7.widget.TintContextWrapper for onClick handler on view class android.support.v7.widget.AppCompatButton with id 'myButton'
at android.view.View$1.onClick(View.java:3843)
at android.view.View.performClick(View.java:4471)
at android.view.View$PerformClick.run(View.java:18778)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5324)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NoSuchMethodException: doThis [class android.view.View]
at java.lang.Class.getConstructorOrMethod(Class.java:472)
at java.lang.Class.getMethod(Class.java:864)
at android.view.View$1.onClick(View.java:3836)
at android.view.View.performClick(View.java:4471)
at android.view.View$PerformClick.run(View.java:18778)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5324)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
The Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my_app.app_one">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:configChanges="keyboardHidden|orientation"
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=".TabbedActivity"
android:label="#string/title_activity_tabbed"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.my_app.app_one.MainActivity" />
</activity>
</application>
</manifest>
The XML, used as Fragment : buttons_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.percent.PercentRelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--Upper Buttons-->
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:text="Fire"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn1"
android:textColor="#color/colorBtnText1"
android:drawableStart="#drawable/fire_icon"
android:drawablePadding="-62dip"
android:paddingLeft="30dip"
android:paddingRight="26dip"
android:singleLine="true"
android:gravity="center"
android:onClick="doThis"/>
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton1"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_below="#id/myButton"
android:text="Flood"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn3"
android:textColor="#color/colorBtnText3"/>
<!-- Divider -->
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton2"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_toEndOf="#id/myButton1"
android:text="Thunder"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn2"
android:textColor="#color/colorBtnText2"/>
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton4"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_below="#id/myButton2"
android:layout_gravity="center_horizontal"
android:layout_toEndOf="#id/myButton1"
android:text="Civil Defense Operation Center"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn4"
android:textColor="#color/colorBtnText4"/>
<!--Lower Buttons-->
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton5"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_below="#id/myButton3"
android:text="Landslide"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn5"
android:textColor="#color/colorBtnText5"/>
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton7"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_below="#id/myButton5"
android:text="Women and Children Protection Center"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn7"
android:textColor="#color/colorBtnText7"/>
<!-- Divider -->
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton6"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_below="#id/myButton4"
android:layout_toEndOf="#id/myButton3"
android:text="Storm"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn6"
android:textColor="#color/colorBtnText6"/>
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton8"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_below="#id/myButton6"
android:layout_gravity="center_horizontal"
android:layout_toEndOf="#id/myButton5"
android:text="Earthquake"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn8"
android:textColor="#color/colorBtnText8"/>
</android.support.percent.PercentRelativeLayout>
</LinearLayout>
New Code Used:
private void InitBtnListener(){
LayoutInflater layoutInflater = this.getLayoutInflater();
View view = layoutInflater.inflate(R.layout.buttons_layout,null);
android.support.v7.widget.AppCompatButton myButton = (android.support.v7.widget.AppCompatButton)view.findViewById(R.id.myButton);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, TabbedActivity.class);
startActivity(intent);
}
});
}
TabbedFragment.java Code
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
public class TabbedFragment extends Fragment implements OnClickListener {
View myView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.survival_tips_layout,container,false);
android.support.v7.widget.AppCompatButton myButton = (android.support.v7.widget.AppCompatButton)myView.findViewById(R.id.myButton);
myButton.setOnClickListener(this);
return myView;
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.myButton:
//--Missing Code:--//
After Btn Click Fire up that TabbedActivity.
//--Ends--//
// Can I do intents Here?
Intent intent = new Intent(MainActivity.this,TabbedActivity.class);
startActivity(intent);
break;
}
}
}
This line needs to be above any findViewById
setContentView(R.layout.activity_main);
If the android:onClick is defined from the XML, you need a public method that accepts a View parameter with that name.
For example, android:onClick="doThis" means you need this method
public void doThis(View view) {
// TODO: Handle click
}
i have a button created on separate xml, used as a fragment
Then you need to find that button from the Fragment class. You can't find it from the Activity.
For example
public class MyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
// Inflate the layout
View rootView = inflater.inflate(R.layoutbuttons_layout, parentViewGroup, false);
Button button = (Button) rootView.findViewById(R.id.button);
// TODO: button.setOnClickListener();
return rootView;
}
// OR... if you have android:onclick="doThis"
public void doThis(View view) {
// TODO: Handle click
}
}
Related
I'm receiving an InflateException from ChatActivity when it is not the LAUNCHER activity but when I change the manifest such that ChatActivity is the LAUNCHER, the app work properly.
I'm probably missing something, is there something missing in the code?
Update 18:15 16.10 -
I've found that if I delete
implements View.OnClickListener
from LoginActivity the app working (but now I don't have buttons).
What is the cause of this problem and how can it be fixed?
Part of the MANIFEST when the error accrue -
<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=".Activities.LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Activities.ChatMainActivity"></activity>
<activity android:name=".Activities.RegisterActivity" />
And if I'm changing the file to this (below) the chat work properly -
<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=".Activities.LoginActivity"></activity>
<activity android:name=".Activities.ChatMainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Activities.RegisterActivity" />
The dependencies -
implementation 'androidx.appcompat:appcompat:1.0.0'
implementation 'com.google.android.material:material:1.0.0'
XML file of ChatActivity -
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".Activities.ChatMainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/appBarLayout">
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
</androidx.appcompat.widget.Toolbar>
<com.google.android.material.tabs.TabLayout
android:id="#+id/main_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"></com.google.android.material.tabs.TabLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/main_tabPager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/appBarLayout">
</androidx.viewpager.widget.ViewPager>
</RelativeLayout>
The activity -
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import androidx.appcompat.widget.Toolbar;
import com.google.android.material.tabs.TabLayout;
import com.nirkov.hive.Fragments.ChatFragment;
import com.nirkov.hive.Fragments.ChatOffersFragment;
import com.nirkov.hive.Fragments.ChatRequestsFragment;
import com.nirkov.hive.R;
public class ChatMainActivity extends AppCompatActivity {
private ViewPager mViewPager;
private SectionsPagerAdapter mSectionsPagerAdapter;
private TabLayout mTabLayout;
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_main);
mToolbar = (Toolbar) findViewById(R.id.main_app_bar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Chat");
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.main_tabPager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mTabLayout = (TabLayout) findViewById(R.id.main_tabs);
mTabLayout.setupWithViewPager(mViewPager);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.chat_bar_layout, menu);
return true;
}
#Override
public void onStart() {
super.onStart();
}
private class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(final int position) {
switch (position){
case 0:
return new ChatRequestsFragment();
case 1:
return new ChatFragment();
case 2:
return new ChatOffersFragment();
}
return null;
}
#Override
public int getCount() {
return 3;
}
public CharSequence getPageTitle(final int position){
switch(position){
case 0:
return "REQUESTS";
case 1:
return "CHATS";
case 2:
return "OFFERS";
}
return null;
}
}
}
The appTheme style -
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
The LoginActivity -
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.nirkov.hive.R;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "LoginActivity";
private Button loginButton;
private EditText emailBox, passwordBox;
private TextView registerHereLink;
private FirebaseAuth mAuth;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginButton = (Button) findViewById(R.id.loginButton);
emailBox = (EditText)findViewById(R.id.emailBox);
passwordBox = (EditText)findViewById(R.id.passwordBox);
registerHereLink = (TextView)findViewById(R.id.registerHereLink);
progressBar = (ProgressBar) findViewById(R.id.loginProgressBar);
mAuth = FirebaseAuth.getInstance();
loginButton.setOnClickListener(this);
registerHereLink.setOnClickListener(this);
}
#Override
public void onStart() {
super.onStart();
if(mAuth.getCurrentUser() != null){
startActivity(new Intent(this, ChatMainActivity.class));
}
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.loginButton:
String email = emailBox.getText().toString();
String password = passwordBox.getText().toString();
loginButton.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
signIn(email, password);
break;
case R.id.registerHereLink:
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
break;
}
}
private void signIn(String email, final String password){
mAuth.signInWithEmailAndPassword(email, password).
addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Log.d(TAG, "signIn : success");
startActivity(new Intent(LoginActivity.this, MainActivity.class));
}else{
Log.w(TAG, "signIn:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
loginButton.setVisibility(View.VISIBLE);
}
});
}
}
The Login XML file -
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".Activities.LoginActivity">
<TextView
android:id="#+id/email"
android:layout_width="255dp"
android:layout_height="34dp"
android:layout_marginStart="20dp"
android:layout_marginTop="32dp"
android:text="Email:"
android:textSize="24sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/emailBox"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:ems="10"
android:inputType="textPersonName"
android:text=""
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/email" />
<!--Password : text view and text box-->
<TextView
android:id="#+id/password"
android:layout_width="133dp"
android:layout_height="31dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="Password:"
android:textSize="24sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/emailBox" />
<EditText
android:id="#+id/passwordBox"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:ems="10"
android:inputType="textPersonName"
android:text=""
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/password" />
<Button
android:id="#+id/loginButton"
android:layout_width="115dp"
android:layout_height="37dp"
android:layout_marginStart="8dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="8dp"
android:text="Login"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/passwordBox" />
<ProgressBar
android:id="#+id/loginProgressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="38dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="#+id/spaceInBottom"
app:layout_constraintEnd_toEndOf="#+id/loginButton"
app:layout_constraintStart_toStartOf="#+id/loginButton"
app:layout_constraintTop_toTopOf="#+id/loginButton" />
<TextView
android:id="#+id/registerHereLink"
android:layout_width="63dp"
android:layout_height="12dp"
android:layout_gravity="center_horizontal"
android:layout_marginStart="8dp"
android:layout_marginTop="3dp"
android:layout_marginEnd="8dp"
android:text="Register Here"
android:textSize="10sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/loginButton" />
</androidx.constraintlayout.widget.ConstraintLayout>
The full error -
2019-10-16 01:07:43.323 6109-6109/com.nirkov.hive E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nirkov.hive, PID: 6109
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nirkov.hive/com.nirkov.hive.Activities.ChatMainActivity}: android.view.InflateException: Binary XML file line #9: Binary XML file line #9: Error inflating class android.support.design.widget.AppBarLayout
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: android.view.InflateException: Binary XML file line #9: Binary XML file line #9: Error inflating class android.support.design.widget.AppBarLayout
Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class android.support.design.widget.AppBarLayout
Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.design.widget.AppBarLayout" on path: DexPathList[[zip file "/system/framework/org.apache.http.legacy.boot.jar", zip file "/data/app/com.nirkov.hive-8a2GYMMALuvTn0Up_KEgfw==/base.apk"],nativeLibraryDirectories=[/data/app/com.nirkov.hive-8a2GYMMALuvTn0Up_KEgfw==/lib/x86, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.view.LayoutInflater.createView(LayoutInflater.java:606)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:555)
at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:161)
at com.nirkov.hive.Activities.ChatMainActivity.onCreate(ChatMainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
upload login Activity code as well , and tell me which is your parent class
Can you try adding
<item name="windowNoTitle">true</item>
to your main style and see if that works?
Didn't find class "android.support.design.widget.AppBarLayout" on path
Comes from your activity where you set the toolbar wrongly:
mToolbar = (Toolbar) findViewById(R.id.main_app_bar);
setSupportActionBar(mToolbar);
Your toolbar is wrapped by com.google.android.material.appbar.AppBarLayout.
So there's no need to add it into the supportActionBar.
Just define your activity theme as NoActionBar (in your styles.xml) and delete setSupportActionBar(mToolbar); in your activity
I have an issue that I can't seem to solve.
I have an activity with a list fragment (landscape and portrait) and an addItem fragment.
There is a FloatingActionButton on the Activity, but I can't seem to figure out how to set up its onClickListener.
The getViewById always returns null so the setOnClickListener has no object to call from. Why is this and how do I fix it?
Am I doing multiple fragments wrong and this is my problem?
Note: I left out the landscape fragment/layout for brevity's sake. It's the same as the portrait with a different id.
MainActivity.java
package tlw.app;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<String> activeFragments = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setContentView(R.layout.fragment_list);
FragmentManager fManager = getFragmentManager();
FragmentTransaction fTrans = fManager.beginTransaction();
Configuration configInfo = getResources().getConfiguration();
activeFragments.clear();
if(configInfo.orientation == Configuration.ORIENTATION_LANDSCAPE){
ListFragmentLand fragmentListLand = new ListFragmentLand();
fTrans.replace(R.id.main_container, fragmentListLand);
activeFragments.add("list_land");
} else {
ListFragment fragmentListPort = new ListFragment();
fTrans.replace(R.id.main_container, fragmentListPort);
activeFragments.add("list_port");
}
fTrans.commit();
if (activeFragments.contains("list_port") || activeFragments.contains("list_land")){
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fManager = getFragmentManager();
FragmentTransaction fTrans = fManager.beginTransaction();
activeFragments.clear();
ItemAddFragment fragmentAdd = new ItemAddFragment();
fTrans.replace(R.id.main_container, fragmentAdd);
activeFragments.add("add");
fTrans.commit();
}
});
}
}
}
activity_main.xml
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
<FrameLayout
android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.design.widget.CoordinatorLayout>
ListFragment.xml
package tlw.app;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ListFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list, container, false);
}
}
fragment_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="#+id/fragment_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="tlw.app.MainActivity"
tools:showIn="#layout/activity_main"
android:orientation="vertical">
<TextView
android:id="#+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="List Portrait"/>
</LinearLayout>
ItemAddFragment.java
package tlw.app;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ItemAddFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_add, container, false);
}
}
fragment_add.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_add"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/textView_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name:"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText_name"
/>
</LinearLayout>
</LinearLayout>
Please change this portion of the code in the MainActivity
FROM
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setContentView(R.layout.fragment_list);
TO
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Mistakes::
--Passing wrong xml instance::
--Trying to fetch the toolbar before the xml was actually set..
Please tell if more assistance needed
setContentView(R.layout.fragment_list);
This sets the layout used for your activity which does not have a FAB. Change this line to
setContentView(R.layout.activity_main);
In general, whenever findViewById() returns null, you need to be sure that the correct XML is loaded and that it contains the id you are trying to find.
Im getting error when i try to run the below activity.
The activity has a custom navigation drawer.
I'm new to android ....
The error is occuring at places where actionbar is involved.
Im getting error when i try to run the below activity.
The activity has a custom navigation drawer.
I'm new to android ....
The error is occuring at places where actionbar is involved.
Im getting error when i try to run the below activity.
The activity has a custom navigation drawer.
I'm new to android ....
The error is occuring at places where actionbar is involved.
Activity
import android.app.ActionBar;
import android.content.Context;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class HomeActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
DrawerLayout drawer_layout;
ListView drawer_list;
ActionBarDrawerToggle drawer_toggle;
ActionBar abar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
drawer_layout= (DrawerLayout) findViewById(R.id.drawer_layout);
drawer_list= (ListView) findViewById(R.id.drawer_list);
drawer_list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1));
drawer_list.setOnItemClickListener(this);
abar=getActionBar();
/*drawer_toggle = new ActionBarDrawerToggle(this, drawer_layout,
R.drawable.tick, R.string.app_name, R.string.app_name) {
*//** Called when a drawer has settled in a completely closed state. *//*
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle("Yuride");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
*//** Called when a drawer has settled in a completely open state. *//*
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle("Yuride");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};*/
abar.setHomeButtonEnabled(true);
abar.setDisplayHomeAsUpEnabled(true);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
class Myadapter extends BaseAdapter
{
Context context;
String[] drawer_items;
public Myadapter(Context context)
{
this.context=context;
drawer_items=context.getResources().getStringArray(R.array.drawer_items);
}
#Override
public int getCount() {
return drawer_items.length;
}
#Override
public Object getItem(int position) {
return drawer_items[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=null;
if(convertView==null)
{
LayoutInflater inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=inflater.inflate(R.layout.drawer_row,parent,false);
}
else
{
row=convertView;
}
ImageView drawer_icon= (ImageView) row.findViewById(R.id.drawer_icon);
TextView drawer_text= (TextView) row.findViewById(R.id.drawer_text);
drawer_text.setText(drawer_items[position]);
drawer_icon.setImageResource(R.drawable.tick);
return null;
}
}
}
xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<ListView
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:id="#+id/drawer_list">
</ListView>
</android.support.v4.widget.DrawerLayout>
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="in.yusoft.yuride.yuride">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".SplashActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Entrance" />
<activity android:name=".HomeActivity"></activity>
</application>
</manifest>
Error
java.lang.RuntimeException: Unable to start activity ComponentInfo{in.yusoft.yuride.yuride/in.yusoft.yuride.yuride.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setHomeButtonEnabled(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2622)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2683)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1440)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:6066)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:770)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:660)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setHomeButtonEnabled(boolean)' on a null object reference
at in.yusoft.yuride.yuride.HomeActivity.onCreate(HomeActivity.java:52)
at android.app.Activity.performCreate(Activity.java:6584)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2575)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2683)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1440)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:6066)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:770)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:660)
The problem is in setting up ActionBar.
Instead of
abar=getActionBar();
abar.setHomeButtonEnabled(true);
abar.setDisplayHomeAsUpEnabled(true);
Write in XML:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/MyMaterialTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/MyMaterialTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<ListView
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:id="#+id/drawer_list">
</ListView>
</android.support.v4.widget.DrawerLayout>
And in Java Class right after setContentView(R.layout.activity_home);:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if(getSupportActionBar()!=null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
I'm new to Android & was trying out the Bluetooth APIs of Google. Whenever I run my app on my phone, it crashes for some reason. I'm following the Google Developer's tutorial for the APIs & have made changes to my MainActivity.java & content.xml accordingly, but no use. Please have a look.
Here's my MainActivity.java
import android.content.Intent;
import android.content.Context;
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.bluetooth.*;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button btn;
private BluetoothAdapter BA = BluetoothAdapter.getDefaultAdapter();
private int REQUEST_ENABLE_BT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/* FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});*/
}
#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);
}
public void bluetoothDiscovery()
{
if(BA == null)
{
System.out.println("System Doesn't Support Bluetooth");
}
if(!BA.isEnabled())
{
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBTIntent,REQUEST_ENABLE_BT);
Toast.makeText(MainActivity.this,"Turned On!!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(MainActivity.this, "ALREADY ON", Toast.LENGTH_LONG).show();
}
}
}
Here's my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="vertex2016.mvjce.edu.bluetoothapptry">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here's my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
android:fitsSystemWindows="true"
tools:context="vertex2016.mvjce.edu.bluetoothapptry.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<!-- <android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email"
android:onClick="bluetoothDiscovery"/> -->
</android.support.design.widget.CoordinatorLayout>
Here's my content.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="vertex2016.mvjce.edu.bluetoothapptry.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BTButton"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="bluetoothDiscovery"/>
</RelativeLayout>
And here's my logcat
03-13 02:06:34.719 18759-18759/vertex2016.mvjce.edu.bluetoothapptry E/AndroidRuntime: FATAL EXCEPTION: main
Process: vertex2016.mvjce.edu.bluetoothapptry, PID: 18759
java.lang.IllegalStateException: Could not find method bluetoothDiscovery(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:307)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:266)
at android.view.View.performClick(View.java:4789)
at android.view.View$PerformClick.run(View.java:19881)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Thank you for your time
Your method bluetoothDiscovery must accept a parameter of type View, see View.onClick for reference.
public void bluetoothDiscovery(View v) {}
When this method is called, v will be the View object that was clicked.
i.e.
switch ( v.getId() ) {
case R.id.button:
// do something
break;
case R.id.other_button
// do something else
break;
}
Where r.id.button comes from your definition in XML,
android:id="#+id/button"
It is using this, you could have a single onClick method that is called by multiple buttons, each one with their own action.
You need a View parameter in your onClick method
public void bluetoothDiscovery(View v)
Personally, I try not to add onClick in the XML because they are hard to find as you add more classes and layouts. You can just set the OnClickListener from the Java code for clearer visibility.
I'm trying do a news sports app with a NavigationDrawer. But when I open the app I want to show a WebView and after from left to come the ListView. I did something but now the ListView doesn't show the items. I have 4 classes and 2 xml.
package com.baronescu.sportsnews2;
import android.os.Bundle;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
String[] menu;
DrawerLayout dLayout;
ListView dList;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu = new String[]{"Football","Tennis","Basketball","Hockey","Handball"};
dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
dList = (ListView) findViewById(R.id.left_drawer);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,menu);
dList.setAdapter(adapter);
dList.setSelector(android.R.color.holo_blue_dark);
dList.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
dLayout.closeDrawers();
Bundle args = new Bundle();
args.putString("Menu", menu[position]);
Fragment detail = new DetailFragment();
detail.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.dfurl, detail).commit();
}
});
Thread timer = new Thread(){
public void run (){
try {
sleep(2000);
} catch (InterruptedException e ){
e.printStackTrace();
} finally {
Intent odu = new Intent ("com.baronescu.sportsnews2.DEFAULTURL");
startActivity(odu);
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
package com.baronescu.sportsnews2;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DetailFragment extends Fragment {
TextView text;
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle args) {
View view = inflater.inflate(R.layout.menu_detail_fragment, container, false);
String menu = getArguments().getString("Menu");
text= (TextView) view.findViewById(R.id.detail);
text.setText(menu);
return view;
}
}
package com.baronescu.sportsnews2;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import com.baronescu.sportsnews2.OurViewClient;
public class DefaultUrl extends Activity {
WebView firstnews;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstnews = (WebView) findViewById(R.id.dfurl);
firstnews.setWebViewClient(new OurViewClient());
firstnews.getSettings().setJavaScriptEnabled(true);
firstnews.getSettings().setLoadWithOverviewMode(true);
firstnews.getSettings().setUseWideViewPort(true);
try {
firstnews.loadUrl("http://www.digisport.ro");
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.baronescu.sportsnews2;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class OurViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView v, String url) {
// TODO Auto-generated method stub
v.loadUrl(url);
return true;
}
}
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/sportsnews" >
<!-- android:id="#+id/content_frame" -->
<!-- android:layout_width="match_parent" -->
<!-- android:layout_height="match_parent" > -->
<WebView
android:id="#+id/dfurl"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#ffffff"
android:textSize="40px" />
</LinearLayout>
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.baronescu.sportsnews2"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="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=".DefaultUrl"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.baronescu.sportsnews2.DEFAULTURL" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
Start reading that does not hurt!
implementing drawer navigation
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
The main content view (the FrameLayout above) must be the first child in the DrawerLayout because the XML order implies
z-ordering and the drawer must be on top of the content.
The main content view is set to match the parent view's width and height, because it represents the entire UI when the navigation drawer is hidden.
The drawer view (the ListView) must specify its horizontal gravity with the android:layout_gravity attribute. To support right-to-left (RTL) languages, specify the value with "start" instead of "left" (so the drawer appears on the right when the layout is RTL).
The drawer view specifies ts width in dp units and the height matches the parent view. The drawer width should be no more than 320dp so the user can always see a portion of the main content.
As a good practice i recommend:
create layout for drawer as above
create main activity consuming layout
create second layout (main content layout) with WebView
make fragment for coresponding layout
add fragment via transaction in main activity