NullPointerException when setting an onClickListener - java

I'm trying to make my own browser, but I'm stuck. I try to send URL with string as data type using intent from my main activity to the web activity. This is my web activity java code:
public class webView extends MainActivity {
private WebView halamanWeb;
private ProgressBar progressBar;
private EditText searchBox;
private ImageButton tombolCari2;
private String Url;
private String getUrl(){
return Url = "https://" + searchBox.getText().toString();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.surfing_layout);
searchBox = (EditText) findViewById(R.id.searchBoxAtas);
tombolCari2 = (ImageButton) findViewById(R.id.tombolCari);
progressBar = (ProgressBar) findViewById(R.id.bar);
halamanWeb = (WebView) findViewById(R.id.webLayout);
Intent test = getIntent();
final String url = "https://" + test.getStringExtra("key");
halamanWeb.getSettings().setJavaScriptEnabled(true);
halamanWeb.getSettings().setDisplayZoomControls(true);
halamanWeb.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(newProgress);
if (newProgress == 100) {
progressBar.setVisibility(View.GONE);
}
halamanWeb.loadUrl(url);
halamanWeb.setWebViewClient(new MyWebLaunch());
}
});
tombolCari2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
halamanWeb.getSettings().setJavaScriptEnabled(true);
halamanWeb.getSettings().setDisplayZoomControls(true);
halamanWeb.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress){
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(newProgress);
if(newProgress == 100){
progressBar.setVisibility(View.GONE);
}
}
});
halamanWeb.loadUrl(getUrl());
halamanWeb.setWebViewClient(new MyWebLaunch());
}
});
}
private class MyWebLaunch extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return super.shouldOverrideUrlLoading(view, url);
}
}
}
this is my main activity java code :
public class MainActivity extends AppCompatActivity {
//deklarasi
private EditText searchBox;
private ImageButton tombolCari;
private WebView halamanWeb;
private ProgressBar progressBar;
private String Url;
//deklarasi fungsi
private String getUrl(){
return Url = "https://" + searchBox.getText().toString();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchBox = (EditText) findViewById(R.id.searchBoxAtas);
tombolCari = (ImageButton) findViewById(R.id.tombolCari);
progressBar = (ProgressBar) findViewById(R.id.bar);
tombolCari.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Url = getUrl();
Intent test = new Intent(v.getContext(), webView.class);
test.putExtra("key", Url);
startActivity(test);
}
});
}
}
when I run that code, got error code that say:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
Can anyone help me with the intent idea, I want to pass a string URL from my main activity to the web activity and then use that to open the site using the URL.
How can I get out from the null pointer on image button?
I would like some help! Thanks!
Edit : This is my log when i start the code, it runs but when i input something and i pressed the ImageButton it crashed.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.johno.myapplication.webView.onCreate(webView.java:54)
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) 

Check if you have something like below in your surfing_layout.xml:
<ImageButton
android:id="#+id/tombolCari"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
If it is there, just check if the ID of that image button is tombolCari. If it is something else, just change it to android:id="#+id/tombolCari"

You are overriding MainActivity view with WebView activity and you are expecting MainActivity view should be alive.All your Mainactivity UI elements which are present in R.layout.activity_main will be out of scope.To fix this move to activity_main content to surfing_layout.
Remove setContentView(R.layout.activity_main) and from MainActivity and make surev
surfing_layout has tombolCari imageButton.

Now you have two xml one for MainActivity => "activity_main",
and the second for webView => "surfing_layout".
I see that you extended MainActivity in webView Class and added the same widget and write it again in webView Class, then if you forget to add ImageButton from activity_main.xml to surfing_layout.xml, or forget to add the same id for ImageButton to surfing_layout.xml
Add this code to surfing_layout.xml
<ImageButton
android:id="#+id/tombolCari"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

Related

Android app crashes when activity is initialised from fragment [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 9 months ago.
I am currently trying to create a calendar app in android studio. The app contains a calendar with different "Views" e.g. monthly view, weekly view, and daily view.
The app uses fragments as pages and each view is an activity.
This is the code for the fragment and buttons to initialise each view
public class CalendarFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_calendar, container, false);
Button btn1 = (Button) v.findViewById(R.id.openCalendar);
btn1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v)
{
Intent intent = new Intent(getActivity(),CalendarActivity.class);
startActivity(intent);
}
});
Button btn2 = (Button) v.findViewById(R.id.openWeek);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(getActivity(), WeekViewActivity.class);
startActivity(intent);
}
});
return v;
}
The first button which displays the monthly view of the calendar called "CalendarActivity" in code works fine but when the second button is clicked which displays the weekly view of the calendar, causes the app to crash and gives the following error in the logcat
2022-05-13 14:44:59.642 15183-15183/com.example.finalyearproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.finalyearproject, PID: 15183
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.finalyearproject/com.example.finalyearproject.WeekViewActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.time.LocalDate.format(java.time.format.DateTimeFormatter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3685)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3842)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
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:2252)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7842)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.time.LocalDate.format(java.time.format.DateTimeFormatter)' on a null object reference
at com.example.finalyearproject.CalendarUtils.monthYearFromDate(CalendarUtils.java:16)
at com.example.finalyearproject.WeekViewActivity.setWeekView(WeekViewActivity.java:40)
at com.example.finalyearproject.WeekViewActivity.onCreate(WeekViewActivity.java:29)
at android.app.Activity.performCreate(Activity.java:8054)
at android.app.Activity.performCreate(Activity.java:8034)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1341)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3666)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3842) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103) 
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:2252) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loopOnce(Looper.java:201) 
at android.os.Looper.loop(Looper.java:288) 
at android.app.ActivityThread.main(ActivityThread.java:7842) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) 
I am not sure what the problem is as I have been following a tutorial and the other features work. I have also included the code for each activity below.
Monthly View
public class CalendarActivity extends AppCompatActivity implements CalendarAdapter.OnItemListener {
private TextView monthYearText;
private RecyclerView calendarRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
initWidgets();
CalendarUtils.selectedDate = LocalDate.now();
setMonthView();
}
private void initWidgets()
{
calendarRecyclerView = findViewById(R.id.calendarRecyclerView);
monthYearText = findViewById(R.id.monthYearTV);
}
private void setMonthView()
{
monthYearText.setText(monthYearFromDate(CalendarUtils.selectedDate));
ArrayList<LocalDate> daysInMonth = daysInMonthArray(CalendarUtils.selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(daysInMonth, this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
}
public void nextMonth(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.plusMonths(1);
setMonthView();
}
public void previousMonth(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.minusMonths(1);
setMonthView();
}
Weekly View
public class WeekViewActivity extends AppCompatActivity implements CalendarAdapter.OnItemListener {
private TextView monthYearText;
private RecyclerView calendarRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_week_view);
initWidgets();
setWeekView();
}
private void initWidgets()
{
calendarRecyclerView = findViewById(R.id.calendarRecyclerView);
monthYearText = findViewById(R.id.monthYearTV);
}
private void setWeekView()
{
monthYearText.setText(monthYearFromDate(CalendarUtils.selectedDate));
ArrayList<LocalDate> days = daysInWeekArray(CalendarUtils.selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(days, this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
}
public void previousWeek(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.minusWeeks(1);
setWeekView();
}
public void nextWeek(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.plusWeeks(1);
setWeekView();
}
Any suggestions would be greatly appreciated.
My suggestions:
Firstly you didn't initialized CalendarUtils.selectedDate
Cover code with breakpoints for. debugging or with Log.d() messages to find, which variable is null

Android: Passing an arraylist to another activity (Attempt to invoke interface method 'int java.util.List.size()' on a null object reference)

I'm creating a memo app. The "save" button creates a Memo object and adds it into the list (this part works when checked with the Log).
The "open" view is supposed to send the whole list into the ListActivity, but the whole app crashes when it is clicked on, so for me the issue seems to be with the intent starting the ListActivity (in the MainActivity) or the creation line of the new ArrayList the ListActivity.
There are plenty of questions with a similar problem, but I failed to find many with a code that I can reliably compare to my own. I tried to swap serializables into parcelables and a few other potential fixes, but came back empty handed.
MainActivity:
public class MainActivity extends AppCompatActivity {
// Creating a static instance of this class to access title and message inputs to ListActivity.
static MainActivity instance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
instance = this;
//Creating the list of memos
final ArrayList<Memo> memos = new ArrayList<Memo>();
// Find the View that opens the ListActivity
TextView open = (TextView) findViewById(R.id.open_view);
// Set a click listener on that View
open.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent openIntent = new Intent(MainActivity.this, ListActivity.class);
openIntent.putExtra("List_of_memos", memos);
startActivity(openIntent);
}
});
// Find the View that saves the memo
TextView save = (TextView) findViewById(R.id.save_view);
// Set a click listener on that View
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
memos.add(new Memo(getmTitle(), getmMessage()));
}
});
}
//Declaring a method that returns the title value.
public String getmTitle(){
//Turning the title input field into a string variable
EditText titleInput = (EditText) findViewById(R.id.title_input);
return titleInput.getText().toString();
}
//Declaring a method that returns the message value.
public String getmMessage(){
//Turning the message input field into a string variable
EditText messageInput = (EditText) findViewById(R.id.message_input);
return messageInput.getText().toString();
}
}
ListActivity:
public class ListActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
String title = MainActivity.instance.getmTitle();
String message = MainActivity.instance.getmMessage();
ArrayList<Memo> memos = (ArrayList<Memo>)getIntent().getSerializableExtra("FILES_TO_SEND");
//Create an ArrayAdapter with a list of Strings as a data source.
// The adapter knows how to create layouts for each item in the list, using the simple_list_item_1.xml layout.
// This list item layout contains a single TextView, which the adapter will set to display a single string.
MemoAdapter adapter = new MemoAdapter(this, memos);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
}
The object class:
public class Memo implements Serializable {
private String mTitle;
private String mMessage;
// Constructor for the word object
public Memo(String title, String message) {
mTitle = title;
mMessage = message;
}
//Get the title
public String getTitle() {
return mTitle;
}
//Get the message
public String getMessage() {
return mMessage;
}
public void setmTitle(String mTitle) {
this.mTitle = mTitle;
}
public void setmMessage(String mMessage) {
this.mMessage = mMessage;
}
#Override
public String toString() {
return "Memo{" +
"Title='" + mTitle + '\'' +
", Message='" + mMessage + '\'' +
'}';
}
}
...and the error message:
FATAL EXCEPTION: main
Process: com.memo.android.memo, PID: 26543
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.memo.android.memo/com.memo.android.memo.ListActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2947)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6688)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:344)
at android.widget.ListView.setAdapter(ListView.java:556)
at com.memo.android.memo.ListActivity.onCreate(ListActivity.java:29)
at android.app.Activity.performCreate(Activity.java:6912)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2900)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008) 
at android.app.ActivityThread.-wrap14(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6688) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358) 
Hope you can help, I've spent quite a few hours without any significant results with this issue. Thanks!
In one activity you call the extras "List_of_memos", in the other you call it "FILES_TO_SEND". The two need to use the same name.

Change code to android annotations

I'm trying to change my code to android annotations. My app starts but when I tap button it crash and get error:
FATAL EXCEPTION: main
Process: com.example.albertpula.apka3, PID: 2523
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference
at com.example.albertpula.apka3.MainActivity$ReadPic.onPreExecute(MainActivity.java:83)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:604)
at android.os.AsyncTask.execute(AsyncTask.java:551)
at com.example.albertpula.apka3.MainActivity.click(MainActivity.java:54)
at com.example.albertpula.apka3.MainActivity_$1.onClick(MainActivity_.java:72)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
here is code:
#EActivity(R.layout.activity_main)
public class MainActivity extends Activity {
String adres ="http://www.heavens-above.com/orbitdisplay.aspx?icon=iss&width=300&height=300&satid=25544";
Bitmap bmp;
ProgressBar progressBar;
Button button1;
ImageView image;
TextView text;
#Override
public void onCreate(Bundle savedInstanceState)
{
image = (ImageView)findViewById(R.id.imageView);
button1 = (Button)findViewById(R.id.button1);
progressBar = (ProgressBar)findViewById(R.id.progressBar1);
text = (TextView)findViewById(R.id.textView1);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Click(R.id.button1)
void click(View view){
ReadPic rp = new ReadPic();
rp.execute();
}
class ReadPic extends AsyncTask<Void, Void, Void>
{
boolean sukces = true;
#Override
protected Void doInBackground(Void... arg0){
URL u;
InputStream is;
try{
u = new URL( adres);
is = u.openStream();
Bitmap temp = BitmapFactory.decodeStream(is);
bmp=temp.copy(Bitmap.Config.ARGB_8888, true);
}
catch( Exception e){
sukces = false;
}
return null;
}
protected void onPreExecute(){
progressBar.setVisibility(ProgressBar.VISIBLE);
button1.setEnabled(false);
super.onPreExecute();
}
protected void onPostExecute(Void result){
if(sukces){
Canvas c = new Canvas(bmp);
Paint p = new Paint();
int width = bmp.getWidth(), height = bmp.getHeight();
p.setColor(Color.WHITE);
p.setStyle(Paint.Style.STROKE);
c.drawRect(0,0,width-1,height-1,p);
image.setImageBitmap(bmp);
text.setText("Downloading finished, img " +width+ "x" + height);
}
else{
text.setText("Error when downloading");
}
button1.setEnabled(true);
progressBar.setVisibility(ProgressBar.INVISIBLE);
super.onPostExecute(result);
}
}
}
Use ViewBinding for binding your xml views like this :
#ViewById(R.id.button1)Button button1;
#ViewById(R.id.imageView)ImageView image;
#ViewById(R.id.textView1)TextView text;
Remove the code from your onCreate().
Don't add :
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
For the error: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference at
Option :1 Check if it is null.
protected void onPreExecute(){
if(progressBar != null)
progressBar.setVisibility(ProgressBar.VISIBLE);
button1.setEnabled(false);
super.onPreExecute();
}
AND,
button1.setEnabled(true);
if(progressBar != null)
progressBar.setVisibility(ProgressBar.INVISIBLE);
super.onPostExecute(result);
Option :2 - Initialize the ProgressDialog
class ReadPic extends AsyncTask<Void, Void, Void> {
ProgressBar progressBar;
boolean sukces = true;
public ReadPic(){
progressBar = new ProgressBar();//Set the Theme, context & call constructor as per your choice.
}
//YOUR CODE GOES BELOW//
}//ReadPic class closes here....
Edit 1: Gorthez, instantiate your Progress bar like this:
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
Also Add Progress Bar in your xml:
<LinearLayout
android:orientation="horizontal"
... >
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#android:style/Widget.ProgressBar.Small"
android:layout_marginRight="5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/loading" /> </LinearLayout>
Edit1 Reference https://developer.android.com/reference/android/widget/ProgressBar.html
#Override
public void onCreate(Bundle savedInstanceState)
{
**//put setContentView and super call here
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);**
image = (ImageView)findViewById(R.id.imageView);
button1 = (Button)findViewById(R.id.button1);
progressBar = (ProgressBar)findViewById(R.id.progressBar1);
text = (TextView)findViewById(R.id.textView1);
//setContentView(R.layout.activity_main);
}
Here you are trying to access the view elements before inflating the layout.
First inflate the layout by calling setContentView(R.layout.activity_main);
then try to access the elements.

App crashes when launching another activity

I searched everywhere for a solution to my problem, but couldn't get one.So, the problem is I want to launch another activity called FifthActivity from my MainActivity via the button but my activity keeps crashing. I checked the logcat and found this -
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.india.chemistry/com.example.india.chemistry.FifthActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
Below is my mainActivity java file.
package com.example.india.chemistry;
public class MainActivity extends AppCompatActivity {
private static boolean isRunning = false;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(!isRunning)
{
isRunning = true;
startActivity(new Intent(this, Intro.class));//Play your video here
}
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#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) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void part_a( View View){
Intent intent1 = new Intent("com.example.india.chemistry.Second_Activity");
startActivity(intent1);
}
public void part_b( View View) {
Intent intent2 = new Intent("com.example.india.chemistry.ThirdActivity");
startActivity(intent2);
}
public void formulas( View View) {
Intent intent4 = new Intent(this,FifthActivity.class);
startActivity(intent4);
}
}
Below is my FifthActivity.java file.
package com.example.india.chemistry;
public class FifthActivity extends ActionBarActivity {
final Animation shake = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.shake);
final Animation bounce = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fifth);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_fifth, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void nernst(View View) {
Intent intentf1 = new Intent("com.example.india.chemistry.nernst_activity");
startActivity(intentf1);
}
public void waterhardness(View View) {
Intent intentf2 = new Intent("com.example.india.chemistry.WaterHardness");
startActivity(intentf2);
}
public void determinationOfCao(View view) {
Intent intentf3 = new Intent("com.example.india.chemistry.CementCao");
startActivity(intentf3);
}
public void COD_waste_water(View view) {
Intent intentf4 = new Intent("com.example.india.chemistry.COD");
startActivity(intentf4);
}
public void C_in_B(View view) {
Intent intentf5 = new Intent("com.example.india.chemistry.Copper_in_Brass");
startActivity(intentf5);
}
public void alkalinity(View view) {
Intent intentf6 = new Intent("com.example.india.chemistry.Alkalinity");
startActivity(intentf6);
}
public void haematite_ore(View view) {
Intent intentf7 = new Intent("com.example.india.chemistry.HaemetiteOre");
startActivity(intentf7);
}
public void colourimetry_copper(View view) {
Intent intentf8 = new Intent("com.example.india.chemistry.Colourimetric_Copper");
startActivity(intentf8);
}
public void potentiometry_fas(View view) {
Intent intentf9 = new Intent("com.example.india.chemistry.Potentiometry_fas");
startActivity(intentf9);
}
public void conductometry(View view) {
Intent intentf10 = new Intent("com.example.india.chemistry.Conductometry");
startActivity(intentf10);
}
public void pka(View view) {
Intent intentf11 = new Intent("com.example.india.chemistry.pka");
startActivity(intentf11);
}
}
Below is the logcat.
10-14 17:13:58.145 15430-15430/com.example.india.chemistry E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.india.chemistry, PID: 15430 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.india.chemistry/com.example.india.chemistry.FifthActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2420)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2569)
at android.app.ActivityThread.access$900(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1399)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:107)
at com.example.india.chemistry.FifthActivity.<init>(FifthActivity.java:21)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1085)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2410)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2569) 
at android.app.ActivityThread.access$900(ActivityThread.java:150) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1399) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:168) 
at android.app.ActivityThread.main(ActivityThread.java:5885) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687) 
Please help me.
You can't call getApplicationContext(result in null) before oncreate because activity has not been created properly yet so you need to call this once your oncreate has been executed or after the super call .
The super call of onCreate fetches the application context for your activity.
Solution :
So either put your code inside oncreate or create a function and call it from inside oncreate after the super call.
Note : you will have to avoid final to make your identifiers global because the lazy initialization with final only works with constructors but don't worry , onCreate gets executed once when your activity is created or recreated.
Try this and let me know if problem solved or not.....
Animation shake,bounce;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fifth);
shake = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.shake);
bounce = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce);
}
You need to add the activity in your manifest file, under application. Whenever you create a new activity add it to manifest file.
<application
...
<activity
android:name=". FifthActivity"
android:label="Fifth" />
...
</application>
Hope this helps.
try this:
public class FifthActivity extends ActionBarActivity {
Animation shake,bounce;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fifth);
shake = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.shake);
bounce = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce);
}
Your view has not yet been created, move :
shake = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.shake);
bounce = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce);
To your oncreate method.
stack trace's first line gives Detailed information : getApplicationContext()' on a null object reference.Means Activity was not created,it's return null Context. You make a both animation's Object Globally. try to edit your code this way.
public class FifthActivity extends ActionBarActivity {
Animation shake,bounce;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fifth);
shake = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.shake);
bounce = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce);
}
}

To Do app crash

I'm trying to make a To Do app in android studio. But as soon as I click on add-button (+ in top right corner) the app crashes. I am very new to java and android studio but I think the problem may lay in "saveListInfo()" but I can't figure out how to fix it...
Code from EditedActivity.java:
public class EditedActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edited);
String name;
name = getIntent().getStringExtra("theName");
EditText editList = (EditText) findViewById(R.id.editText);
editList.setText(name);
}
private void saveListInfo() {
EditText editList = (EditText) findViewById(R.id.editText);
String name = editList.getText().toString();
Bundle listBundle = new Bundle();
listBundle.putString("name", name);
Intent finalIntent = new Intent(this, MainActivity.class);
finalIntent.putExtras(listBundle);
setResult(RESULT_OK, finalIntent);
}
Button addBtn = (Button) findViewById(R.id.add_btn);
{
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveListInfo();
}
});
}
}
Code from MainActivity.java:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add_task:
saveTodoInfo();
}
return true;
}
private void saveTodoInfo(){
TextView nameView = (TextView) findViewById(R.id.action_add_task);
String name = nameView.getText().toString();
Intent myIntent = new Intent(this, EditedActivity.class);
myIntent.putExtra("theName", name);
startActivityForResult(myIntent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0){
if(resultCode == RESULT_OK){
Bundle ListBundle = data.getExtras();
String name = ListBundle.getString("theName");
updateToDo(name);
}
}
}
private void updateToDo(String name){
TextView nameView = (TextView) findViewById(R.id.action_add_task);
nameView.setText(name);
}
}
This is the error I get when clicking the add-button:
02-12 16:07:40.553 1410-1410/com.carpe_diem.anitas_todolist
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.carpe_diem.anitas_todolist, PID: 1410
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.carpe_diem.anitas_todolist/com.carpe_diem.anitas_todolist.EditedActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.view.View android.view.Window.findViewById(int)' on a null
object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'android.view.View android.view.Window.findViewById(int)' on a
null object reference
at android.app.Activity.findViewById(Activity.java:2090)
at
com.carpe_diem.anitas_todolist.EditedActivity.(EditedActivity.java:40)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
By the logs, we can see that you crash is happening in following line:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference at
android.app.Activity.findViewById(Activity.java:2090) at
com.carpe_diem.anitas_todolist.EditedActivity.(EditedActivity.java:40)
...
After checking your code, I can find in line 40 (EditedActivity.java:40) that following code is outside of any method or function.
Button addBtn = (Button) findViewById(R.id.add_btn);
{
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveListInfo();
}
});
}
So, you have to move the lines above to onCreate() method.
EditedActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edited);
String name;
name = getIntent().getStringExtra("theName");
EditText editList = (EditText) findViewById(R.id.editText);
editList.setText(name);
Button addBtn = (Button) findViewById(R.id.add_btn);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveListInfo();
}
});
}
Root Cause
If you leave the line below outside of any method, it will run during object instantiation.
Button addBtn = (Button) findViewById(R.id.add_btn);
However, during object creation, the view was not created yet. So, findViewById wont find anything and will return null. Thus, that CRASH (or Force Close) will happen.
Solution
So, make sure to add findViewById() inside a method which is called after the view was already created (otherwise, it will never find the view).
As you can see, I suggested to add at onCreate() method after setContentView(R.layout.activity_edited) (which is responsible to add the objects to VIEW).
After that line, findViewById() will be able to find the views (if you add them in the layout, of course).
Remove the brackets around this code
{
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveListInfo();
}
});
}
Should look like this
Button addBtn = (Button) findViewById(R.id.add_btn);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveListInfo();
}
});
If you want to know why the crash happened, you can read more about What is an initialization block?

Categories