This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
$ error in androidmonitor
02-02 14:22:48.870 3269-3269/com.example.applincatio.t E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.applincatio.t, PID: 3269
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.applincatio.t/com.example.applincatio.t.moddle}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.webkit.WebView.setWebChromeClient(android.webkit.WebChromeClient)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.webkit.WebView.setWebChromeClient(android.webkit.WebChromeClient)' on a null object reference
at com.example.applincatio.t.moddle.onCreate(moddle.java:20)
at android.app.Activity.performCreate(Activity.java:6664)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
$main activity.java
package com.example.applincatio.t;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import static com.example.applincatio.t.R.*;
import static com.example.applincatio.t.R.id.moddle1;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ImageView moddle;
ImageButton outlook;
ImageButton contactus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_main);
moddle = (ImageView) findViewById(moddle1);
ImageView moddle = (ImageView) findViewById(moddle1);
moddle.setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case moddle1:
Intent imprintIntent = new Intent(MainActivity.this, moddle.class);
imprintIntent.putExtra("webivew", moddle1);
this.startActivity(imprintIntent);
break;
case id.outlook:
Intent contactIntent = new Intent(MainActivity.this, moddle.class);
// contactIntent.putExtra("webivewContact", outlook);
this.startActivity(contactIntent);
break;
case id.contactus:
Intent aboutIntent = new Intent(MainActivity.this, moddle.class);
//aboutIntent.putExtra("webivewAbout", contactus);
this.startActivity(aboutIntent);
break;
}
}
}
$moddle.java
package com.example.applincatio.t;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
public class moddle extends AppCompatActivity {
String url;
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.web_link);
webView.clearCache(true);
webView.clearHistory();
webView.getSettings().setJavaScriptEnabled(true);
Intent intent = this.getIntent();
if (intent != null) {
Bundle data = getIntent().getExtras();
if (data.containsKey("webivew")) { //i have changed this param to match the intent passed
url = data.getString("webivew");
}
if (data.containsKey("webivewContact")) {
url = data.getString("webivewContact");
}
if (data.containsKey("webivewAbout")) {
url = data.getString("webivewAbout");
}
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView wView, int progress) {
// webViewActivity.setTitle("Loading...");
// webViewActivity.requestWindowFeature(progress * 100);
if(progress == 100) {
// webViewActivity.setTitle(R.string.app_name);
}
}
});
webView.loadUrl(url);
}
}
}
$activitymain.xml
<?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:id="#+id/activity_main"
android:layout_width="match_parent"
android:background="#drawable/p"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.applincatio.t.MainActivity"
android:weightSum="1">
<GridLayout
android:layout_width="match_parent"
android:rowCount="4"
android:columnCount="2"
android:layout_height="530dp"
android:alignmentMode="alignMargins"
android:columnOrderPreserved="false"
android:id="#+id/gridview"
android:padding="14dp">
<LinearLayout
android:layout_gravity="center_horizontal|center_vertical"
android:layout_margin="16dp"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="#+id/moddle1"
android:src="#drawable/moddle"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MODDLE"
android:textColor="#fff"
android:textStyle="bold"
android:textAppearance="#style/TextAppearance.AppCompat.Headline" />
</LinearLayout>
<LinearLayout
android:layout_gravity="center_horizontal|center_vertical"
android:layout_margin="16dp"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageButton
android:layout_width="96dp"
android:layout_height="139dp"
android:id="#+id/outlook"
android:layout_gravity="center"
android:src="#drawable/ou"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OUTLOOK"
android:gravity="bottom"
android:textAlignment="center"
android:textColor="#ffffff"
android:textStyle="bold"
android:textAppearance="#style/TextAppearance.AppCompat.Headline" />
</LinearLayout>
<LinearLayout
android:layout_gravity="center_horizontal|center_vertical"
android:layout_margin="16dp"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageButton
android:layout_width="122dp"
android:layout_height="141dp"
android:layout_gravity="center"
android:id="#+id/contactus"
android:src="#drawable/cont"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CONTACT US"
android:textSize="20dp"
android:textColor="#ffff"
android:textStyle="bold"
android:textAppearance="#style/TextAppearance.AppCompat.Headline" />
</LinearLayout>
<LinearLayout
android:layout_gravity="center_horizontal|center_vertical"
android:layout_margin="16dp"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageButton
android:layout_width="123dp"
android:layout_height="128dp"
android:onClick="onClick"
android:layout_gravity="center"
android:src="#drawable/vi"
android:id="#+id/visitus" />
<TextView
android:layout_width="wrap_content"
android:layout_height="48dp"
android:text="VISIT US"
android:gravity="bottom"
android:textAlignment="center"
android:textColor="#ffffff"
android:textStyle="bold"
android:textAppearance="#style/TextAppearance.AppCompat.Headline" />
</LinearLayout>
</GridLayout>
</LinearLayout>
when i run the app. it is running but when i click on any imagebutton the app keeps stopping. i cant understand the mistake i did .in image you can see my layout its running but imagebuttons are not working
please any one help me
thanks in advance
Try the below one,
package com.example.applincatio.t;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
public class moddle extends AppCompatActivity {
String url;
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.web_link);
webView.clearCache(true);
webView.clearHistory();
webView.getSettings().setJavaScriptEnabled(true);
Intent intent = this.getIntent();
if (intent != null) {
Bundle data = getIntent().getExtras();
if (data.containsKey("webview")) {
url = data.getString("webview");
}
if (data.containsKey("webivewContact")) {
url = data.getString("webivewContact");
}
if (data.containsKey("webivewAbout")) {
url = data.getString("webivewAbout");
}
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView wView, int progress) {
// webViewActivity.setTitle("Loading...");
// webViewActivity.requestWindowFeature(progress * 100);
if(progress == 100) {
// webViewActivity.setTitle(R.string.app_name);
}
}
});
url = "https://moodle.kluniversity.in/login/index.php";
webView.loadUrl(url);
}
}
}
Thanks!
Related
I have a null pointer exception but I can't see where I am going wrong. I have been trying to fix this error for 2 days.
Here is the activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
and the Code for the class MainActivity
package com.example.servicestest1;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity{
private static final String TAG = "MainActivity";
private ArrayList<String> mDescriptions = new ArrayList<>();
private ArrayList<String> mStartDates = new ArrayList<>();
private ArrayList<String> mEndDates = new ArrayList<>();
private ArrayList<String> mImageUrls = new ArrayList<>();
private ArrayList<String> mTopicList = new ArrayList<>();
RecyclerView recyclerView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
initRecyclerViewItems();
}
private void initRecyclerViewItems() {
Log.d(TAG, "initRecyclerViewItems: preparing items");
addRecyclerViewItem("https://i.redd.it/3p6500yf3he41.jpg","Hogwarts Express","Working for the soviet union"
,"20/01/1968","20/10/1984");
addRecyclerViewItem("https://i.redd.it/s8bmctrhdxd41.jpg","Some scene about Nature","Some title",
"20/09/1897","20/03/1989");
addRecyclerViewItem("https://i.redd.it/lrbmhm707rd41.jpg","Boating","Boating in a pristine location",
"30/09/1998","31/09/1998");
initRecyclerView();
}
private void addRecyclerViewItem(String imageUrl, String topic, String description, String startDate, String endDate){
Log.w(TAG, "addRecyclerViewItem: called", null);
mImageUrls.add(imageUrl);
mTopicList.add(topic);
mStartDates.add(startDate);
mEndDates.add(endDate);
mDescriptions.add(description);
}
private void initRecyclerView(){
RecyclerViewAdapter adapter = new RecyclerViewAdapter(this,mTopicList,mDescriptions,
mStartDates,mEndDates,mImageUrls);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
The recyclerView.setAdapter returns a NullPointer exeception even though I have defined the adapter.
and the code for the RecyclerView adapter
package com.example.servicestest1;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private static final String TAG = "RecyclerViewAdapter";
private ArrayList<String> mTopicListOfTheEvent;
private ArrayList<String> mDescriptionListOfTheEvent;
private ArrayList<String> mStartDateListOfTheEvent;
private ArrayList<String> mEndDateListOfTheEvent;
private ArrayList<String> mImageListDescribingTheEvent;
private Context mContext;
RecyclerViewAdapter(Context context,
ArrayList<String> topicListOfTheEvent,
ArrayList<String> descriptionListOfTheEvent,
ArrayList<String> startDateListOfTheEvent,
ArrayList<String> endDateListOfTheEvent,
ArrayList<String> imageListDescribingTheEvent){
this.mContext = context;
this.mTopicListOfTheEvent = topicListOfTheEvent;
this.mDescriptionListOfTheEvent = descriptionListOfTheEvent;
this.mStartDateListOfTheEvent = startDateListOfTheEvent;
this.mEndDateListOfTheEvent = endDateListOfTheEvent;
this.mImageListDescribingTheEvent = imageListDescribingTheEvent;
}
#NonNull
#Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_recycler_view_layout,parent,true);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewAdapter.ViewHolder holder, int position) {
Log.d(TAG, "onBindViewHolder: called");
holder.descriptionOfTheEvent.setText(mDescriptionListOfTheEvent.get(position));
holder.imageDescribingTheEvent.setImageURI(Uri.parse(mImageListDescribingTheEvent.get(position)));
holder.startDateOfTheEvent.setText(mStartDateListOfTheEvent.get(position));
holder.endDateOfTheEvent.setText(mEndDateListOfTheEvent.get(position));
holder.topicListOfTheEvent.setText(mTopicListOfTheEvent.get(position));
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Clicked on");
Toast.makeText(mContext,"You pressed me",Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return mTopicListOfTheEvent.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView descriptionOfTheEvent;
TextView topicListOfTheEvent;
TextView startDateOfTheEvent;
TextView endDateOfTheEvent;
ImageView imageDescribingTheEvent;
LinearLayout parentLayout;
ViewHolder(#NonNull View itemView) {
super(itemView);
parentLayout = itemView.findViewById(R.id.recycler_view_item);
}
}
}
and the code for the activity_recycler_view_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/recycler_view_item">
<!-- The code for the AppBar -->
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="44dp"
android:background="#FFFEFE"
android:elevation="5dp"
tools:targetApi="lollipop">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginTop="8dp"
android:src="#drawable/bottom_lotus"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="ContentDescription" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="11dp"
android:layout_height="44dp"
android:layout_marginStart="18dp"
android:layout_marginLeft="18dp"
android:layout_marginTop="17dp"
android:layout_marginBottom="10dp"
android:src="#drawable/arrow"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="ContentDescription" />
<TextView
android:id="#+id/textView"
android:layout_width="66dp"
android:layout_height="44dp"
android:layout_marginStart="49dp"
android:layout_marginLeft="49dp"
android:layout_marginTop="13dp"
android:layout_marginBottom="10dp"
android:lineHeight="21sp"
android:text="Services"
android:textColor="#403E42"
android:textSize="16sp"
app:fontFamily="#font/roboto_condensed_regular"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profile_picture"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:layout_alignParentRight="true"
android:layout_marginLeft="4dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:src="#drawable/ic_launcher_background"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</androidx.appcompat.widget.Toolbar>
<RelativeLayout
android:layout_width="348dp"
android:layout_height="296dp"
android:layout_margin="6dp">
<ImageView
android:layout_width="348dp"
android:layout_height="296dp"
android:src="#drawable/images" />
<TextView
android:id="#+id/topic_text_view"
android:layout_width="wrap_content"
android:layout_height="28dp"
android:layout_marginStart="25dp"
android:layout_marginLeft="25dp"
android:layout_marginTop="25dp"
android:alpha="0.41"
android:text="It's His Birthday"
android:textColor="#f93f3f"
android:textSize="21sp"
app:fontFamily="#font/roboto_condensed_bold" />
<!--This LinearLayout is used for drawing the text inside the rectangle -->
<LinearLayout
android:layout_width="242dp"
android:layout_height="51dp"
android:layout_marginLeft="26dp"
android:layout_marginTop="64dp"
android:background="#drawable/rectangle"
android:orientation="vertical"
android:layout_marginStart="26dp">
<TextView
android:layout_width="198dp"
android:layout_height="32dp"
android:gravity="center"
android:lineHeight="16dp"
android:text="This is Sample Text"
android:textColor="#ffffff"
android:textSize="12sp"
app:fontFamily="#font/roboto_bold" />
</LinearLayout>
<TextView
android:layout_width="37dp"
android:layout_height="19dp"
android:layout_marginStart="26dp"
android:layout_marginLeft="26dp"
android:layout_marginTop="142dp"
android:lineHeight="19dp"
android:text="Dates"
android:textColor="#FFFFFF"
android:textSize="14sp"
app:fontFamily="#font/roboto_condensed_bold" />
<LinearLayout
android:layout_width="86dp"
android:layout_height="35dp"
android:layout_marginStart="62dp"
android:layout_marginLeft="62dp"
android:layout_marginTop="142dp"
android:orientation="vertical">
<TextView
android:id="#+id/start_date_of_the_event"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineHeight="16dp"
android:text="12 June 2019"
android:textColor="#ffffff"
android:textSize="12sp"
app:fontFamily="#font/roboto" />
<TextView
android:id="#+id/end_date_of_the_event"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineHeight="16dp"
android:text="13 June 2019"
android:textColor="#ffffff"
android:textSize="12sp"
app:fontFamily="#font/roboto" />
</LinearLayout>
</RelativeLayout>
<TextView
android:id="#+id/reject_button"
android:layout_width="35dp"
android:layout_height="16dp"
android:layout_marginStart="160dp"
android:layout_marginLeft="160dp"
android:layout_marginTop="15dp"
android:clickable="true"
android:text="REJECT"
android:textColor="#4B0082"
android:textStyle="bold"
tools:ignore="KeyboardInaccessibleWidget" />
<Button
android:id="#+id/accept_button"
android:layout_width="103dp"
android:layout_height="37dp"
android:layout_marginStart="248dp"
android:layout_marginLeft="248dp"
android:background="#4B0082"
android:text="ACCEPT"
android:textColor="#ffffff"
android:textSize="20sp" />
</LinearLayout>
And the here are the errors
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.servicestest1/com.example.servicestest1.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference
at com.example.servicestest1.MainActivity.initRecyclerView(MainActivity.java:53)
at com.example.servicestest1.MainActivity.initRecyclerViewItems(MainActivity.java:38)
at com.example.servicestest1.MainActivity.onCreate(MainActivity.java:27)
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)
recyclerView variable is set after its usage, so it's null when you try to set adapter.
Assign recyclerView before setting the adapter
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
initRecyclerViewItems();
}
in Java, calling findViewById(...) initializes the view variable. The variable is usually null when findViewById(..) hasn't been called yet or has been called with an id from a layout which hasn't been inflated yet. In your case. You can fix the error simply by changing your onCreate method.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view); //recyclerView gets initialized here
initRecyclerViewItems();
}
Google docs on findViewById
It takes some time to inflate recycler view. Try to add waiting cycle:
recyclerView = findViewById(R.id.recycler_view);
while (recyclerView == null){
Thread.sleep(1);
}
init();
Am getting a null pointer exception after setting the onclick listeners on the textview and the button. Where could be the error be please?
MainActivity.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:background="#drawable/background_design"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Login"
android:textAppearance="?android:textAppearanceLarge"
android:textColor="#ffffff"></TextView>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your email..."
android:textColorHint="#android:color/white"
android:textColor="#ffffff"
android:background="#drawable/ed_design"
android:padding="10dp"
android:inputType="textEmailAddress"
android:layout_margin="10dp"
android:id="#+id/email_login"></EditText>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your password..."
android:textColorHint="#android:color/white"
android:textColor="#ffffff"
android:background="#drawable/ed_design"
android:padding="10dp"
android:layout_margin="10dp"
android:inputType="textPassword"
android:id="#+id/pass_login"></EditText>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/login_button"
android:text="Login"
android:textAllCaps="false"
android:background="#drawable/ed_design"
android:padding="10dp"
android:textColor="#android:color/white"
android:textAppearance="?android:textAppearanceMedium"
android:layout_margin="10dp"></Button>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:textAppearanceSmall"
android:text="don't have an account? REGISTER here"
android:id="#+id/toRegisterActivity"
android:gravity="center"
android:textColor="#android:color/white"
android:padding="5dp"></TextView>
</LinearLayout>
</ScrollView>
</LinearLayout>
MainActivity.java file
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity {
private EditText email, pass;
private Button login_button;
private TextView toRegisterActivity;
private ProgressDialog progressDialog;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
email = findViewById(R.id.email_login);
pass = findViewById(R.id.pass_login);
login_button = findViewById(R.id.login_button);
toRegisterActivity = findViewById(R.id.toRegisterActivity);
progressDialog = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
toRegisterActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent registerIntent = new Intent(MainActivity.this, RegistrationActivity.class);
startActivity(registerIntent);
}
});
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String mEmail = email.getText().toString().trim();
String mPass = pass.getText().toString().trim();
if (TextUtils.isEmpty(mEmail)){
email.setError("Email required!");
return;
}
if (TextUtils.isEmpty(mPass)){
pass.setError("Password required!");
return;
}
else {
progressDialog.setTitle("Login in ...");
progressDialog.setMessage("please wait as we log you in.");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
mAuth.signInWithEmailAndPassword(mEmail,mPass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_SHORT).show();
Intent homeIntent = new Intent(MainActivity.this, HomeActivity.class);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(homeIntent);
finish();
progressDialog.dismiss();
}else {
String errorMsg = task.getException().toString();
Toast.makeText(MainActivity.this, "Login Failed, please try again."+ errorMsg, Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
}
}
});
}
}
StackTrace
11-04 21:25:31.840 16416-16416/com.example.checkmydailyspend E/Zygote: MountEmulatedStorage()
11-04 21:25:31.840 16416-16416/com.example.checkmydailyspend E/Zygote: v2
11-04 21:25:31.840 16416-16416/com.example.checkmydailyspend E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
11-04 21:25:33.202 16416-16416/com.example.checkmydailyspend E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.checkmydailyspend, PID: 16416
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.checkmydailyspend/com.example.checkmydailyspend.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3160)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3275)
at android.app.ActivityThread.access$1000(ActivityThread.java:218)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1744)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:7007)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.checkmydailyspend.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:6609)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3113)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3275)
at android.app.ActivityThread.access$1000(ActivityThread.java:218)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1744)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:7007)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Change setContentView(R.layout.activity_registration); to setContentView(R.layout.MainActivity);
Clicking on register makes the app crash when the email and password fields are empty, but when the name field is empty it works properly what seems to be the problem?
xml file:
<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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:gravity="center_vertical|center_horizontal"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.zachmarcelo.softcash.LoginActivity"
android:background="#fff"
>
<!-- Login progress -->
<ImageView
android:layout_width="match_parent"
android:layout_height="47dp"
android:layout_marginBottom="20dp"
android:visibility="visible"
app:srcCompat="#drawable/icon_ewallet_" />
<ProgressBar
android:id="#+id/login_progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:visibility="gone" />
<ScrollView
android:id="#+id/login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center">
<LinearLayout
android:id="#+id/email_login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColorHint="#color/colorHint" >
<EditText
android:id="#+id/reg_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:inputType="text"
android:textSize="20sp"
android:textColor="#android:color/background_dark"
/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/TextLabel"
android:textColorHint="#color/colorHint">
<EditText
android:id="#+id/reg_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#android:color/darker_gray"
android:hint="Email"
android:maxLines="1"
android:singleLine="true"
android:textColor="#android:color/background_dark"
android:inputType="textEmailAddress"
/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/TextLabel"
android:textColorHint="#color/colorHint">
<EditText
android:id="#+id/reg_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#android:color/background_dark"
android:hint="Password"
android:imeActionId="6"
android:imeActionLabel="#string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true"
android:textColor="#android:color/background_dark" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/register"
style="?android:textAppearanceSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="#color/colorAccent"
android:gravity="center"
android:paddingLeft="20sp"
android:paddingRight="20sp"
android:text="Register"
android:textStyle="bold"
android:layout_marginBottom="20dp"/>
<TextView
android:id="#+id/signin"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Already have an account?"
android:textAlignment="center"
android:textColor="#color/colorPrimary"
android:textSize="12dp" />
</LinearLayout>
</ScrollView>
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
code:
package com.example.zachmarcelo.softcash;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.view.WindowManager;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
public class RegisterActivity extends AppCompatActivity implements
View.OnClickListener {
private EditText reg_password,
reg_username,
reg_email;
private FirebaseAuth mAuth;
private ProgressBar progressBar;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
progressBar = new ProgressBar(getApplicationContext());
reg_password = findViewById(R.id.reg_password);
reg_email = findViewById(R.id.reg_email);
reg_username = findViewById(R.id.reg_username);
progressBar = findViewById(R.id.progressBar);
progressBar.setVisibility(View.GONE);
mAuth = FirebaseAuth.getInstance();
findViewById(R.id.register).setOnClickListener(this);
findViewById(R.id.signin).setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
if (mAuth.getCurrentUser() != null) {
Intent i = new Intent(RegisterActivity.this, HomeActivity.class);
startActivity(i);
finish();
}
}
private void registerUser() {
final String username = reg_username.getText().toString().trim();
final String email = reg_email.getText().toString().trim();
String password = reg_password.getText().toString().trim();
if (username.equals("")) {
reg_username.setError(getString(R.string.input_error_name));
reg_username.requestFocus();
return;
}
if (email.equals("")) {
reg_email.setError(getString(R.string.input_error_email));
reg_email.requestFocus();
return;
}else{
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
reg_email.setError(getString(R.string.input_error_email_invalid));
reg_email.requestFocus();
return;
}
}
if (password.equals("")) {
reg_password.setError(getString(R.string.input_error_password));
reg_password.requestFocus();
return;
}else{
if (password.length() < 8) {
reg_password.setError(getString(R.string.input_error_password_length));
reg_password.requestFocus();
return;
}
}
progressBar.setVisibility(View.VISIBLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
User user = new User(
username,
email
);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
progressBar.setVisibility(View.GONE);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
if (task.isSuccessful()) {
Toast.makeText(RegisterActivity.this, getString(R.string.registration_success), Toast.LENGTH_LONG).show();
Intent i = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(i);
finish();
} else {
Toast.makeText(RegisterActivity.this, getString(R.string.registration_failed), Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(RegisterActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.register:
registerUser();
break;
case R.id.signin:
Intent i = new Intent(this, LoginActivity.class);
startActivity(i);
finish();
break;
}
}
}
error log:
09-03 13:25:24.942 15875-15875/com.example.zachmarcelo.softcash E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.zachmarcelo.softcash, PID: 15875
android.view.InflateException: Binary XML file line #17: Binary XML file line #17: Error inflating class TextView
Caused by: android.view.InflateException: Binary XML file line #17: Error inflating class TextView
Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 4: TypedValue{t=0x2/d=0x1010099 a=1}
at android.content.res.TypedArray.getColor(TypedArray.java:492)
at android.widget.TextView.<init>(TextView.java:955)
at android.widget.TextView.<init>(TextView.java:872)
at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:75)
at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:71)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:103)
at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1024)
at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1081)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:783)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:741)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.widget.Editor.showError(Editor.java:505)
at android.widget.Editor.onFocusChanged(Editor.java:1237)
at android.widget.TextView.onFocusChanged(TextView.java:9821)
at android.view.View.handleFocusGainInternal(View.java:6631)
at android.view.View.requestFocusNoSearch(View.java:10890)
at android.view.View.requestFocus(View.java:10869)
at android.view.View.requestFocus(View.java:10836)
at android.view.View.requestFocus(View.java:10778)
at com.example.zachmarcelo.softcash.RegisterActivity.registerUser(RegisterActivity.java:74)
at com.example.zachmarcelo.softcash.RegisterActivity.onClick(RegisterActivity.java:143)
at android.view.View.performClick(View.java:6291)
at android.view.View$PerformClick.run(View.java:24931)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:101)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7425)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
and this is what is supposed to be happening: (works perfectly in name text but not in other edittexts)
screenshot of mobile app
any help will be appreciated :D
My guess is that it has something to do with what you put into #style/TextLabel.
When you have an error with password or email you request focus programmatically. Which is fine, however when that happens something in your style is looking for a color resource which doesn't exist. That's what's causing the error.
The error seems to be for getColor() method of textview, your primary color has some problem, please check that.
I have this problem and it shows me following error
please help me:
I get a NullPointerException in init2(). Apperently sms is null.
I don't understand the problem
Process: com.example.android.projectdestage, PID: 11049
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.android.projectdestage/com.example.android.projectdestage.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.view.View.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.view.View.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at
com.example.android.projectdestage.MainActivity.init2(MainActivity.java:60)
at
com.example.android.projectdestage.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:6956)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
****this is my main activity****
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
public class MainActivity extends AppCompatActivity
{
private Button sms;
private Button btnMap;
private static final String TAG = "MainActivity";
private static final int ERROR_DIALOG_REQUEST = 9001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
if(isServicesOK()){
init();
init2();
}
}
private void init(){
Button btnMap = (Button) findViewById(R.id.btnMap);
btnMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MapActivity.class);
startActivity(intent);
}
});
}
private void init2()
{
Button sms = (Button) findViewById(R.id.sms);
sms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent message = new Intent(MainActivity.this, MainActivity2.class);
startActivity(message);
}
});
}
public boolean isServicesOK()
{
Log.d(TAG, "isServicesOK: checking google services version");
int available = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(MainActivity.this);
if(available == ConnectionResult.SUCCESS)
{
// koulchi mli7 map request
Log.d(TAG, "isServicesOK: Google Play Services is working");
return true;
}
else if(GoogleApiAvailability.getInstance().isUserResolvableError(available))
{
//test d erreur
Log.d(TAG, "isServicesOK: an error occured but we can fix it");
Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(MainActivity.this, available, ERROR_DIALOG_REQUEST);
dialog.show();
}else
{
Toast.makeText(this, "You can't make map requests", Toast.LENGTH_SHORT).show();
}
return false;
}
}
`**this is my mainactivity 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="com.example.android.projectdestage.MainActivity">
<Button
android:id="#+id/btnMap"
android:layout_width="87dp"
android:layout_height="45dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="244dp"
android:text="#string/map"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.43"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/smsbtn"
android:layout_width="wrap_content"
android:layout_height="43dp"
android:layout_marginBottom="136dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="#string/enter_your_message"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.43"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>
**and the main2activity xml**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context="com.example.android.projectdestage.MainActivity2">
<TextView
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/enter_your_message"
android:textSize="30sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="519dp"
android:orientation="vertical">
<TextView
android:id="#+id/editText2"
android:layout_width="385dp"
android:layout_height="410dp"
android:layout_marginTop="50dp"
android:layout_weight="1"
android:text="#string/textview" />
<Button
android:id="#+id/btnSendSMSendSms"
android:layout_width="wrap_content"
android:layout_height="250dp"
android:layout_marginLeft="150dp"
android:layout_marginStart="150dp"
android:layout_marginVertical="110dp"
android:layout_weight="1"
android:text="#string/sendsms"
tools:targetApi="o" />
</LinearLayout>
</LinearLayout>
and the the mapactivity xml
i think the main problem is here
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
<fragment 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"
android:id="#+id/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:elevation="10dp"
android:background="#drawable/white_border"
android:id="#+id/relLayout1" tools:targetApi="lollipop">
<ImageView
android:layout_width="15dp"
android:layout_height="15dp"
android:id="#+id/ic_magnify"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:src="#drawable/ic_magnify" android:contentDescription="#string/todoo" android:layout_marginStart="10dp" />
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/ic_magnify"
android:layout_centerVertical="true"
android:textSize="15sp"
android:textColor="#000"
android:id="#+id/input_search"
android:background="#null"
android:hint="#string/enter_address_city_or_zip_code"
android:imeOptions="actionSearch" android:layout_toEndOf="#+id/ic_magnify" />
</RelativeLayout>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_below="#id/relLayout1"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:scaleType="centerCrop"
android:id="#+id/ic_gps"
android:src="#drawable/ic_gps" android:contentDescription="#string/todo" android:layout_alignParentEnd="true" android:layout_marginEnd="10dp" />
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/place_picker"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
android:scaleType="centerCrop"
android:layout_below="#+id/relLayout1"
android:src="#drawable/ic_map" android:contentDescription="#string/todoml" android:layout_marginStart="10dp" />
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_below="#+id/place_picker"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
android:scaleType="centerCrop"
android:id="#+id/place_info"
android:src="#drawable/ic_info" android:layout_marginStart="10dp" android:contentDescription="#string/todoop" />
</RelativeLayout>
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
Button sms = (Button) findViewById(R.id.sms); returns null
This means he can not find R.id.sms in your activity_main.xml layout.
Maybe a typo or copy paste error? Check if this button's ID in this file really is sms.
Also if you have multiple layouts for different screen sizes, etc. Check all of them.
You have smsBtn as an id for sms Button in your activity_main.xml, whereas you've passed sms as id. So id with sms is not found and so button is null and throws null pointer exception.
There is better approach that can accomplish this using Butterknife library:
public class MainActivity extends AppCompatActivity
{
#BindView(R.id.smsBtn)
private Button sms;
#BindView(R.id.btnMap)
private Button btnMap;
private static final String TAG = "MainActivity";
private static final int ERROR_DIALOG_REQUEST = 9001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
#OnClick({R.id.btnMap, R.id.smsBtn})
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnMap:
//Your functionality
break;
case R.id.smsBtn:
//Your functionality
break;
}
}
}
//Dependency for ButterKnife library
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
//Butterknife link
https://github.com/JakeWharton/butterknife
This question already has answers here:
Why does my Android app crash with a NullPointerException when initializing a variable with findViewById(R.id.******) at the beginning of the class?
(9 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
When i want to run app in my device i get this error in logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.allo/com.example.android.allo.WelcomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.setAnimation(android.view.animation.Animation)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.setAnimation(android.view.animation.Animation)' on a null object reference
at com.example.android.allo.WelcomeActivity.onCreate(WelcomeActivity.java:24)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
WelcomActivty.java :
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
public class WelcomeActivity extends AppCompatActivity {
LinearLayout l1,l2;
Button btnsub;
Animation uptodown,downtoup;
LinearLayout linearLayout=(LinearLayout) findViewById(R.id.l1);
LinearLayout linearLayout1=(LinearLayout) findViewById(R.id.l2);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
btnsub = (Button)findViewById(R.id.buttoncom);
uptodown = AnimationUtils.loadAnimation(this,R.anim.uptodown);
downtoup = AnimationUtils.loadAnimation(this,R.anim.downtoup);
l1.setAnimation(uptodown);
l2.setAnimation(downtoup);
}
protected void onStart(){
super.onStart();
linearLayout.startAnimation(uptodown);
linearLayout1.startAnimation(downtoup);
}
public void com(View view){
Intent intent = new Intent(this, Login.class);
Button buttoncom = (Button) findViewById(R.id.buttoncom);
startActivity(intent);
}
}
welcome.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.allo.WelcomeActivity"
android:background="#drawable/background"
android:orientation="vertical">
<LinearLayout
android:id="#+id/l1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="120dp"
android:text="#string/bienvenue"
android:textColor="#color/lightorange"
android:textSize="60sp"
android:textStyle="bold" />
<TextView
android:textColor="#color/lightorangedark"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/dans_quoi"
android:textAlignment="center"
android:textSize="20sp"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/l2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="115dp"
android:background="#drawable/spaceullustration"
android:orientation="vertical">
<Button
android:id="#+id/buttoncom"
android:layout_width="145dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#drawable/buttonstyle"
android:text="#string/button_commencer" />
</LinearLayout>
activity_login.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/backgroudlogin"
tools:context=".Login">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="232dp"
android:background="#drawable/ic_email_button"
android:hint=" Email"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="159dp"
android:background="#drawable/ic_email_button"
android:hint=" password"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="70dp"
android:background="#drawable/ic_sign_in"
android:text="Sign IN" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:text="create an account"
android:textSize="20dp"
android:textColor="#FFFFFF"/>
Login.xml
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class Login extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
}
i know, there is a lot of question in the forum with the same subject but I can not find the solution, so please do not mark the question as duplicated
You should do this way -
public class WelcomeActivity extends AppCompatActivity {
Button btnsub;
Animation uptodown,downtoup;
LinearLayout linearLayout;
LinearLayout linearLayout1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
linearLayout=(LinearLayout) findViewById(R.id.l1);
linearLayout1=(LinearLayout) findViewById(R.id.l2);
btnsub = (Button)findViewById(R.id.buttoncom);
uptodown = AnimationUtils.loadAnimation(this,R.anim.uptodown);
downtoup = AnimationUtils.loadAnimation(this,R.anim.downtoup);
linearLayout.setAnimation(uptodown);
linearLayout1.setAnimation(downtoup);
}
}