So I tried to make a port scanner and I got stuck on the way and i will love to get some explication of what am I doing wrong here(and almost every time) when I am starting a new activity.
P.S. :4rd time programing with java in my life.
My java:
package com.nliplace.nli.xxxx;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class portscan extends AppCompatActivity {
EditText Portaa = (EditText)findViewById(R.id.editText3);
EditText Portbb = (EditText)findViewById(R.id.editText4);
EditText Iptot = (EditText)findViewById(R.id.editText5);
TextView rez = (TextView)findViewById(R.id.textView18);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_portscan);
}
private static String available(String ip, int porta, int portb) {
String rezultat = "";
for (int port = porta; port <= portb; port++) {
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress("185.28.20.123", port), 1000);
socket.close();
rezultat = rezultat + "," + port;
} catch (Exception ex) {
}
}
return rezultat;
}
public void scanclick(View s) {
// Scaneaza
Iptot= (EditText)this.findViewById(R.id.editText3);
Portaa = (EditText)this.findViewById(R.id.editText4);
Portbb = (EditText)this.findViewById(R.id.editText5);
String portaa = Portaa.getText().toString();
int porta = Integer.parseInt(portaa);
String portbb = Portbb.getText().toString();
int portb = Integer.parseInt(portbb);
String ip = Iptot.getText().toString();
// available(ip, porta, portb);
//textView18
rez.setText(available(ip, porta, portb));
}
}
My XML:
<?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"
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.nliplace.nli.unealta.portscan">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Aceasta activitate scaneaza dupa port-uri deschise."
android:id="#+id/textView13"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Adresa:"
android:id="#+id/textView14" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText3"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Port A:"
android:id="#+id/textView15" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText4" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Port B:"
android:id="#+id/textView16" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText5" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scan"
android:id="#+id/button11"
android:layout_gravity="center_horizontal"
android:onClick="scanclick" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Aici se vor afisa porturile deschise:"
android:id="#+id/textView17"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="...va dura..."
android:id="#+id/textView18"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</RelativeLayout>
My challenge for you guys:
FATAL EXCEPTION: main
Process: com.nliplace.nli.unealta, PID: 20048
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.nliplace.nli.unealta/com.nliplace.nli.unealta.portscan}:
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:2551)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2769)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1430)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5910)
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:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
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:2172)
at com.nliplace.nli.unealta.portscan.(portscan.java:20)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1690)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2541)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2769)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1430)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5910)
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:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
You cant use findViewById() method before using setContentView() in onCreate(). Put find views inside onCreate() after setContentView() method like this:
public class portscan extends AppCompatActivity {
EditText Portaa;
EditText Portbb;
EditText Iptot;
TextView rez;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_portscan);
Portaa = (EditText)findViewById(R.id.editText3);
Portbb = (EditText)findViewById(R.id.editText4);
Iptot = (EditText)findViewById(R.id.editText5);
rez = (TextView)findViewById(R.id.textView18);
}...
You were basically trying to find something that doesnt exist.
Related
I am trying to make a form that includes students details and again show that detail in text views. When the user types the details in edit texts save them into the model class then show them again in text views. first, I have created a model class to save variables of students.
Logcat:
2021-11-09 13:12:47.784 30040-30040/com.example.studentapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.studentapp, PID: 30040
java.lang.NumberFormatException: For input string: "stephen"
at java.lang.Integer.parseInt(Integer.java:608)
at java.lang.Integer.parseInt(Integer.java:643)
at com.example.studentapp.MainActivity$1.onClick(MainActivity.java:52)
at android.view.View.performClick(View.java:6291)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
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:7529)
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)
XML file:
<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"
tools:context=".MainActivity">
<EditText
android:id="#+id/edit_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/name"
android:autofillHints="" />
<EditText
android:id="#+id/edit_age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Age"
android:autofillHints="" />
<EditText
android:id="#+id/edit_grade"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Grade"
android:autofillHints="" />
<EditText
android:id="#+id/edit_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Address"
/>
<EditText
android:id="#+id/edit_distance"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Distance"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp"
android:orientation="vertical">
<TextView
android:id="#+id/txtName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp" />
<TextView
android:id="#+id/txtAge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp" />
<TextView
android:id="#+id/txtGrade"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp" />
<TextView
android:id="#+id/txtAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp" />
<TextView
android:id="#+id/txtDistance"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp" />
<Button
android:text="View"
android:id="#+id/btnView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
</LinearLayout>
Model class:
package com.example.studentapp;
public class Student {
public String name = "";
public int age = 0;
public int grade = 0;
public String address = "";
public double distance = 0;
}
This is .java file:
package com.example.studentapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button buttonView;
EditText editName;
EditText editAge;
EditText editGrade;
EditText editAddress;
EditText editDistance;
TextView textName, textAge, textGrade, textAddress, textDistance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editName = findViewById(R.id.edit_name);
editAge = findViewById(R.id.edit_age);
editGrade = findViewById(R.id.edit_grade);
editAddress = findViewById(R.id.edit_address);
editDistance = findViewById(R.id.edit_distance);
textName = findViewById(R.id.txtName);
textAge = findViewById(R.id.txtAge);
textGrade = findViewById(R.id.txtGrade);
textAddress = findViewById(R.id.txtAddress);
textDistance = findViewById(R.id.txtDistance);
buttonView = findViewById(R.id.btnView);
buttonView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Student student1 = new Student();
student1.name = editName.getText().toString();
student1.age = Integer.parseInt(editAge.getText().toString());
student1.grade = Integer.parseInt( editName.getText().toString());
student1.address = editName.getText().toString();
student1.distance = Double.parseDouble( editName.getText().toString());
textName.setText(student1.name);
textAge.setText(""+student1.age);
textGrade.setText(student1.grade+" Years");
textAddress.setText(student1.address);
textDistance.setText(student1.distance+"km");
}
});
}
}
Please, bear in mind that I am a very beginner at android development.
student1.distance = Double.parseDouble(editName.getText().toString());
You are using editName for getting distance grade and address. Please, change them according to your needs.
Your code
student1.grade = Integer.parseInt( editName.getText().toString());
student1.distance = Double.parseDouble( editName.getText().toString());
Expected code
student1.grade = Integer.parseInt( editGrade.getText().toString());
student1.distance = Double.parseDouble( editDistance.getText().toString());
Your are trying to parse string to integer Integer.parseInt( editName.getText().toString()). It won't work for non numbers input.
Looking at your Locat message, it seems you're saving the String name in an Integer variable, kindly look at your codebase to see if you're making that mistake, if so reassign the name variable to a string variable.
You are using wrong editText for grade and distance.
your code:
student1.grade = Integer.parseInt(editName.getText().toString());
change editName to editGrade :
student1.grade = Integer.parseInt(editGrade.getText().toString());
aswell for:
student1.distance = Double.parseDouble(editName.getText().toString());
change editName to editDistance:
student1.distance = Double.parseDouble(editDistance.getText().toString());
I want to show current weather data in fragment on search CityName base. Mean if I entered any city name in searchbox it show me the current weather of that city. All work was performing correctly if I give static City name, but I want that which city I select it give me this current data.
The SearchBox (EditText) is on Main Activity and currentweather data Method where I want to show my currentweather data is in Fragment. How it is possible to search on Main Activity and show currentweather data in fragment layout.
MainActivity
package com.deitel.apiretrofitfragmentweatherapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.deitel.apiretrofitfragmentweatherapp.Adapter.FragementViewAdapter;
import com.deitel.apiretrofitfragmentweatherapp.Fragment.currentweather;
import com.google.android.material.tabs.TabLayout;
public class MainActivity extends AppCompatActivity {
private static FragmentManager fragmentManager;
public static String BaseUrl = "http://api.openweathermap.org/";
public static String AppId = "08fd7374790f2ccee9f1f1dbfae38fdf";
/* public static String lat = "33.69";
public static String lon = "73.06";*/
ViewPager viewPager;
FragementViewAdapter fragementViewAdapter;
TabLayout tabLayout;
EditText text_search;
ImageButton btn_search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
text_search = findViewById(R.id.text_search_city);
tabLayout = findViewById(R.id.tab_layout);
viewPager = findViewById(R.id.fragment_container);
btn_search = findViewById(R.id.btn_search);
final currentweather currentweather = new currentweather();
btn_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager=getSupportFragmentManager();
currentweather weather= (currentweather) manager.findFragmentById(R.id.current_weather);
assert weather != null;
weather.getCurrentData();
String City= text_search.getText().toString().trim();
Bundle bundle = new Bundle();
bundle.putString("search_city", City);
currentweather.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.fragment_container, currentweather).commit();
currentweather.getCurrentData();
if (TextUtils.isEmpty(City)) {
text_search.setError("Enter City Name");
return;
}
}
});
fragementViewAdapter = new FragementViewAdapter(getSupportFragmentManager());
viewPager.setAdapter(fragementViewAdapter);
tabLayout.setupWithViewPager(viewPager);
fragmentManager = getSupportFragmentManager();
}
}
CurrentWeatherFragment
package com.deitel.apiretrofitfragmentweatherapp.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import com.deitel.apiretrofitfragmentweatherapp.CurrentWeather.WeatherResponse;
import com.deitel.apiretrofitfragmentweatherapp.R;
import com.deitel.apiretrofitfragmentweatherapp.Retrofit.WeatherService;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import static com.deitel.apiretrofitfragmentweatherapp.MainActivity.AppId;
import static com.deitel.apiretrofitfragmentweatherapp.MainActivity.BaseUrl;
public class currentweather extends Fragment {
public TextView text_country,text_city,text_pressure,text_humidity,text_temp;
public TextView textView_country, textView_city, textView_temp,
textView_pressure, textView_humidity, textview_date;
/*public TextView text_view;*/
public currentweather() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View itemview=inflater.inflate(R.layout.fragment_currentweather, container, false);
textView_country = itemview.findViewById(R.id.textView_country);
textView_city =itemview.findViewById(R.id.textView_city);
textView_temp =itemview.findViewById(R.id.textview_temp);
textView_pressure =itemview.findViewById(R.id.textView_pressure);
textView_humidity =itemview.findViewById(R.id.textView_humidity);
textview_date =itemview.findViewById(R.id.textView_date);
text_country= itemview.findViewById(R.id.text_country);
text_city=itemview. findViewById(R.id.text_city);
/*text_view=itemview.findViewById(R.id.text_view);*/
text_pressure=itemview. findViewById(R.id.text_pressure);
text_humidity=itemview.findViewById(R.id.text_humidity);
text_temp=itemview.findViewById(R.id.text_temp);
/* Bundle bundle=getArguments();
if (bundle!=null)
{
city=bundle.getString("search_city");
textView_country.setText(city);
Log.d("ass",""+city);
}*/
text_country.setVisibility(View.GONE);
text_city.setVisibility(View.GONE);
text_pressure.setVisibility(View.GONE);
text_humidity.setVisibility(View.GONE);
text_temp.setVisibility(View.GONE);
return itemview;
}
public void getCurrentData() {
String City1 = null;
if (getArguments() != null){
City1=getArguments().getString("search_city");
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
WeatherService weatherService = retrofit.create(WeatherService.class);
Call<WeatherResponse> call = weatherService.getCurrentWeatherDataCityName(City1, AppId);
call.enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) {
if (response.code() == 200) {
WeatherResponse weatherResponse = (WeatherResponse) response.body();
assert weatherResponse != null;
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE-dd-MM");
String formatedate = simpleDateFormat.format(calendar.getTime());
/* String stringbuilder= "Country : " +
weatherResponse.sys.country +
"\n" +
"City : " +weatherResponse.name +
"\n" +
"Tempreture : " + weatherResponse.main.temp +
"\n" +
"Tempreture(Min) : " +
weatherResponse.main.temp_min +
"\n" +
"Tempreture(Max) : " +
weatherResponse.main.temp_max +
"\n" +
"Humidity : " +
weatherResponse.main.humidity +
"\n" +
"Pressure : " +
weatherResponse.main.pressure;*/
String Country = weatherResponse.sys.country;
String City = weatherResponse.name;
String Temp = String.valueOf(weatherResponse.main.temp);
Double calcius = Double.parseDouble(Temp) - 273.0;
Integer i = calcius.intValue();
String Pressure = String.valueOf(weatherResponse.main.pressure);
String Humidity = String.valueOf(weatherResponse.main.humidity);
textView_country.setText(Country);
textView_city.setText(City);
textView_temp.setText(String.valueOf(i));
textView_pressure.setText(Pressure);
textView_humidity.setText(Humidity);
textview_date.setText(formatedate);
text_country.setVisibility(View.VISIBLE);
text_city.setVisibility(View.VISIBLE);
text_pressure.setVisibility(View.VISIBLE);
text_humidity.setVisibility(View.VISIBLE);
text_temp.setVisibility(View.VISIBLE);
Toast.makeText(getContext(), "Successfully", Toast.LENGTH_SHORT).show();
}
if (response.code()==404)
{
Toast.makeText(getContext(), "City Not Founded", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call call, Throwable t) {
textView_country.setText(t.getMessage());
textView_city.setText(t.getMessage());
textView_temp.setText(t.getMessage());
textView_pressure.setText(t.getMessage());
textView_humidity.setText(t.getMessage());
textview_date.setText(t.getMessage());
}
});
}
}
Currentweatherframent.XML File
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/current_weather"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text_country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="Country"
android:textColor="#000"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView_date" />
<TextView
android:id="#+id/textView_country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text=""
android:textColor="#000"
android:textSize="17dp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_country" />
<TextView
android:id="#+id/text_city"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:text="City"
android:textColor="#000"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView_date" />
<TextView
android:id="#+id/textView_city"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:text=""
android:textColor="#000"
android:textSize="17dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_city" />
<TextView
android:id="#+id/text_temp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="90dp"
android:text="Temperature"
android:textColor="#000"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/textView_country"
app:layout_constraintTop_toBottomOf="#id/textView_date" />
<TextView
android:id="#+id/textview_temp"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginTop="40dp"
android:gravity="center"
android:text=""
android:textColor="#000"
android:textSize="40dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/text_temp" />
<TextView
android:id="#+id/text_pressure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Pressure"
android:textColor="#000"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textview_temp" />
<TextView
android:id="#+id/textView_pressure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text=""
android:textColor="#000"
android:textSize="17dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_pressure" />
<TextView
android:id="#+id/text_humidity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Humidity"
android:textColor="#000"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView_pressure" />
<TextView
android:id="#+id/textView_humidity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginBottom="32dp"
android:text=""
android:textColor="#000"
android:textSize="17dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_humidity" />-->
<TextView
android:id="#+id/textView_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text=""
android:textColor="#000"
android:textSize="17dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
Error
1-03 19:35:10.586 1428-1428/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.deitel.apiretrofitfragmentweatherapp, PID: 1428
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.widget.Toast.<init>(Toast.java:107)
at android.widget.Toast.makeText(Toast.java:264)
at com.deitel.apiretrofitfragmentweatherapp.Fragment.currentweather$1.onResponse(currentweather.java:129)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
01-03 21:43:00.695 10885-10885/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.deitel.apiretrofitfragmentweatherapp, PID: 10885
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.deitel.apiretrofitfragmentweatherapp/com.deitel.apiretrofitfragmentweatherapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.deitel.apiretrofitfragmentweatherapp.Fragment.currentweather.getCurrentData()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2572)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.deitel.apiretrofitfragmentweatherapp.Fragment.currentweather.getCurrentData()' on a null object reference
at com.deitel.apiretrofitfragmentweatherapp.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:6301)
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);
}
}
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!