Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am new in android. I created simple application,that contains autocomplete text field.I wrote some code but unfortunately application stopped when i run. there is no error, How do i fix...
Please any one help!
Mycode here:
Mainactivity.java
package com.h2o;
import android.app.Activity;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.location.Address;
import android.location.Geocoder;
import android.support.v4.app.DialogFragment;
import android.os.Bundle;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.support.annotation.Nullable;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
CustomDrawerAdapter adapter;
List<DrawerItem> dataList;
EditText mEdit;
private String[] states;
private Spinner spinner;
AutoCompleteTextView autoTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] city= getResources().getStringArray(R.array.city);
autoTextView = (AutoCompleteTextView) findViewById(R.id.city_autoCompleteTextView);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,city);
autoTextView.setThreshold(1);
autoTextView.setAdapter(arrayAdapter);
// Initializing
dataList = new ArrayList<DrawerItem>();
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// Add Drawer Item to dataList
dataList.add(new DrawerItem(true)); // adding a spinner to the list - 0
dataList.add(new DrawerItem("Wallet")); // adding a header to the list - 1
dataList.add(new DrawerItem("Balance", R.drawable.ic_balance)); // - 2
dataList.add(new DrawerItem("Profile"));// adding a header to the list - 3
dataList.add(new DrawerItem("Personal", R.drawable.ic_account));
dataList.add(new DrawerItem("Work", R.drawable.ic_account));
dataList.add(new DrawerItem("Address", R.drawable.ic_account));
dataList.add(new DrawerItem("Vehicle", R.drawable.ic_car));
dataList.add(new DrawerItem("Preference", R.drawable.ic_pref));
dataList.add(new DrawerItem("Other Option")); // adding a header to the list
dataList.add(new DrawerItem("About", R.drawable.ic_action_about));
dataList.add(new DrawerItem("Settings", R.drawable.ic_action_settings));
dataList.add(new DrawerItem("Help", R.drawable.ic_action_help));
adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
dataList);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
//Calendar picker
public void selectDate(View view) {
DialogFragment newFragment = new SelectDateFragment();
newFragment.show(getSupportFragmentManager(), "DatePicker");
}
public void populateSetDate(int year, int month, int day) {
mEdit = (EditText)findViewById(R.id.dobText);
mEdit.setText(month + "/" + day + "/" + year);
}
public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener
{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
public void onDateSet(DatePicker view, int yy, int mm, int dd) {
populateSetDate(yy, mm + 1, dd);
}
}
//Spinner
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void SelectItem(String item, int possition) {
Fragment fragment = null;
Bundle args = new Bundle();
switch(item) {
case "Balance": fragment = new BalanceFragment(); break;
case "Personal": fragment = new PersonalFragment(); break;
case "Work": fragment = new WorkFragment(); break;
case "Address": fragment = new AddressFragment(); break;
case "Vehicle": fragment = new VehicleFragment(); break;
case "Preference": fragment = new PreferenceFragment(); break;
case "About": fragment = new AboutFragment(); break;
case "Settings": fragment = new SettingsFragment(); break;
case "Help": fragment = new HelpFragment(); break;
default: fragment = new DefaultFragment(); break;
}
fragment.setArguments(args);
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
mDrawerList.setItemChecked(possition, true);
setTitle(dataList.get(possition).getItemName());
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return false;
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if (dataList.get(position).getTitle() == null) {
SelectItem(dataList.get(position).getItemName(), position);
}
}
}
}
log cat:
06-03 12:23:32.446 2843-2843/? I/art﹕ Not late-enabling -Xcheck:jni (already on)
06-03 12:23:32.637 2843-2843/com.h2o D/AndroidRuntime﹕ Shutting down VM
06-03 12:23:32.638 2843-2843/com.h2o E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.h2o, PID: 2843
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.h2o/com.h2o.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.AutoCompleteTextView.setThreshold(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.AutoCompleteTextView.setThreshold(int)' on a null object reference
at com.h2o.MainActivity.onCreate(MainActivity.java:73)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="40dp"
android:text="Address Details"
android:id="#+id/address"
android:textColor="#ff000000"
android:textSize="20dp"
android:layout_marginLeft="10dp"
android:gravity="center" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1"
android:layout_weight="0.03">
<TextView
android:layout_width="wrap_content"
android:layout_height="33dp"
android:text="Tag Address"
android:id="#+id/residential"
android:textColor="#ff000000"
android:layout_marginLeft="10dp"
android:layout_gravity="center"
android:gravity="center" />
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="276dp"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
android:weightSum="1">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Home"
android:id="#+id/home"
android:layout_gravity="center"
android:textColor="#FF000000"
android:checked="false"
android:layout_weight="0.22"
android:layout_marginLeft="10dp" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Office"
android:id="#+id/office"
android:textColor="#FF000000"
android:checked="false"
android:layout_gravity="center" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1"
android:layout_weight="0.06">
<TextView
android:layout_width="48dp"
android:layout_height="wrap_content"
android:text="Line 1"
android:id="#+id/address1"
android:textColor="#ff000000"
android:layout_marginLeft="10dp"
android:gravity="center" />
<EditText
android:layout_width="291dp"
android:layout_height="wrap_content"
android:inputType="textPostalAddress"
android:ems="10"
android:id="#+id/addressText"
android:layout_marginLeft="50dp"
android:textColor="#ff000000"
android:layout_weight="1.04" /> />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1"
android:layout_weight="0.06">
<TextView
android:layout_width="48dp"
android:layout_height="wrap_content"
android:text="Line 2"
android:id="#+id/address2"
android:textColor="#ff000000"
android:layout_marginLeft="10dp"
android:gravity="center" />
<EditText
android:layout_width="291dp"
android:layout_height="wrap_content"
android:inputType="textPostalAddress"
android:ems="10"
android:id="#+id/address2Text"
android:layout_marginLeft="50dp"
android:textColor="#ff000000"
android:layout_weight="1.04" /> />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1"
android:layout_weight="0.06">
<TextView
android:layout_width="48dp"
android:layout_height="wrap_content"
android:text="City"
android:id="#+id/city"
android:textColor="#ff000000"
android:layout_marginLeft="5dp"
android:gravity="center"
android:layout_gravity="center" />
<AutoCompleteTextView
android:layout_width="112dp"
android:layout_height="wrap_content"
android:id="#+id/city_autoCompleteTextView"
android:ems="10"
android:layout_gravity="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="33dp"
android:text="Zipcode"
android:id="#+id/zipcode"
android:textColor="#ff000000"
android:layout_marginLeft="10dp"
android:layout_gravity="center"
android:gravity="center" />
<EditText
android:layout_width="291dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/zipcodeText"
android:layout_marginLeft="10dp"
android:textColor="#ff000000"
android:layout_weight="1.04" /> />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="50dp"
android:weightSum="1"
android:layout_weight="0.09">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Country"
android:id="#+id/country"
android:textColor="#ff000000"
android:layout_marginLeft="10dp"
android:layout_gravity="center" />
<Spinner
android:layout_width="75dp"
android:layout_height="31dp"
android:id="#+id/countrySpinner"
android:entries="#array/country_list"
android:layout_marginLeft="40dp"
android:spinnerMode="dropdown"
android:outlineProvider="bounds"
android:layout_gravity="center" />
<TextView
android:layout_width="51dp"
android:layout_height="match_parent"
android:text="State"
android:id="#+id/state"
android:textColor="#ff000000"
android:layout_marginLeft="10dp"
android:layout_gravity="center"
android:gravity="center" />
<Spinner
android:layout_width="75dp"
android:layout_height="31dp"
android:id="#+id/stateSpinner"
android:entries="#array/state_list"
android:spinnerMode="dropdown"
android:outlineProvider="bounds"
android:layout_weight="0.10"
android:layout_gravity="center"
android:layout_marginLeft="10dp" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1"
android:layout_weight="0.06">
<TextView
android:layout_width="wrap_content"
android:layout_height="33dp"
android:text="Landmark"
android:id="#+id/landmark"
android:textColor="#ff000000"
android:layout_marginLeft="10dp"
android:layout_gravity="center"
android:gravity="center" />
<EditText
android:layout_width="291dp"
android:layout_height="wrap_content"
android:inputType="textPostalAddress"
android:ems="10"
android:id="#+id/landmarkText"
android:layout_marginLeft="40dp"
android:textColor="#ff000000"
android:layout_weight="1.04" /> />
</LinearLayout>
</LinearLayout>
Thanks for advance!!
Once check ID for below line in layout activity_main file
autoTextView = (AutoCompleteTextView) findViewById(R.id.city_autoCompleteTextView);
Here autoTextView is giving null.
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();
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'm trying to make a Drawer Menu but i'm having NullPointer, but i think everything is corect.
I'll post all my code here:
package wagner.com.meuartesanato.home;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import wagner.com.meuartesanato.R;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showHome(null);
TextView textMenu = (TextView) findViewById(R.id.text_menu);
TextView textHome = (TextView) findViewById(R.id.text_home);
TextView textSimulation = (TextView) findViewById(R.id.text_simulation);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
loadDrawer();
}
public void showMenu(View v){
//drawer.openDrawer(GravityCompat.END);
}
public void showHome(View v){
//loadFragment(Home1Fragment.class);
}
public void showSimulation(View v){
Toast.makeText(this,"Mostrar simulação",Toast.LENGTH_SHORT).show();
}
private void loadDrawer(){
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View view = navigationView.getHeaderView(0);
Button about = (Button)view.findViewById(R.id.button_about);
Button howToUse = (Button)view.findViewById(R.id.button_how_to_use);
Button addAccount = (Button)view.findViewById(R.id.button_add_account);
Button changeRegister = (Button)view.findViewById(R.id.button_change_register);
Button changePassword = (Button)view.findViewById(R.id.button_change_password);
Button help = (Button)view.findViewById(R.id.button_help);
Button exit = (Button)view.findViewById(R.id.button_exit);
about.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Mostra tela sobre o app
//loadFragment(SobreFragment.class);
drawer.closeDrawer(GravityCompat.END);
}
});
howToUse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"Mostrar como usar",Toast.LENGTH_SHORT).show();
drawer.closeDrawer(GravityCompat.END);
}
});
addAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"Mostrar algo",Toast.LENGTH_SHORT).show();
drawer.closeDrawer(GravityCompat.END);
}
});
changeRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"Alterar cadastro",Toast.LENGTH_SHORT).show();
drawer.closeDrawer(GravityCompat.END);
}
});
changePassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"Alterar cadastro",Toast.LENGTH_SHORT).show();
drawer.closeDrawer(GravityCompat.END);
}
});
help.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"Help",Toast.LENGTH_SHORT).show();
drawer.closeDrawer(GravityCompat.END);
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//fecha a activity, voltando pra tela de login
finish();
}
});
}
private void loadFragment(Class fragmentClass){
try {
Fragment fragment = (Fragment) fragmentClass.newInstance();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment_holder, fragment).commit();
}catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
drawer.closeDrawer(GravityCompat.END);
return false;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
drawer.openDrawer(GravityCompat.END);
}
}
}
And my xml files:
activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="end"
app:headerLayout="#layout/nav_header_main"
android:fitsSystemWindows="true"
android:background="#color/colorWhite"/>
</android.support.v4.widget.DrawerLayout>
activity_main.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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="10dp"
android:background="#drawable/degrade"
tools:context="wagner.com.meuartesanato.home.MainActivity">
<LinearLayout
android:baselineAligned="false"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/top_bar">
<LinearLayout
android:onClick="showMenu"
android:layout_width="0dp"
android:layout_weight="3"
android:gravity="center_horizontal"
android:orientation="vertical"
android:layout_gravity="center_vertical"
android:layout_height="wrap_content">
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#mipmap/menu"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text_menu"
android:layout_marginTop="5dp"
android:textSize="12sp"
android:textColor="#FFF"
android:text="Menu"/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:onClick="showHome"
android:gravity="center_horizontal"
android:orientation="vertical"
android:layout_gravity="center_vertical">
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#mipmap/home"/>
<TextView
android:id="#+id/text_home"
android:layout_marginTop="5dp"
android:textSize="12sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:text="Home"
/>
</LinearLayout>
<LinearLayout
android:onClick="showSimulation"
android:layout_width="0dp"
android:layout_weight="3"
android:gravity="center_horizontal"
android:orientation="vertical"
android:layout_gravity="center_vertical"
android:layout_height="wrap_content">
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#mipmap/simulacao"
/>
<TextView
android:id="#+id/text_simulation"
android:layout_marginTop="5dp"
android:layout_width="wrap_content"
android:textSize="12sp"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:text="Simulação"
/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_below="#id/top_bar">
<View
android:layout_width="match_parent"
android:layout_height="10dp"
android:background="#drawable/shadow"/>
<FrameLayout
android:id="#+id/fragment_holder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFF"
android:layout_marginBottom="#dimen/activity_vertical_margin">
</FrameLayout>
</LinearLayout>
</RelativeLayout>
nav_header_main.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:orientation="vertical"
android:background="#FFF"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/drawer_avatar"
android:layout_marginTop="20dp"
android:layout_width="115dp"
android:layout_height="115dp" />
<TextView
android:id="#+id/full_name"
android:layout_width="180dp"
android:gravity="center"
android:textColor="#color/colorDarkGray"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_marginBottom="20dp"
android:layout_marginTop="10dp"
/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorLightGray"
android:text="Sobre o App"
android:id="#+id/button_about"
android:textColor="#color/colorPurple"
android:textSize="#dimen/normal_text"
android:textAllCaps="false"
/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorWhite"
android:text="Como usar o App"
android:id="#+id/button_how_to_use"
android:textColor="#color/colorPurple"
android:textSize="#dimen/normal_text"
android:textAllCaps="false"
/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorLightGray"
android:text="Adicionar Conta Bancaria?"
android:id="#+id/button_add_account"
android:textColor="#color/colorPurple"
android:textSize="#dimen/normal_text"
android:textAllCaps="false"
/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorWhite"
android:text="Alterar Cadastro?"
android:id="#+id/button_change_register"
android:textColor="#color/colorPurple"
android:textSize="#dimen/normal_text"
android:textAllCaps="false"
/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorLightGray"
android:text="Alterar Senha?"
android:id="#+id/button_change_password"
android:textColor="#color/colorPurple"
android:textSize="#dimen/normal_text"
android:textAllCaps="false"
/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorWhite"
android:text="Ajuda"
android:id="#+id/button_help"
android:textColor="#color/colorPurple"
android:textSize="#dimen/normal_text"
android:textAllCaps="false"
/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorLightGray"
android:text="Sair"
android:id="#+id/button_exit"
android:textColor="#color/colorPurple"
android:textSize="#dimen/normal_text"
android:textAllCaps="false"
/>
<TextView
android:layout_marginTop="50dp"
android:layout_marginBottom="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Copyright"
android:textColor="#color/colorGray"
/>
</LinearLayout>
The error log is:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: wagner.com.meuartesanato, PID: 9112
java.lang.RuntimeException: Unable to start activity ComponentInfo{wagner.com.meuartesanato/wagner.com.meuartesanato.home.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.design.widget.NavigationView.setNavigationItemSelectedListener(android.support.design.widget.NavigationView$OnNavigationItemSelectedListener)'
on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.design.widget.NavigationView.setNavigationItemSelectedListener(android.support.design.widget.NavigationView$OnNavigationItemSelectedListener)'
on a null object reference
at wagner.com.meuartesanato.home.MainActivity.loadDrawer(MainActivity.java:59)
at wagner.com.meuartesanato.home.MainActivity.onCreate(MainActivity.java:41)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I really don't know why i'm getting null pointer exception.
Thanks, for the answers!
The stack trace clearly says what is missing. You could have actually found out the programming error by carefully reviewing your code. Anyways modify the following line in your onCreate method. You were inflating the wrong layout
What it is now - setContentView(R.layout.activity_main);
What you should change it to - setContentView(R.layout.activity_home);
Can not create objects think that an error is contained in Tab1.java
In Tab1 contains the timer. Accordingly, I sent you to see "layout".
Tab.java
package com.android.example;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Tab1 extends Fragment {
private TextView tvDay, tvHour, tvMinute, tvSecond, tvEvent;
private LinearLayout linearLayout1, linearLayout2;
private Handler handler;
private Runnable runnable;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_1, container, false);
initUI();
countDownStart();
return v;
}
#SuppressLint("SimpleDateFormat")
private void initUI() {
linearLayout1 = (LinearLayout) getView().findViewById(R.id.ll1);
linearLayout2 = (LinearLayout) getView().findViewById(R.id.ll2);
tvDay = (TextView) getView().findViewById(R.id.txtTimerDay);
tvHour = (TextView) getView().findViewById(R.id.txtTimerHour);
tvMinute = (TextView) getView().findViewById(R.id.txtTimerMinute);
tvSecond = (TextView) getView().findViewById(R.id.txtTimerSecond);
tvEvent = (TextView) getView().findViewById(R.id.tvevent);
}
// //////////////COUNT DOWN START/////////////////////////
public void countDownStart() {
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
handler.postDelayed(this, 1000);
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd");
// Here Set your Event Date
Date futureDate = dateFormat.parse("2016-12-30");
Date currentDate = new Date();
if (!currentDate.after(futureDate)) {
long diff = futureDate.getTime()
- currentDate.getTime();
long days = diff / (24 * 60 * 60 * 1000);
diff -= days * (24 * 60 * 60 * 1000);
long hours = diff / (60 * 60 * 1000);
diff -= hours * (60 * 60 * 1000);
long minutes = diff / (60 * 1000);
diff -= minutes * (60 * 1000);
long seconds = diff / 1000;
tvDay.setText("" + String.format("%02d", days));
tvHour.setText("" + String.format("%02d", hours));
tvMinute.setText("" + String.format("%02d", minutes));
tvSecond.setText("" + String.format("%02d", seconds));
} else {
linearLayout1.setVisibility(View.VISIBLE);
linearLayout2.setVisibility(View.GONE);
tvEvent.setText("Android Event Start");
handler.removeCallbacks(runnable);
// handler.removeMessages(0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
handler.postDelayed(runnable, 0);
}
// //////////////COUNT DOWN END/////////////////////////
}
MainActivity.java
Then connect the fragments
package com.android.example;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
// Declaring Your View and Variables
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
int Numboftabs =3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CharSequence Titles[]= {getResources().getString(R.string.titles), getResources().getString(R.string.result), getResources().getString(R.string.contacts)};
// Creating The Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
tab_1.xml
it is layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/ll1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:background="#drawable/counter_back"
android:gravity="center"
android:orientation="horizontal"
android:visibility="gone" >
<TextView
android:id="#+id/tvevent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal|center_vertical"
android:singleLine="true"
android:text="Android Event Start"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:id="#+id/ll2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="10dp"
android:background="#drawable/counter_back"
android:gravity="center"
android:orientation="horizontal"
android:visibility="visible" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#drawable/counter_back"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/txtTimerDay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="3"
android:gravity="center"
android:text="00"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#fff" />
<TextView
android:id="#+id/txt_TimerDay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="Days"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#fff" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#drawable/counter_back"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/txtTimerHour"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="3"
android:gravity="center"
android:text="00"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#fff" />
<TextView
android:id="#+id/txt_TimerHour"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="Hour"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#fff" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#drawable/counter_back"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/txtTimerMinute"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="3"
android:gravity="center"
android:text="00"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#fff" />
<TextView
android:id="#+id/txt_TimerMinute"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="Minute"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#fff" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#drawable/counter_back"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/txtTimerSecond"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="3"
android:gravity="center"
android:text="00"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#fff" />
<TextView
android:id="#+id/txt_TimerSecond"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="Second"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#fff" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
Gradle error:
I can not figure out the error. Please do not "write" because I am a beginner programmer :)
03-19 18:00:55.154 28193-28193/? E/Zygote: v2
03-19 18:00:55.154 28193-28193/? I/libpersona: KNOX_SDCARD checking this for 10140
03-19 18:00:55.154 28193-28193/? I/libpersona: KNOX_SDCARD not a persona
03-19 18:00:55.154 28193-28193/? I/SELinux: Function: selinux_compare_spd_ram , priority [2] , priority version is VE=SEPF_SM-A300F_5.0.2-1_0026
03-19 18:00:55.154 28193-28193/? E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
03-19 18:00:55.154 28193-28193/? I/art: Late-enabling -Xcheck:jni
03-19 18:00:55.174 28193-28193/? D/TimaKeyStoreProvider: in addTimaSignatureService
03-19 18:00:55.184 28193-28193/? D/TimaKeyStoreProvider: Cannot add TimaSignature Service, License check Failed
03-19 18:00:55.184 28193-28193/? D/ActivityThread: Added TimaKesytore provider
03-19 18:00:55.374 28193-28193/com.android.example D/DisplayManager: DisplayManager()
03-19 18:00:55.714 28193-28240/com.android.example D/OpenGLRenderer: Render dirty regions requested: true
03-19 18:00:55.784 28193-28193/com.android.example W/FragmentManager: moveToState: Fragment state for Tab2{3edefe8b #0 id=0x7f0c0052} not updated inline; expected state 3 found 2
03-19 18:00:55.834 28193-28193/com.android.example D/AndroidRuntime: Shutting down VM
03-19 18:00:55.844 28193-28193/com.android.example E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.example, PID: 28193
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.android.example.Tab1.initUI(Tab1.java:36)
at com.android.example.Tab1.onCreateView(Tab1.java:28)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:164)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1545)
at android.view.View.measure(View.java:17826)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5653)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
at android.view.View.measure(View.java:17826)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5653)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:17826)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5653)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
at android.view.View.measure(View.java:17826)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5653)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at android.view.View.measure(View.java:17826)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5653)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
at android.view.View.measure(View.java:17826)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5653)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2748)
at android.view.View.measure(View.java:17826)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2030)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1174)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1395)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1062)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5873)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5536)
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:1397)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.j
03-19 18:00:57.404 28193-28193/com.android.example I/Process: Sending signal. PID: 28193 SIG: 9
I think you should pass the result of inflater.inflate() to initUI(). Not sure, but I think getView() returns null because the system have not received your newly created view yet (you just created it, but it will be bound to the fragment only after return from onCreateView).
getView() returns the view which was returned by OnCreateView();
It will be null till onCreateView() returns.
You need to make sure you call getView() only after onCreateView() returns. To do this, you can move initUi() and countdownStart() inside onViewCreated(), which is called after onCreateView() returns.
http://developer.android.com/reference/android/app/Fragment.html#onViewCreated(android.view.View, android.os.Bundle)
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_1, container, false);
return v;
}
public void onViewCreated(View container, #Nullable Bundle savedInstanceState)
{
initUI();
countDownStart();
}
Alternatively, you can pass the layout inflated to the function initUI(), as others have mentioned
Can you see if there is anything wrong with my code?
I tried to create dialog box when the button is pressed.
I don't see something wrong here, But the logcat shows java.lang.NullPointerException in this line "agree.setOnClickListener(new OnClickListener() {"
package com.sociyo;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //Lock Orientation
requestWindowFeature(Window.FEATURE_NO_TITLE); //Hide Action menu
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //Load main activity
//viewPager default page
ViewPagerAdapter adapter = new ViewPagerAdapter();
ViewPager myPager = (ViewPager) findViewById(R.id.pager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
//textView clickable
Button agree = (Button)findViewById(R.id.btnTerms);
agree.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder tpDialog = new AlertDialog.Builder(null);
tpDialog.setTitle("Terms and Policy");
tpDialog.setMessage(R.string.action_settings)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
MainActivity.this.finish();
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
And this is the complete log cat :
E/AndroidRuntime(13076): FATAL EXCEPTION: main
E/AndroidRuntime(13076): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sociyo/com.sociyo.MainActivity}: java.lang.NullPointerException
E/AndroidRuntime(13076): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2070)
E/AndroidRuntime(13076): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2095)
E/AndroidRuntime(13076): at android.app.ActivityThread.access$600(ActivityThread.java:137)
E/AndroidRuntime(13076): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
E/AndroidRuntime(13076): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(13076): at android.os.Looper.loop(Looper.java:213)
E/AndroidRuntime(13076): at android.app.ActivityThread.main(ActivityThread.java:4793)
E/AndroidRuntime(13076): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(13076): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(13076): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
E/AndroidRuntime(13076): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
E/AndroidRuntime(13076): at dalvik.system.NativeStart.main(Native Method)
**E/AndroidRuntime(13076): Caused by: java.lang.NullPointerException**
E/AndroidRuntime(13076): at com.sociyo.MainActivity.onCreate(MainActivity.java:34)
E/AndroidRuntime(13076): at android.app.Activity.performCreate(Activity.java:5008)
E/AndroidRuntime(13076): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
E/AndroidRuntime(13076): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2034)
E/AndroidRuntime(13076): ... 11 more
My activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:background="#drawable/background"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
</android.support.v4.view.ViewPager>
</RelativeLayout>
And my activity_register.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#android:color/transparent"
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"
android:orientation="vertical" >
<TextView
android:id="#+id/tvRegisterTitle"
style="#style/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/register_text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/etNameReg"
style="#style/textfield"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/spMlmList"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:ems="10"
android:hint="#string/name_hint"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/etEmailReg"
style="#style/textfield"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/etNameReg"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:ems="10"
android:hint="#string/email_hint"
android:inputType="textEmailAddress" />
<EditText
android:id="#+id/etPasswordReg"
style="#style/textfield"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/etEmailReg"
android:layout_below="#+id/etEmailReg"
android:layout_centerVertical="true"
android:layout_marginTop="15dp"
android:ems="10"
android:hint="#string/password_hint"
android:inputType="textPassword" />
<Spinner
android:id="#+id/spMlmList"
style="#style/textfield"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tvRegisterTitle"
android:layout_below="#+id/tvRegisterTitle"
android:layout_marginTop="15dp"
android:entries="#array/mlm_list" />
<Button
android:id="#+id/btnRegister"
style="#style/buttonBlue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/etPasswordReg"
android:layout_below="#+id/chkAgree"
android:layout_marginTop="15dp"
android:text="#string/register_text" />
<CheckBox
android:id="#+id/chkAgree"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/etPasswordReg"
android:text="#string/agree_text"
android:layout_marginTop="15dp"
style="#style/checkbox"/>
<Button
android:id="#+id/btnTerms"
android:background="#android:color/transparent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/chkAgree"
android:layout_alignBottom="#+id/chkAgree"
android:layout_toRightOf="#+id/tvRegisterTitle"
android:layout_marginLeft="10dp"
android:text="#string/terms_policy"
style="#style/smallLink"/>
</RelativeLayout>
Yes the button doesnt exist at that point.
Your R.id.btnTermsR.id.btnTerms is defined in activity_register.xml, but that layout is never inflated. or not accessible at that point :)
Its the button that has the Problem, not the OnClickListener. A nullpointer within the Listener would appear the moment you click the button, not while attaching it.
// Before Replace
AlertDialog.Builder tpDialog = new AlertDialog.Builder(null);
// After Replace
AlertDialog.Builder tpDialog = new AlertDialog.Builder(MainActivity.this);
AlertDialog.Builder tpDialog = new AlertDialog.Builder(null);
change this line too
AlertDialog.Builder tpDialog = new AlertDialog.Builder(MainActivity.this);