I'm having problems with running the code on my device [duplicate] - java

This question already has answers here:
Explanation of ClassCastException in Java
(12 answers)
Closed 4 years ago.
Here is my problem. Below is my class (Events.java) below it is the error. I continue to run my code on my phone but continue to get that error. I don't know what exactly the problem is and I don't know how to fix it. I tried everything I looked up but kept getting errors. Please help I'm a noob obviously.
package com.androidapp.restart;
import android.app.Fragment;
import android.app.LoaderManager;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.getbase.floatingactionbutton.FloatingActionButton;
/**
* Created by aa215995 on 3/2/2018.
*/
public class Events extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private FloatingActionButton mAddEventButton;
private Toolbar mToolbar;
EventCursorAdapter mCursorAdapter;
EventDbHelper eventDbHelper = new EventDbHelper(getActivity());
ListView eventListView;
ProgressDialog prgDialog;
private static final int VEHICLE_LOADER = 0;
#Nullable
#Override
public ListView onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
eventListView = (ListView) inflater.inflate(R.layout.nav_events, container, false);
mToolbar = (Toolbar) getView().findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
mToolbar.setTitle("Events");
eventListView = (ListView) getView().findViewById(R.id.list);
View emptyView = getView().findViewById(R.id.empty_view);
eventListView.setEmptyView(emptyView);
mCursorAdapter = new EventCursorAdapter(getActivity(), null);
eventListView.setAdapter(mCursorAdapter);
eventListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(view.getContext(), AddEvent.class);
Uri currentVehicleUri = ContentUris.withAppendedId(EventContract.EventEntry.CONTENT_URI, id);
// Set the URI on the data field of the intent
intent.setData(currentVehicleUri);
startActivity(intent);
}
});
mAddEventButton = (FloatingActionButton) getView().findViewById(R.id.fab);
mAddEventButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), AddEvent.class);
startActivity(intent);
}
});
getLoaderManager().initLoader(VEHICLE_LOADER, null, this);
return eventListView;
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
EventContract.EventEntry._ID,
EventContract.EventEntry.KEY_TITLE,
EventContract.EventEntry.KEY_DATE,
EventContract.EventEntry.KEY_TIME,
EventContract.EventEntry.KEY_REPEAT,
EventContract.EventEntry.KEY_REPEAT_NO,
EventContract.EventEntry.KEY_REPEAT_TYPE,
EventContract.EventEntry.KEY_ACTIVE
};
return new CursorLoader(getActivity(), // Parent activity context
EventContract.EventEntry.CONTENT_URI, // Provider content URI to query
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
mCursorAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
}
This is the error
05-24 14:02:00.885 15627-15627/com.androidapp.restart E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.androidapp.restart, PID: 15627
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast
to android.widget.ListView
at com.androidapp.restart.Events.onCreateView(Events.java:47)
at com.androidapp.restart.Events.onCreateView(Events.java:31)
at android.app.Fragment.performCreateView(Fragment.java:2508)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1279)
at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2407)
at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2186)
at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2142)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2043)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:719)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
This is the xml file (events.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/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.androidapp.restart.Events">
<ListView
android:id="#+id/list"
android:layout_below="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<RelativeLayout
android:id="#+id/empty_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<TextView
android:id="#+id/no_event_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:padding="16dp"
android:gravity="center"
android:text="#string/no_cardetails"/>
</RelativeLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_margin="16dp"
android:src="#drawable/ic_add_black_24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent" />
EDITED
Now I have change the xml to a Relative Layout, same issues, but here is another issue I found:
at android.app.Fragment.performCreateView(Fragment.java:2508)
Here is the section of the Fragment.java:
if (mFragmentManager != null) {
writer.print(prefix); writer.print("mFragmentManager=");
writer.println(mFragmentManager);
}

This is an issue:
eventListView = (ListView) inflater.inflate(R.layout.nav_events, container, false);
You try to inflate listview but inflater returns you a LinearLayout a parent of all views. You need inflate the LinearLayout instead of listview and this is causes to cast exception.

You are trying to cast a layout on a listview
add this #id into your LinearLayout and inflate it in your Activity
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#id/layout";
tools:context="com.delaroystudiuos.alarmreminder.MainActivity">
and then call it like this
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.layout, container, false);;

If you are trying to access your existing ListView item in the XML:
<ListView
android:id="#+id/list"
android:layout_below="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
You will need to instead use:
View view = inflater.inflate(R.layout.nav_events, container, false);
eventListView = view.findViewById(R.id.list);

Related

Android 4.1.1 - findViewById on RecyclerView returns null in MainActivity

I'm following Android Fundamentals CodeLabs (https://developer.android.com/codelabs/android-training-create-recycler-view?index=..%2F..%2Fandroid-training#3), with minor changes given I am using a more advanced version of Android Studio (4.1.1) and am getting a null recyclerView in MainActivity onCreate method even though the view exists. I've used BasicActivity to start this project. How do I fix this?
Here my XML for fragment_first.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=".FirstFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/ourcards_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:id="#+id/button_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/next"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
and here the MainActivity.java file content:
package com.example.ourcards;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import java.util.LinkedList;
public class MainActivity extends AppCompatActivity {
private final LinkedList<String> mCardList = new LinkedList<>();
private RecyclerView mRecyclerView;
private CardListAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = 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();
}
});
mCardList.addLast("Carta 1");
mCardList.addLast("Carta 2");
// Get a handle to the RecyclerView.
mRecyclerView = findViewById(R.id.ourcards_view);
// Create an adapter and supply the data to be displayed.
mAdapter = new CardListAdapter(this, mCardList);
// Connect the adapter with the RecyclerView.
mRecyclerView.setAdapter(mAdapter);
// Give the RecyclerView a default layout manager.
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
EDIT
Here is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.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"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/Theme.OurCards.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/Theme.OurCards.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<include layout="#layout/content_main" />
<com.google.android.material.floatingactionbutton.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="#drawable/ic_add_for_fab" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Here content_main.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/nav_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here my CardListAdapter.java
package com.example.ourcards;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.LinkedList;
public class CardListAdapter extends
RecyclerView.Adapter<CardListAdapter.CardViewHolder> {
private final LinkedList<String> mCardList;
private final LayoutInflater mInflater;
class CardViewHolder extends RecyclerView.ViewHolder {
public final TextView cardItemView;
final CardListAdapter mAdapter;
public CardViewHolder(View itemView, CardListAdapter adapter) {
super(itemView);
cardItemView = itemView.findViewById(R.id.card);
this.mAdapter = adapter;
}
}
public CardListAdapter(Context context,
LinkedList<String> cardList) {
mInflater = LayoutInflater.from(context);
this.mCardList = cardList;
}
#NonNull
#Override
public CardListAdapter.CardViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View mItemView = mInflater.inflate(R.layout.cardlist_item,
parent, false);
return new CardViewHolder(mItemView, this);
}
#Override
public void onBindViewHolder(#NonNull CardListAdapter.CardViewHolder holder, int position) {
String mCurrent = mCardList.get(position);
holder.cardItemView.setText(mCurrent);
}
#Override
public int getItemCount() {
return mCardList.size();
}
}
and here my FirstFragment.java
package com.example.ourcards;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
public class FirstFragment extends Fragment {
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false);
}
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NavHostFragment.findNavController(FirstFragment.this)
.navigate(R.id.action_FirstFragment_to_SecondFragment);
}
});
}
}
Here my XML for fragment_first.xml:
Note that your filename is fragment_first.xml.
and here the MainActivity.java file content
Your code here seems to have nothing to do with fragment_first.xml. For example, your setContentView() call is loading activity_main.xml.
So, either your RecyclerView needs to be in activity_main.xml, your setContentView() needs to be loading fragment_first, or you otherwise need to synchronize the work in your two code snippets.

How to get next activity when clicked from frag button

Hi i am trying to get my NextActivity when i press on Fab in my View 1
View 1 xml
<RelativeLayout 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"
android:orientation="vertical">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/Fbutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:layout_marginLeft="180dp"
android:clickable="true"
android:paddingRight="16dp"
android:paddingBottom="16dp"
/>
</RelativeLayout>,
View.java
package com.example.myapplication;
import android.content.Intent;
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;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class View1 extends Fragment {
private FloatingActionButton mFab;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.view1, container, false);
mFab.findViewById(R.id.Fbutton);
mFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),NextActivity.class);
startActivity(intent);
}
});
return view;
}
}
Error
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.google.android.material.floatingactionbutton.FloatingActionButton.findViewById(int)' on a null object reference
at com.example.myapplication.View1.onCreateView(View1.java:21)
i have tried
getContext()
View1.this
nothing worked
You haven't complete the floating button assigning.
Remove mFab.findViewById(R.id.Fbutton); this line.
Add
mFab = view.findViewById(R.id.Fbutton);
Here view is used to get the ID from the layout.
From the code that you posted most probably the problem is that you are not assigning the return value of findViewById(R.id.Fbutton); to the mFab.
mFab = findViewById(R.id.Fbutton);

I can't seem to get my fragment to load webview without crashing

So I'm making an app where the bottom navigation lets you click through different web pages and I've come across a problem. I can't seem to get it where the webview will function correctly inside the fragment class.
activity_main
<?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:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment_container"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginBottom="56dp">
</FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
fragment_clever.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/clever_web"></WebView>
</RelativeLayout>
cleverfragment.java (the one im currently working with)
package com.port.schoool;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class CleverFragment extends Fragment {
WebView webview;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
webview.findViewById(R.id.clever_web);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("google.com");
return inflater.inflate(R.layout.fragment_clever, null);
}
}
mainactivity.java
package com.port.schoool;
import android.os.Bundle;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(this);
loadFragment(new ReadWorksFragment());
}
private boolean loadFragment(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment fragment = null;
switch (menuItem.getItemId()) {
case R.id.navigation_home:
fragment = new ReadWorksFragment();
break;
case R.id.navigation_dashboard:
fragment = new CleverFragment();
break;
case R.id.navigation_notifications:
fragment = new PortalFragment();
break;
}
return loadFragment(fragment);
}
}
Here is my logcat logs for the crashes:
2019-08-04 18:05:25.164 7425-7425/com.port.schoool E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.port.schoool, PID: 7425
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.webkit.WebView.findViewById(int)' on a null object reference
at com.port.schoool.CleverFragment.onCreateView(CleverFragment.java:20)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2439)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at androidx.fragment.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6960)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Replace your fragment with:
public class CleverFragment extends Fragment {
WebView webview;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_clever, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
webview = view.findViewById(R.id.clever_web);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("https://google.com");
}
}
Of note:
Your original code would not compile, as there is no findViewById() on Fragment
The right version of inflate() to use in onCreateView() is the one that takes the container and false as the second and third parameters
You configure your fragment's views in onViewCreated()
You need to call findViewById() on the inflated layout (view in onViewCreated()) and assign that to webview
You need to use a valid URL with loadUrl()
This sort of stuff should be covered in your book on Android app development.

How to fix a bug where my Android app keeps crashing on start, does not open? (see description for more details)

This is the full logcat info:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void
android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a
null object reference
at cmput301.subbook.MainActivity.onCreate(MainActivity.java:49)
at android.app.Activity.performCreate(Activity.java:6999)
at android.app.Activity.performCreate(Activity.java:6990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6494) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
These are the relevant files:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="cmput301.subbook.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit App"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ListView
android:id="#+id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/mainText"
android:background="#e6a1a1"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp" />
<!-- <Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="144dp"
android:layout_marginTop="504dp"
android:text="Add New Subscription"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" /> -->
</android.support.constraint.ConstraintLayout>
MainActivity.java
package cmput301.subbook;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.view.View;
import android.widget.ArrayAdapter;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private TextView text;
private List<String> subListVal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.mainText);
ArrayList<String> subListVal = new ArrayList<String>();
// subListVal = new ArrayList<String>();
subListVal.add("Netflix");
subListVal.add("Github");
subListVal.add("Spotify");
subListVal.add("Gym");
/* ArrayAdapter<String> adapter;
adapter = new ArrayAdapter <String>(this, R.layout.list_rows, R.id.listText, subListVal);
ListView listView = (ListView) findViewById(android.R.id.list);
listView.setAdapter(adapter); */
CustomAdapter adapter = new CustomAdapter(subListVal, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(android.R.id.list);
lView.setAdapter(adapter);
/* Button add_btn = new Button(this);
add_btn.setText("Add New");
lView.addFooterView(add_btn); */
}
}
list_rows.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" >
<TextView
android:id="#+id/listText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="20sp"
android:textColor="#ffe600" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:text="Delete" />
<Button
android:id="#+id/edit_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/delete_btn"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:text="Edit" />
</LinearLayout>
CustomerAdapter.java
package cmput301.subbook;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by thesh on 2/3/2018.
*/
public class CustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list= new ArrayList<String>();
private Context context;
public CustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_rows, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.listText);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
Button editBtn = (Button)view.findViewById(R.id.edit_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
list.remove(position); //or some other task
notifyDataSetChanged();
}
});
editBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
notifyDataSetChanged();
}
});
return view;
}
}
Literally my app was working, and suddenly I got this bug, without changing much. The last change I made was trying to add a button at the footer_view of the list. I tried googling the logchat error to no avail.
Would appreciate the help. Thanks.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference at cmput301.subbook.MainActivity.onCreate(MainActivity.java:49)
This is telling you that line 49 in MainActivity has your problem, in a setAdapter() call, where you are calling it on something that is null.
That would appear to be this line:
lView.setAdapter(adapter);
That means lView is null.
You attempt to assign a value to lView in the preceding line:
ListView lView = (ListView)findViewById(android.R.id.list);
If lView is null, then findViewById(android.R.id.list) is returning null. This means that Android cannot find a widget in your layout that has an android:id value of #android:id/list.
That is because your ListView has a different ID value:
<ListView
android:id="#+id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/mainText"
android:background="#e6a1a1"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp" />
These need to line up. So, either:
Change android:id in the <ListView> to #android:id/list, or
Change your findViewById() call to look for R.id.listView
change this ListView lView = (ListView)findViewById(android.R.id.list);
to ListView lView = (ListView)findViewById(R.id.listView);
Change -
ListView lView = (ListView)findViewById(android.R.id.list);
with -
ListView lView = (ListView)findViewById(R.id.listview);

Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference - Bundle putExtra [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
The required output is that in 1st activity, there's a title, imageview and 3 buttons. When the image is clicked, new activity starts where same details are shown but this time only that post is shown(later along with comments). SO I need to pass the title and image details using bundle but my app crashes.
CustomAdapter.java code:
package com.example.swapsha96.myapplication;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
class CustomAdapter extends ArrayAdapter<String> {
private final String[] itemname;
private final Integer[] imgid;
private final Context context;
public CustomAdapter(Context context, String[] resource, Integer[] imgid) {
super(context, R.layout.postcard, resource);
this.itemname=resource;
this.imgid=imgid;
this.context = context;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
View view = layoutInflater.inflate(R.layout.postcard, parent, false);
TextView title = (TextView)view.findViewById(R.id.title);
ImageView post = (ImageView)view.findViewById(R.id.post);
Button plus1 = (Button)view.findViewById(R.id.plus1);
Button share = (Button)view.findViewById(R.id.share);
Button comment = (Button)view.findViewById(R.id.comment);
title.setText(itemname[position]);
post.setImageResource(imgid[position]);
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(parent.getContext(), Post.class);
Bundle extras = new Bundle();
extras.putString("title",itemname[position]);
extras.putInt("post", imgid[position]);
intent.putExtras(extras);
parent.getContext().startActivity(intent);
}
});
return view;
}
}
Post.java code: (the activity class which is going to open next on image click)
package com.example.swapsha96.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
public class Post extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String titleValue = extras.getString("title");
Integer postValue = extras.getInt("post");
TextView title = (TextView)findViewById(R.id.title);
ImageView post = (ImageView)findViewById(R.id.post);
title.setText(titleValue);
post.setImageResource(postValue);
}
}
activity_post.xml post:
<?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:orientation="vertical"
android:id="#+id/postcard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context="com.example.swapsha96.myapplication.Post"
android:background="#FFFFFF"
android:layout_margin="2dp"
android:adjustViewBounds="true">
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/myCoordinator"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.v4.widget.NestedScrollView
android:id="#+id/myScrollingContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
android:fillViewport="true">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_gravity="center_horizontal"
android:divider="#android:color/transparent"
android:dividerHeight="2dp" />
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
It throws the error that title.setText(titleValue); in 2nd code is a null object reference and hence unable to start the activity.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.swapsha96.myapplication/com.example.swapsha96.myapplication.Post}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
You haven't declared any TextView with id title in you layout. So you are unable to find that textview and hence title object is null.
Add TextView to your layout like this:
<TextView android:id="#+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" "/>

Categories

Resources