I keep gettting an InFlateException error in my Wearable app - floating-action-button

at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2914)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3049)
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:1809)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6680)
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 #28: Binary XML file line #28: Error inflating class com.google.android.material.floatingactionbutton.FloatingActionButton
Caused by: android.view.InflateException: Binary XML file line #28: Error inflating class com.google.android.material.floatingactionbutton.FloatingActionButton
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at android.view.LayoutInflater.createView(LayoutInflater.java:647)
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.rInflate(LayoutInflater.java:866)
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 com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:420)
at android.app.Activity.setContentView(Activity.java:2772)
at com.example.ticwatch_1.floating_action_button.onCreate(floating_action_button.java:35)
at android.app.Activity.performCreate(Activity.java:7144)
at android.app.Activity.performCreate(Activity.java:7135)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2894)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3049)
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:1809)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6680)
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: java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.AppCompat (or a descendant).
E/AndroidRuntime: at com.google.android.material.internal.ThemeEnforcement.checkTheme(ThemeEnforcement.java:243)
at com.google.android.material.internal.ThemeEnforcement.checkAppCompatTheme(ThemeEnforcement.java:213)
at com.google.android.material.internal.ThemeEnforcement.checkCompatibleTheme(ThemeEnforcement.java:148)
at com.google.android.material.internal.ThemeEnforcement.obtainStyledAttributes(ThemeEnforcement.java:76)
at com.google.android.material.floatingactionbutton.FloatingActionButton.<init>(FloatingActionButton.java:212)
at com.google.android.material.floatingactionbutton.FloatingActionButton.<init>(FloatingActionButton.java:201)
... 30 more
This is the error I get, I figured that the problem is with the floating action button, but my question is why? I have the dependency for it by default in the app.
implementation 'com.google.android.material:material:1.2.1'
So I'm not sure why it doesn't work. My app is for wearable devices could this be the problem?
Anyway here is my activity and xml layout:
package com.example.ticwatch_1;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.wear.ambient.AmbientModeSupport;
import androidx.wear.widget.drawer.WearableActionDrawerView;
import androidx.wear.widget.drawer.WearableDrawerLayout;
import androidx.wear.widget.drawer.WearableNavigationDrawerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class floating_action_button extends FragmentActivity
implements AmbientModeSupport.AmbientCallbackProvider {
private TextView mTextView;
/////////////////////////////////////////////////////////
private FloatingActionButton openbtn,tools,keys,modes;
private Boolean clicked = false;
////////////////////////////////////////////////////////
Animation rotateOpen,rotateClose,fromBottom, toBottom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_floating_action_button);
mTextView = (TextView) findViewById(R.id.text);
openbtn = (FloatingActionButton)findViewById(R.id.floatingActionButton);
tools = (FloatingActionButton)findViewById(R.id.Tools);
keys = (FloatingActionButton)findViewById(R.id.Keys);
modes = (FloatingActionButton)findViewById(R.id.Modes);
/////////////////////////////////////////////////////////////
rotateOpen = AnimationUtils.loadAnimation(floating_action_button.this,R.anim.rotate_open_anim);
rotateClose= AnimationUtils.loadAnimation(floating_action_button.this,R.anim.rotate_close_anime);
fromBottom = AnimationUtils.loadAnimation(floating_action_button.this,R.anim.from_bottom);
toBottom = AnimationUtils.loadAnimation(floating_action_button.this,R.anim.to_bottom);
openbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onFloatButtonClicked();
}
});
tools.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(floating_action_button.this, "tools", Toast.LENGTH_SHORT).show();
}
});
modes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(floating_action_button.this, "modes", Toast.LENGTH_SHORT).show();
}
});
keys.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(floating_action_button.this, "keys", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public AmbientModeSupport.AmbientCallback getAmbientCallback() {
return null;
}
private void onFloatButtonClicked()
{
setVisibility(clicked);
setAnimations(clicked);
clicked = !clicked;
}
private void setVisibility(Boolean clicked)
{
if(!clicked)
{
tools.setVisibility(View.VISIBLE);
modes.setVisibility(View.VISIBLE);
keys.setVisibility(View.VISIBLE);
}
else
{
tools.setVisibility(View.INVISIBLE);
modes.setVisibility(View.INVISIBLE);
keys.setVisibility(View.INVISIBLE);
}
}
private void setAnimations(Boolean clicked)
{
if(!clicked)
{
openbtn.startAnimation(rotateOpen);
tools.startAnimation(fromBottom);
modes.startAnimation(fromBottom);
keys.startAnimation(fromBottom);
}
else
{
openbtn.startAnimation(rotateClose);
tools.startAnimation(toBottom);
modes.startAnimation(toBottom);
keys.startAnimation(toBottom);
}
}
}
This is the xml layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.wear.widget.CircularProgressLayout
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:background="#color/dark_grey"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".floating_action_button"
tools:deviceIds="wear"
android:padding="#dimen/box_inset_layout_padding">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="#dimen/inner_frame_layout_padding"
>
<TextView
android:id="#+id/text"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/Modes"
android:layout_gravity="center"
android:translationY="-60dp"
android:translationX="-50dp"
android:visibility="invisible"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#drawable/round_shape"
android:backgroundTint="#color/green"
android:clickable="true"
android:focusable="true"
android:src="#drawable/ic_mode" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/Keys"
android:layout_gravity="center"
android:translationY="-10dp"
android:translationX="-70dp"
android:visibility="invisible"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#drawable/round_shape"
android:backgroundTint="#color/red_a200"
android:clickable="true"
android:focusable="true"
android:src="#drawable/ic_key"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/Tools"
android:translationY="40dp"
android:translationX="-50dp"
android:layout_gravity="center"
android:visibility="invisible"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#drawable/round_shape"
android:backgroundTint="#color/orange"
android:clickable="true"
android:focusable="true"
android:src="#drawable/ic_tools" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/floatingActionButton"
android:layout_gravity="center"
android:translationY="70dp"
android:layout_width="50dp"
android:layout_height="50dp"
android:focusable="true"
android:clickable="true"
android:src="#drawable/ic_menu"
android:background="#drawable/round_shape"
android:backgroundTint="#00BFFF"/>
</FrameLayout>
</androidx.wear.widget.CircularProgressLayout>

Related

Display ImageButton on last slide of viewpager

I'm trying to have a button appear only on the last page of a ViewPager. I have the working button but it is displayed on all the pages instead of only the last page. I want to have it visible only on the last page. Here is my code.
activity_welcome2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
tools:context=".Welcome_Activity"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!--- for dots -->
<View
android:id="#+id/view1"
android:layout_width="match_parent"
android:layout_height="1dp"
android:alpha=".5"
android:layout_above="#+id/dotsLayout"
android:background="#color/white"
android:layout_marginBottom="15dp" />
<LinearLayout
android:id="#+id/dotsLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:gravity="center"
android:layout_marginBottom="55sp" />
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/next3"
android:layout_width="99dp"
android:layout_height="45dp"
android:background="#android:color/transparent"
android:scaleType="fitCenter"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.822"
app:srcCompat="#drawable/next" />
</androidx.constraintlayout.widget.ConstraintLayout>
</RelativeLayout>
Welcome_Activity.java
package com.group7.salitongue;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;
public class Welcome_Activity extends AppCompatActivity {
private ViewPager mPager;
private int[] layouts = { R.layout.activity_main, R.layout.activity_splashscreen2, R.layout.activity_welcome };
private MpagerAdapter mpagerAdapter;
private LinearLayout Dots_Layout;
private ImageView[] dots;
private ImageButton nextBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome2);
mPager = (ViewPager) findViewById(R.id.viewPager);
mpagerAdapter = new MpagerAdapter(layouts, this);
mPager.setAdapter(mpagerAdapter);
Dots_Layout = (LinearLayout) findViewById(R.id.dotsLayout);
createDots(0);
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
#Override
public void onPageSelected(int position) {
createDots(position);
}
#Override
public void onPageScrollStateChanged(int state) {}
});
// transition button to Signup page
nextBtn = (ImageButton) findViewById(R.id.next3);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Welcome_Activity.this,MainActivity.class);
startActivity(intent);
}
});
}
private void createDots(int current_position) {
if(Dots_Layout != null)
Dots_Layout.removeAllViews();
dots = new ImageView[layouts.length];
for (int i = 0; i < layouts.length; i++) {
dots[i] = new ImageView(this);
if (i == current_position) {
dots[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.active_dots));
}
else {
dots[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.default_dots));
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
params.setMargins(4, 0, 4, 0);
Dots_Layout.addView(dots[i],params);
}
}
}
How can I display the button only when the user has reached the last page of swiping?
Just listen in the onPageSelected method of your OnPageChangeListener when the last page is reached and set the button to visible. In all other cases, just hide it.
#Override
public void onPageSelected(int position) {
createDots(position);
// only show the button when the last page is reached
if (position == mPagerAdapter.getCount() - 1)
nextBtn.setVisibility(View.VISIBLE);
else
nextBtn.setVisibility(View.GONE);
}

My app is unble to start another activity after showing splash screen and it is showing this error

My app is unble to start another Activity after showing splash screen.
This is the error I get when running my app:
Exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ref, PID: 7683
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ref/com.example.ref.LoginActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
at com.example.ref.LoginActivity.onCreate(LoginActivity.java:46)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
I/Process: Sending signal. PID: 7683 SIG: 9
Disconnected from the target VM, address: 'localhost:49932', transport: 'socket'
SpalshScreen:
package com.example.ref;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.os.Handler;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class SpalshScreen extends AppCompatActivity {
FirebaseUser currentUser;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spalsh_screen2);
mAuth = FirebaseAuth.getInstance();
if (mAuth != null) {
currentUser = mAuth.getCurrentUser(); }
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
FirebaseUser user = mAuth.getCurrentUser();
if (user == null) {
Intent intent = new Intent(SpalshScreen.this, LoginActivity.class);
startActivity(intent);
finish();
} else {
Intent mainIntent = new Intent(SpalshScreen.this, DashboardActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
}, 1000);
}
}
LoginActivity:
package com.example.ref;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.InputType;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.HashMap;
import java.util.Objects;
public class LoginActivity extends AppCompatActivity {
private EditText email, password, name;
private Button mlogin;
private TextView newdnewaccount, reocverpass;
FirebaseUser currentUser;
private ProgressDialog loadingBar;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Create Account");
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
// initialising the layout items
email = findViewById(R.id.login_email);
password = findViewById(R.id.login_password);
newdnewaccount = findViewById(R.id.needs_new_account);
reocverpass = findViewById(R.id.forgetp);
mAuth = FirebaseAuth.getInstance();
mlogin = findViewById(R.id.login_button);
loadingBar = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
// checking if user is null or not
if (mAuth != null) {
currentUser = mAuth.getCurrentUser();
}
mlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String emaill = email.getText().toString().trim();
String pass = password.getText().toString().trim();
// if format of email doesn't matches return null
if (!Patterns.EMAIL_ADDRESS.matcher(emaill).matches()) {
email.setError("Invalid Email");
email.setFocusable(true);
} else {
loginUser(emaill, pass);
}
}
});
// If new account then move to Registration Activity
newdnewaccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegistrationActivity.class));
}
});
// Recover Your Password using email
reocverpass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showRecoverPasswordDialog();
}
});
}
private void showRecoverPasswordDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Recover Password");
LinearLayout linearLayout = new LinearLayout(this);
final EditText emailet = new EditText(this);//write your registered email
emailet.setText("Email");
emailet.setMinEms(16);
emailet.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
linearLayout.addView(emailet);
linearLayout.setPadding(10, 10, 10, 10);
builder.setView(linearLayout);
builder.setPositiveButton("Recover", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String emaill = emailet.getText().toString().trim();
beginRecovery(emaill);//send a mail on the mail to recover password
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
private void beginRecovery(String emaill) {
loadingBar.setMessage("Sending Email....");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
// send reset password email
mAuth.sendPasswordResetEmail(emaill).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
loadingBar.dismiss();
if (task.isSuccessful()) {
Toast.makeText(LoginActivity.this, "Done sent", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LoginActivity.this, "Error Occured", Toast.LENGTH_LONG).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Error Failed", Toast.LENGTH_LONG).show();
}
});
}
private void loginUser(String emaill, String pass) {
loadingBar.setMessage("Logging In....");
loadingBar.show();
// sign in with email and password after authenticating
mAuth.signInWithEmailAndPassword(emaill, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
loadingBar.dismiss();
FirebaseUser user = mAuth.getCurrentUser();
if (task.getResult().getAdditionalUserInfo().isNewUser()) {
String email = user.getEmail();
String uid = user.getUid();
HashMap<Object, String> hashMap = new HashMap<>();
hashMap.put("email", email);
hashMap.put("uid", uid);
hashMap.put("name", "");
hashMap.put("onlineStatus", "online");
hashMap.put("typingTo", "noOne");
hashMap.put("phone", "");
hashMap.put("image", "");
hashMap.put("cover", "");
FirebaseDatabase database = FirebaseDatabase.getInstance();
// store the value in Database in "Users" Node
DatabaseReference reference = database.getReference("Users");
// storing the value in Firebase
reference.child(uid).setValue(hashMap);
}
Toast.makeText(LoginActivity.this, "Registered User " + user.getEmail(), Toast.LENGTH_LONG).show();
Intent mainIntent = new Intent(LoginActivity.this, DashboardActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
} else {
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Login Failed", Toast.LENGTH_LONG).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Error Occured", Toast.LENGTH_LONG).show();
}
});
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return super.onSupportNavigateUp();
}
}
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.Ref" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">#color/purple_500</item>
<item name="colorPrimaryVariant">#color/purple_700</item>
<item name="colorOnPrimary">#color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">#color/teal_200</item>
<item name="colorSecondaryVariant">#color/teal_700</item>
<item name="colorOnSecondary">#color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LoginActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/welcom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="120dp"
android:layout_marginTop="50dp"
android:text="Welcome!"
android:textColor="#color/colorBlack"
android:textSize="30sp"
android:textStyle="italic|bold" />
<TextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/welcom"
android:layout_marginStart="35dp"
android:layout_marginTop="120dp"
android:text="Email"
android:textColor="#color/colorBlack" />
<EditText
android:id="#+id/login_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/email"
android:layout_alignParentStart="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="5dp"
android:layout_marginRight="30dp"
android:background="#drawable/edit"
android:drawableStart="#drawable/ic_email"
android:hint="Email..."
android:inputType="textEmailAddress"
android:padding="8dp" />
<TextView
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/login_email"
android:layout_marginStart="32dp"
android:layout_marginTop="20dp"
android:text="Password"
android:textColor="#color/colorBlack" />
<EditText
android:id="#+id/login_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/password"
android:layout_alignParentStart="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="5dp"
android:layout_marginRight="30dp"
android:background="#drawable/edit"
android:drawableStart="#drawable/password"
android:hint="Password..."
android:inputType="textPassword"
android:padding="8dp" />
<TextView
android:id="#+id/forgetp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/login_password"
android:layout_marginStart="210dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="23dp"
android:text="#string/forget_password"
android:textAlignment="center"
android:textColor="#color/colorPrimaryDark"
android:textSize="17sp"
android:textStyle="bold" />
<Button
android:id="#+id/login_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/forgetp"
android:layout_marginLeft="30dp"
android:layout_marginTop="15dp"
android:layout_marginRight="30dp"
android:background="#drawable/buttonss"
android:padding="4dp"
android:text="Login"
android:textAllCaps="false"
android:textColor="#android:color/background_light"
android:textSize="24sp" />
<TextView
android:id="#+id/needs_new_account"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/login_button"
android:layout_centerHorizontal="true"
android:layout_marginStart="15dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="23dp"
android:text="#string/need_new_account_sign_up_here"
android:textAlignment="center"
android:textColor="#color/colorPrimary"
android:textSize="17sp"
android:textStyle="bold" />
</RelativeLayout>
</ScrollView>
</LinearLayout>
See getting Null pointer exception while setting the title to action bar. Probably you missed something in styles.xml. Could you write it? There may be a problem in
<style name="AppTheme.NoActionBar">
<item name="android:windowActionBar">false</item>
Also, please, add a layout of LoginActivity. There should be Toolbar.
When the compiler start onCreate() in your second activity he can't find the reference to the object that you are trying to setTitle(), so basically your Toolbar or ActionBar doesn't have a reference to the Object in the View(xml).
Ex:
Toolbar toolbar = findViewById(R.id.name_of_the_object);
in this way toolbar gets the reference to the object in the view (activity.xml);
I think this line is wrong ActionBar actionBar = getSupportActionBar();
It should be ActionBar actionBar = activity.getSupportActionBar();

App Crashes whenever I click an Icon on Navigation bar

Just got many problems sorted out on my bottom navigation bar, but now the app crashes whenever I click on any of the 3 navigation bar Icons.
Error
2020-07-23 15:41:26.397 25876-25876/com.example.sociate11 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sociate11, PID: 25876
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at androidx.fragment.app.FragmentTransaction.doAddOp(FragmentTransaction.java:245)
at androidx.fragment.app.BackStackRecord.doAddOp(BackStackRecord.java:180)
at androidx.fragment.app.FragmentTransaction.replace(FragmentTransaction.java:343)
at androidx.fragment.app.FragmentTransaction.replace(FragmentTransaction.java:293)
at com.example.sociate11.activityHome$2.onNavigationItemSelected(activityHome.java:67)
at com.google.android.material.bottomnavigation.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:243)
at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)
at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
at com.google.android.material.bottomnavigation.BottomNavigationMenuView$1.onClick(BottomNavigationMenuView.java:124)
at android.view.View.performClick(View.java:7357)
at android.view.View.performClickInternal(View.java:7334)
at android.view.View.access$3600(View.java:808)
at android.view.View$PerformClick.run(View.java:28200)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7478)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
activityHome.java
package com.example.sociate11;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
public class activityHome extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private Button logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
firebaseAuth = FirebaseAuth.getInstance();
logout = (Button)findViewById(R.id.btnLogOut);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseAuth.signOut();
finish();
startActivity(new Intent(activityHome.this, MainActivity.class));
}
});
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation_bar);
bottomNav.setOnNavigationItemSelectedListener(navListener);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.home_fragment:
selectedFragment = new HomeFragment();
break;
case R.id.events_fragment:
selectedFragment = new EventFragment();
break;
case R.id.fragment_myconversation:
selectedFragment = new ConversationFragment();
break;
}
assert selectedFragment != null;
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
};
}
ConversationsFragment.java (all 3 fragments are currently identical)
package com.example.sociate11;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class ConversationFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_myconversations,container,false);
}
}
bottom_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/menu_home"
android:title="Home"
android:icon="#drawable/ic_home"
app:showAsAction="always"/>
<item
android:id="#+id/menu_myEvents"
android:title="My Events"
android:icon="#drawable/ic_event"
app:showAsAction="always"/>
<item
android:id="#+id/menu_myConversations"
android:title="My Conversations"
android:icon="#drawable/ic_conversations"
app:showAsAction="always"/>
</menu>
activity_home.xml
<?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=".activityHome"
android:background="#color/colorPrimary">
<Button
android:id="#+id/btnLogOut"
android:layout_width="115dp"
android:layout_height="75dp"
android:text="log out"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/bottom_navigation_bar" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:itemTextColor="#color/colorPrimaryDark"
app:itemIconTint="#color/colorPrimaryDark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnLogOut"
app:layout_constraintVertical_bias="1.0"
app:menu="#menu/bottom_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
Thank you for the help as always, and please let me know if I didn't provide enough info!

Trying to add scrollable tabs in a fragment that extends FragmentActivity, but unable to find the mistake

MyEventsFragment.java
List item
package com.example.edvenswa.collabevents;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class MyEventsFragment extends FragmentActivity{
ViewPager viewPager = null;
MyAdapter myAdapter;
public MyEventsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_my_events);
viewPager = (ViewPager) findViewById(R.id.myEventsPager);
/*List<Fragment> listFragments = new ArrayList<Fragment>();
listFragments.add(new MyEventsInsideFragment());
listFragments.add(new ExpiredEventsFragment());
listFragments.add(new AttendingEventsFragment());
listFragments.add(new PastAttendingEventsFragment());*/
myAdapter = new MyAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.myEventsPager);
viewPager.setAdapter(myAdapter);
}
/* #Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_my_events, container, false);
}*/
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Log.d("count","count called"+i);
Fragment fragment = null;
if (i == 0) {
fragment = new MyEventsInsideFragment();
}
if (i == 1) {
fragment = new ExpiredEventsFragment();
}
if (i == 2) {
fragment = new AttendingEventsFragment();
}
if (i == 3) {
fragment = new PastAttendingEventsFragment();
}
return fragment;
}
#Override
public int getCount() {
Log.d("count", "count called");
return 4;
}
}
fragment_my_events.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.example.edvenswa.collabevents.MyEvents">
<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/colorPrimaryDark"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/myEventsPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="56dp"
android:gravity="center">
</android.support.v4.view.ViewPager>
</FrameLayout>
So, this is my code. here I am able to view the first page in fragment but unable scroll and no view of other fragments.
Note: This MyEventsFragment.java is also a fragment in the sidedrawer.
First add the design support library if you haven't
compile 'com.android.support:design:23.0.0'
then add the TabLayout like this one.
<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/colorPrimaryDark"
app:popupTheme="#style/AppTheme.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
Then in your onCreate() method below the viewPager add the following line,
TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
Also, in your FragmentPageAdapter, you'll have to override getPageTitle() method for returning your Tabs title.

Search bar is messing up ListView

I had a ListView that was working fine until I tried to add a search bar. I did have to reformat the activity and use a different kind of array, so that could be it too.
Basically, when I try and click on an item in the ListView on the emulator it says 'Unfortunately, myapp has stopped'. I'll post the code and hopefully I've made a stupid mistake somewhere that's easy to fix.
SecondScreenActivity.java (the ListView Activity)
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
public class SecondScreenActivity extends Activity
{
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Listview Data
String products[] = {"Recipe1", "Recipe2", "Recipe3", "Recipe4", "Recipe5",
"Recipe6", "Recipe7", "Recipe8", "Recipe9", "Recipe10"};
lv = (ListView) findViewById(R.id.mainListView);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
lv.setAdapter(adapter);
// Enabling search filter
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
SecondScreenActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
// register onClickListener to handle click events on each item
lv.setOnItemClickListener(new OnItemClickListener()
{
// argument position gives the index of item which is clicked
public void onItemClick(AdapterView<?> parent, View itemClicked,
int position, long id) {
TextView textView = (TextView) itemClicked;
String strText = textView.getText().toString();
Intent intenttwo = new Intent(SecondScreenActivity.this, ThirdScreenActivity.class);
intenttwo.putExtra("position", strText);
startActivity(intenttwo);
}
});
}
}
ThirdScreenActivity.java (should open on item click)
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class ThirdScreenActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);
//Sets the title to recipe name
TextView t = ((TextView)findViewById(R.id.textviewPosition));
Intent intent = getIntent();
String position = intent.getStringExtra("position");
t.setText(position);
//Sets the correct recipe
if ("Recipe1".equals(position)) {
TextView RecipeTextView = ((TextView)findViewById(R.id.RecipeTextView));
RecipeTextView.setText(R.string.recipe1);
}
else if ("Recipe2".equals(position)) {
TextView RecipeTextView = ((TextView)findViewById(R.id.RecipeTextView));
RecipeTextView.setText(R.string.recipe2);
}
else if ("Recipe3".equals(position)) {
TextView RecipeTextView = ((TextView)findViewById(R.id.RecipeTextView));
RecipeTextView.setText(R.string.recipe3);
}
else if ("Recipe4".equals(position)) {
TextView RecipeTextView = ((TextView)findViewById(R.id.RecipeTextView));
RecipeTextView.setText(R.string.recipe4);
}
else if ("Recipe5".equals(position)) {
TextView RecipeTextView = ((TextView)findViewById(R.id.RecipeTextView));
RecipeTextView.setText(R.string.recipe5);
}
else if ("Recipe6".equals(position)) {
TextView RecipeTextView = ((TextView)findViewById(R.id.RecipeTextView));
RecipeTextView.setText(R.string.recipe6);
}
else if ("Recipe7".equals(position)) {
TextView RecipeTextView = ((TextView)findViewById(R.id.RecipeTextView));
RecipeTextView.setText(R.string.recipe7);
}
else if ("Recipe8".equals(position)) {
TextView RecipeTextView = ((TextView)findViewById(R.id.RecipeTextView));
RecipeTextView.setText(R.string.recipe8);
}
else if ("Recipe9".equals(position)) {
TextView RecipeTextView = ((TextView)findViewById(R.id.RecipeTextView));
RecipeTextView.setText(R.string.recipe9);
}
else if ("Recipe10".equals(position)) {
TextView RecipeTextView = ((TextView)findViewById(R.id.RecipeTextView));
RecipeTextView.setText(R.string.recipe10);
}
}
Main.xml (The ListView layout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000">
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:text="Recipes"
android:textColor="#33ccff"
android:textSize="40sp"
android:gravity="center_vertical|center_horizontal"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/inputSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search recipes..."
android:inputType="textVisiblePassword"/>
<ListView
android:id="#+id/mainListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
screen2.xml (layout of page that should open on item click)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff">
<TextView
android:id="#+id/textviewPosition"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:textSize="40sp"
android:textColor="#33ccff"
android:gravity="center" />
<ScrollView
android:layout_height="fill_parent"
android:layout_width="fill_parent">
<TextView
android:id="#+id/RecipeTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="20dp"
android:textColor="#000000"
android:textSize="15sp" />
</ScrollView>
</LinearLayout>
And finally, the logcat.
06-24 23:11:33.350: E/AndroidRuntime(939): FATAL EXCEPTION: main
06-24 23:11:33.350: E/AndroidRuntime(939): java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView
06-24 23:11:33.350: E/AndroidRuntime(939): at com.leopenrose.cookbook.SecondScreenActivity$2.onItemClick(SecondScreenActivity.java:80)
06-24 23:11:33.350: E/AndroidRuntime(939): at android.widget.AdapterView.performItemClick(AdapterView.java:298)
06-24 23:11:33.350: E/AndroidRuntime(939): at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
06-24 23:11:33.350: E/AndroidRuntime(939): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
06-24 23:11:33.350: E/AndroidRuntime(939): at android.widget.AbsListView$1.run(AbsListView.java:3423)
06-24 23:11:33.350: E/AndroidRuntime(939): at android.os.Handler.handleCallback(Handler.java:725)
06-24 23:11:33.350: E/AndroidRuntime(939): at android.os.Handler.dispatchMessage(Handler.java:92)
06-24 23:11:33.350: E/AndroidRuntime(939): at android.os.Looper.loop(Looper.java:137)
06-24 23:11:33.350: E/AndroidRuntime(939): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-24 23:11:33.350: E/AndroidRuntime(939): at java.lang.reflect.Method.invokeNative(Native Method)
06-24 23:11:33.350: E/AndroidRuntime(939): at java.lang.reflect.Method.invoke(Method.java:511)
06-24 23:11:33.350: E/AndroidRuntime(939): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-24 23:11:33.350: E/AndroidRuntime(939): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-24 23:11:33.350: E/AndroidRuntime(939): at dalvik.system.NativeStart.main(Native Method)
I've seen the fatal exception in the logcat but I really have no idea what to do about it!
I'm sorry for posting so much code but I didn't think there was any that might not be helpful. Thanks for the help!
Each item in your list is of type LinearLayout. In your onItemClick, you are typecasting it to TextView, hence the ClassCastException. The following code should work
lv.setOnItemClickListener(new OnItemClickListener()
{
// argument position gives the index of item which is clicked
public void onItemClick(AdapterView<?> parent, View itemClicked,
int position, long id) {
LinearLayout view = (LinearLayout) itemClicked;
TextView textView = (TextView)view.findViewById(R.id.textViewPosition);
String strText = textView.getText().toString();
Intent intenttwo = new Intent(SecondScreenActivity.this, ThirdScreenActivity.class);
intenttwo.putExtra("position", strText);
startActivity(intenttwo);
}
});

Resources