Button click causing null pointer - java

Every time I click on the button, the app crashes. I have trouble finding the bug, but I'm sure it has to do something with either the onClickListener, or the onClick function.
Note: I'm using Parse API for some back end stuff. But I highly doubt it has anything to do with any of the Parse stuff.
Here's what my code looks like:
public class SignUpActivity extends Activity {
protected EditText mUserName;
protected EditText mPassword;
protected EditText mEmail;
protected Button mSignUpButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_sign_up);
mUserName = (EditText) findViewById(R.id.usernameField);
mPassword = (EditText) findViewById(R.id.passwordField);
mEmail = (EditText) findViewById(R.id.emailField);
mSignUpButton = (Button) findViewById(R.id.signupButton);
mSignUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = mUserName.getText().toString();
String password = mPassword.getText().toString();
String email = mEmail.getText().toString();
username = username.trim();
password = password.trim();
email = email.trim();
if(username.isEmpty() || password.isEmpty() || email.isEmpty()){
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
builder.setMessage(R.string.signup_error_message)
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else{
setProgressBarIndeterminateVisibility(true);
ParseUser newUser = new ParseUser();
newUser.setUsername(username);
newUser.setPassword(password);
newUser.setEmail(email);
newUser.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
setProgressBarIndeterminateVisibility(false);
if(e == null){
// success
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.sign_up, menu);
return true;
}
}
Here's my Log Cat:
04-14 14:19:05.881: E/AndroidRuntime(1156): FATAL EXCEPTION: main 04-14 14:19:05.881:
E/AndroidRuntime(1156): Process: com.ebad.ribbit, PID: 1156 04-14 14:19:05.881:
E/AndroidRuntime(1156): java.lang.NullPointerException 04-14 14:19:05.881:
E/AndroidRuntime(1156): at com.ebad.ribbit.SignUpActivity$1.onClick(SignUpActivity.java:40) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at android.view.View.performClick(View.java:4438) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at android.view.View$PerformClick.run(View.java:18422) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at android.os.Handler.handleCallback(Handler.java:733) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at android.os.Handler.dispatchMessage(Handler.java:95) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at android.os.Looper.loop(Looper.java:136) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at android.app.ActivityThread.main(ActivityThread.java:5017) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at java.lang.reflect.Method.invokeNative(Native Method) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at java.lang.reflect.Method.invoke(Method.java:515) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at dalvik.system.NativeStart.main(Native Method)
EDIT:
As requested, here is line 40:
String username = mUserName.getText().toString();
EDIT 2:
Here is the log cat after adding Log.i(TAG, mUserName == null ? "mUserName is null" : mUserName.getText() == null ? "mUserName.getText() is null" : "nothing is null"); :
04-14 15:21:47.955: E/AndroidRuntime(1318): FATAL EXCEPTION: main
04-14 15:21:47.955: E/AndroidRuntime(1318): Process: com.ebad.ribbit, PID: 1318
04-14 15:21:47.955: E/AndroidRuntime(1318): java.lang.NullPointerException
04-14 15:21:47.955: E/AndroidRuntime(1318): at com.ebad.ribbit.SignUpActivity$1.onClick(SignUpActivity.java:43)
04-14 15:21:47.955: E/AndroidRuntime(1318): at android.view.View.performClick(View.java:4438)
04-14 15:21:47.955: E/AndroidRuntime(1318): at android.view.View$PerformClick.run(View.java:18422)
04-14 15:21:47.955: E/AndroidRuntime(1318): at android.os.Handler.handleCallback(Handler.java:733)
04-14 15:21:47.955: E/AndroidRuntime(1318): at android.os.Handler.dispatchMessage(Handler.java:95)
04-14 15:21:47.955: E/AndroidRuntime(1318): at android.os.Looper.loop(Looper.java:136)
04-14 15:21:47.955: E/AndroidRuntime(1318): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-14 15:21:47.955: E/AndroidRuntime(1318): at java.lang.reflect.Method.invokeNative(Native Method)
04-14 15:21:47.955: E/AndroidRuntime(1318): at java.lang.reflect.Method.invoke(Method.java:515)
04-14 15:21:47.955: E/AndroidRuntime(1318): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-14 15:21:47.955: E/AndroidRuntime(1318): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-14 15:21:47.955: E/AndroidRuntime(1318): at dalvik.system.NativeStart.main(Native Method)
EDIT 3:
Upon Request, here is my activity_sign_up.xml:
<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=".SignUpActivity" >
<EditText
android:id="#+id/userNameField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:hint="#string/username_hint"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/passwordField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/userNameField"
android:ems="10"
android:hint="#string/password_hint"
android:inputType="textPassword" />
<EditText
android:id="#+id/emailField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/passwordField"
android:ems="10"
android:hint="#string/email_hint"
android:inputType="textEmailAddress" />
<Button
android:id="#+id/signupButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/emailField"
android:layout_below="#+id/emailField"
android:layout_marginTop="50dp"
android:text="#string/sign_up_button_label" />
</RelativeLayout>

Do this please:
#Override
public void onClick(View v) {
if(mUserName != null && mPassword != null && mEmail != null && mUserName.getText() != null && mPassword.getText() != null && mEmail.getText() != null)
{
Your original code here.
}
}
Update:
Typo
mUserName = (EditText) findViewById(R.id.usernameField); should be userNameField?
<EditText android:id="#+id/userNameField" ...

If mUsername is null, calling getText() on it will cause a NullPointerException. You should check that it's not null before doing this. Try changing to the following:
if(mUserName == null || mPassword == null || mEmail == null){
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
builder.setMessage(R.string.signup_error_message)
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
String username = mUserName.getText().toString();
String password = mPassword.getText().toString();
String email = mEmail.getText().toString();
username = username.trim();
password = password.trim();
email = email.trim();

Try
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
https://developer.android.com/guide/topics/ui/dialogs.html
Also make sure that SignUpActivity is declared in the app manifest. I guess make sure that all activities are set up in the manifest.
EDIT 1
If line 40 is the issue, then
mUserName is null
or
mUserName.getText() is null. So create a couple checks before hand and also add some debug logs to just verify that they are not null.
Make sure that R.layout.activity_sign_up has usernameField as an id. Also make sure in any other app/res/layout folders (ie layout-v14), that all R.layout.activity_sign_up has the edittext as well.

If this errors occurred in your line 40, that means your are getting null from your EditText.
Try it in every place you are getting a string. At least it will save you from getting null pointer exception from EditText.
String username = String.valueOf(mUserName.getText());
String password = String.valueOf(mPassword.getText());
String email = String.valueOf(mEmail.getText());

Related

NullPointerException on TextView using setText()

I'm rather new to android programming, and am running into my old friend the NullPointerException...
I've been on it for quite a while now, but can't figure out what is wrong.
basicly gives me a NullPointerException when I try to call any .setText() methods, maybe someone sees what I'm doing wrong here...(though i tried to follow examples as close as possible)
public class lessonView extends Activity {
TextView adressOfLecture;
TextView lecturer;
TextView lesson;
Lecture lecture;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lesson_view);
Bundle data = getIntent().getExtras();
lecture = (Lecture) data.getParcelable("student");
adressOfLecture = (TextView)findViewById(R.id.lectureViewAdressLabel);
lecturer = (TextView)findViewById(R.id.lectureViewLecturerLabel);
lesson = (TextView)findViewById(R.id.lectureViewTitle);
updateLabels();
}
#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_lesson_view, 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);
}
private void updateLabels(){
adressOfLecture.setText(lecture.getRoom());
lecturer.setText(lecture.getTutor());
lesson.setText(lecture.getName());
}
}
also, here's my xml file:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.coronarip7.app.stupla.lessonView">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="(ort)"
android:id="#+id/lectureViewAdressLabel"
android:layout_centerVertical="true"
android:layout_toStartOf="#+id/lectureViewTitle"
android:layout_marginRight="86dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dozent"
android:id="#+id/lectureViewLecturerLabel"
android:layout_toEndOf="#+id/lectureViewTitle"
android:layout_alignTop="#+id/lectureViewAdressLabel"
android:layout_alignParentEnd="true"
android:layout_marginRight="27dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lectureViewTitle"
android:gravity="center_horizontal"
android:text="test"
android:textSize="40dp"
android:textStyle="bold"
android:padding="10dp"
android:layout_row="0"
android:layout_column="0"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
and the logcat I'm getting:
04-25 01:23:51.058 12236-12236/com.coronarip7.app.stupla E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.coronarip7.app.stupla, PID: 12236
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.coronarip7.app.stupla/com.coronarip7.app.stupla.lessonView}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
at android.app.ActivityThread.access$800(ActivityThread.java:145)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5081)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.coronarip7.app.stupla.lessonView.updateLabels(lessonView.java:59)
at com.coronarip7.app.stupla.lessonView.onCreate(lessonView.java:31)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
            at android.app.ActivityThread.access$800(ActivityThread.java:145)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5081)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
            at dalvik.system.NativeStart.main(Native Method)
seriously, I am out of ideas on how to fix it...
First check if you properly put the extra in the intent. Then I would use the following test in your onCreate method:
Intent intent = getIntent();
if (intent.hasExtra("student")){
lecture = (Lecture) intent.getParcelableExtra("student");
}
Then test if lecture is null like Rami wrote earlier.
Ok guys, thanks for the suggestions, but I'll go the global route. I'll create a static version of my array (from which i wanted to pass an object via the Intent), and just pass an int[] array with the coordiantes and call it in the new view.
But thanks for the quick answers anyways!
(I'm new to stackoverflow, is there a way to mark a question as "solved", or "not-needed-to-be-solved-anymore"?)
Do not use static objects in your code like arrays, objects, they have globally available, you should create intent and add your data into your intent like and call your activity
Intent intent = new Intent ();
intent.putExtra ("student",value);
start activity with intent
And in your
lessonViewActivity check for intent like
Intent intent = getIntent();
if (intent.hasExtra("student")){
lecture = (Lecture) intent.getParcelableExtra("student");
if (lecture !=null){
updateLabels ();
}
}

Android NumberPicker NullPointer why?

i am try to implement a numberPicker to select minute values.
But i am getting a NullPointer Exception at this line:
minutePicker = (NumberPicker) findViewById(R.id.minuten_picker);
Following Code:
public class MainActivity extends Activity {
NumberPicker minutePicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Auswahl Minuten zum starten / Stoppen aller
minutePicker = new NumberPicker(MainActivity.this);
minutePicker = (NumberPicker) findViewById(R.id.minuten_picker);
minutePicker.setMaxValue(30);
minutePicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
abschaltzeit = minutePicker.getValue();
}
});
minutePicker.setValue(0);
minutePicker.setWrapSelectorWheel(false);
}
}
XML:
<NumberPicker
android:id="#+id/minuten_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_row="6"
android:layout_column="0"
android:paddingLeft="20dp" />
Log:
09-25 11:00:09.749 10687-10687/de.carsten.awesome.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.carsten.awesome.app, PID: 10687
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.carsten.awesome.app/de.carsten.awesome.app.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at de.carsten.awesome.app.MainActivity.onCreate(MainActivity.java:83)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
minutePicker = new NumberPicker(MainActivity.this);
minutePicker = (NumberPicker) findViewById(R.id.minuten_picker);
You're creating a NumberPicker programmatically and then overwriting the reference with whatever findViewById() returns. It returns null if your activity_main layout does not contain a minuten_picker.
Choose only the other: either create it prorgrammatically or find it from a view hierarchy you inflated.
If you choose the programmatic way new NumberPicker(), remember to add it to some layout in your activity view hierarchy, e.g. with setContentView()
If you choose the inflation way, make sure you have the view in your XML layout file.
I'm guessing the NPE you're seeing is actually on the following line where you're trying to invoke a method on the minutePicker and it's null.
I apologize.
I moved the Code from the MainActivity in the creating Fragment and it works with rootView.findView.
Sorry but i am new with the Fragement Konzept.
Thanks a lot for your help !

Null pointer exception - loading a new activity from fragment

I ran into a null pointer exception when trying to load a new activity from a fragment - it essentially tells me an unexpected error has occurred. Below is the log cat message:
08-21 11:57:14.801: E/AndroidRuntime(1245): FATAL EXCEPTION: main
08-21 11:57:14.801: E/AndroidRuntime(1245): Process: com.dooba.beta, PID: 1245
08-21 11:57:14.801: E/AndroidRuntime(1245): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dooba.beta/com.dooba.beta.matchOptionActivity}: java.lang.NullPointerException
08-21 11:57:14.801: E/AndroidRuntime(1245): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
08-21 11:57:14.801: E/AndroidRuntime(1245): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
08-21 11:57:14.801: E/AndroidRuntime(1245): at android.app.ActivityThread.access$800(ActivityThread.java:135)
08-21 11:57:14.801: E/AndroidRuntime(1245): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
08-21 11:57:14.801: E/AndroidRuntime(1245): at android.os.Handler.dispatchMessage(Handler.java:102)
08-21 11:57:14.801: E/AndroidRuntime(1245): at android.os.Looper.loop(Looper.java:136)
08-21 11:57:14.801: E/AndroidRuntime(1245): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-21 11:57:14.801: E/AndroidRuntime(1245): at java.lang.reflect.Method.invokeNative(Native Method)
08-21 11:57:14.801: E/AndroidRuntime(1245): at java.lang.reflect.Method.invoke(Method.java:515)
08-21 11:57:14.801: E/AndroidRuntime(1245): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-21 11:57:14.801: E/AndroidRuntime(1245): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-21 11:57:14.801: E/AndroidRuntime(1245): at dalvik.system.NativeStart.main(Native Method)
08-21 11:57:14.801: E/AndroidRuntime(1245): Caused by: java.lang.NullPointerException
08-21 11:57:14.801: E/AndroidRuntime(1245): at com.dooba.beta.matchOptionActivity.onCreate(matchOptionActivity.java:29)
08-21 11:57:14.801: E/AndroidRuntime(1245): at android.app.Activity.performCreate(Activity.java:5231)
08-21 11:57:14.801: E/AndroidRuntime(1245): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-21 11:57:14.801: E/AndroidRuntime(1245): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
08-21 11:57:14.801: E/AndroidRuntime(1245): ... 11 more
Below is the fragment activity code (the place where the new intent activity is called)
public class Fragment1 extends Fragment {
private String currentUserId;
private ArrayAdapter<String> namesArrayAdapter;
private ArrayList<String> names;
private ListView usersListView;
private Button logoutButton;
String userGender = ParseUser.getCurrentUser().getString("Gender");
String activityName = ParseUser.getCurrentUser().getString("ActivityName");
Number maxDistance = ParseUser.getCurrentUser().getNumber("Maximum_Distance");
String userLookingGender = ParseUser.getCurrentUser().getString("Looking_Gender");
Number minimumAge = ParseUser.getCurrentUser().getNumber("Minimum_Age");
Number maximumAge = ParseUser.getCurrentUser().getNumber("Maximum_Age");
Number userage = ParseUser.getCurrentUser().getNumber("Age");
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setConversationsList();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1_layout, container, false);
Button newPage = (Button)view.findViewById(R.id.btnMatchConfirm);
newPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), matchOptionActivity.class);
startActivity(intent);
}
});
return view;
}
private void setConversationsList() {
currentUserId = ParseUser.getCurrentUser().getObjectId();
names = new ArrayList<String>();
// String userActivitySelectionName = null;
ParseQuery<ParseUser> query = ParseUser.getQuery();
// query.whereEqualTo("ActivityName",userActivitySelectionName);
query.whereNotEqualTo("objectId", ParseUser.getCurrentUser().getObjectId());
// users with Gender = currentUser.Looking_Gender
query.whereEqualTo("Gender", userLookingGender);
// users with Looking_Gender = currentUser.Gender
query.whereEqualTo("Looking_Gender", userGender);
query.setLimit(1);
query.whereEqualTo("ActivityName", activityName);
// query.whereGreaterThanOrEqualTo("Age", minimumAge);
// query.whereLessThanOrEqualTo("Age", maximumAge);
query.orderByDescending("Name");
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> userList, ParseException e) {
if (e == null) {
for (int i=0; i<userList.size(); i++) {
names.add(userList.get(i).get("Name").toString());
names.add(userList.get(i).get("Headline").toString());
names.add(userList.get(i).get("Age").toString());
names.add(userList.get(i).get("ActivityName").toString());
// names.add(userList.get(i).getParseObject("ProfilePicture").;
}
usersListView = (ListView)getActivity().findViewById(R.id.userlistview1);
namesArrayAdapter =
new ArrayAdapter<String>(getActivity().getApplicationContext(),
R.layout.user_list_item, names);
usersListView.setAdapter(namesArrayAdapter);
usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
openConversation(names, i);
}
});
} else {
Toast.makeText(getActivity().getApplicationContext(),
"Error loading user list",
Toast.LENGTH_LONG).show();
}
}
});
}
public void openConversation(ArrayList<String> names, int pos) {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("Name", names.get(pos));
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> user, ParseException e) {
if (e == null) {
Intent intent = new Intent(getActivity().getApplicationContext(), MessagingActivity.class);
intent.putExtra("RECIPIENT_ID", user.get(0).getObjectId());
startActivity(intent);
} else {
Toast.makeText(getActivity().getApplicationContext(),
"Error finding that user",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
Below is the code for the matchOption activity (the activity that is called upon button click)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.matchoption);
final ImageView idrinks = (ImageView) this.findViewById(R.id.icasual);
idrinks.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
matchOptionActivity.this.startActivity(new Intent(matchOptionActivity.this, MessagingActivity.class));
}
});
}
}
Furthermore, I am using Parse to populate my list of users, and I would like to know how I would be hide the confirm button in the event that the list is empty.
Thanks in advance.
Update
below is the fragment XML file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/blue_bac3"
android:orientation="vertical" >
<ListView
android:id="#+id/userlistview1"
android:layout_width="match_parent"
android:layout_height="400dp"
android:textColor="#ffffff"
android:divider="#null"
>
</ListView>
<Button
android:id="#+id/btnMatchConfirm"
android:layout_width="100dp"
android:layout_height="50dp"
android:background="#drawable/gray_bac"
android:layout_below="#+id/userlistview1"
android:layout_centerHorizontal="true"
android:layout_marginTop="13dp"
android:text="Confirm" />
</RelativeLayout>
I don't have reputation to add comment...Can you also provide the matchoption xml for further analysis or check the onClick() method. looks like some issue over there
Caused by: java.lang.NullPointerException
08-21 11:57:14.801: E/AndroidRuntime(1245): at com.dooba.beta.matchOptionActivity.onCreate(matchOptionActivity.java:29)
I guess you need to change the code
from this
idrinks.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
matchOptionActivity.this.startActivity(new Intent(matchOptionActivity.this, MessagingActivity.class));
}
});
to this
idrinks.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(this,MessagingActivity.class);
i.startActivity(new Intent(matchOptionActivity.this, MessagingActivity.class));
}
});

getting null pointer exception

I am getting a NullPointerException when I try to access text view which is defined in view class. I am accessing it from setting class. A small part of my code is:
view class
public class view1 extends menu {
public static TextView text1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
text1=(TextView)findViewById(R.id.textfile1);
text1.setText("product");
}
public void small(String mytext) { // this is my method which I want to access
text1.setText(mytext);
}
}
setting class
public class Setting extends Activity {
private Spinner spinner1;
private Button apply;
TextView small1;
private view1 view11;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setting);
//setContentView(R.layout.view);
addItemsOnSpinner1();
addListenerOnSpinnerItemSelection();
}
public void addItemsOnSpinner1() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
List<String> list = new ArrayList<String>();
list.add("Small");
list.add("Medium");
list.add("Large");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
apply = (Button) findViewById(R.id.apply);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
apply.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String mytext = "Something else";
view11.small(mytext);
}
Stack trace
01-17 00:11:02.064: E/AndroidRuntime(4191): FATAL EXCEPTION: main
01-17 00:11:02.064: E/AndroidRuntime(4191): java.lang.NullPointerException
01-17 00:11:02.064: E/AndroidRuntime(4191): at com.ramanrayat.notelet.Setting$1.onClick(Setting.java:106)
01-17 00:11:02.064: E/AndroidRuntime(4191): at android.view.View.performClick(View.java:4240)
01-17 00:11:02.064: E/AndroidRuntime(4191): at android.view.View$PerformClick.run(View.java:17721)
01-17 00:11:02.064: E/AndroidRuntime(4191): at android.os.Handler.handleCallback(Handler.java:730)
01-17 00:11:02.064: E/AndroidRuntime(4191): at android.os.Handler.dispatchMessage(Handler.java:92)
01-17 00:11:02.064: E/AndroidRuntime(4191): at android.os.Looper.loop(Looper.java:137)
01-17 00:11:02.064: E/AndroidRuntime(4191): at android.app.ActivityThread.main(ActivityThread.java:5103)
01-17 00:11:02.064: E/AndroidRuntime(4191): at java.lang.reflect.Method.invokeNative(Native Method)
01-17 00:11:02.064: E/AndroidRuntime(4191): at java.lang.reflect.Method.invoke(Method.java:525)
01-17 00:11:02.064: E/AndroidRuntime(4191): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-17 00:11:02.064: E/AndroidRuntime(4191): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-17 00:11:02.064: E/AndroidRuntime(4191): at dalvik.system.NativeStart.main(Native Method)
setting.xml code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="38dp"
android:text="Setting"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="40dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="57dp"
android:gravity="center"
android:text="Font Size"
android:textSize="30dp" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="30dp" />
<Button
android:id="#+id/apply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignRight="#+id/textView2"
android:layout_below="#+id/spinner1"
android:layout_marginTop="58dp"
android:text="Apply" />
</RelativeLayout>
Chnage
if(String.valueOf(spinner1.getSelectedItem())=="Small")
TO
if(String.valueOf(spinner1.getSelectedItem()).equals("Small"))
Use .equals or .equalsIgnoreCase to compare strings
Instead of making textview static you should use intents to pass values between activities.
Intent intent = new Intent(ActivityName.this,Settings.class);
intent.putExtra("key",text1.getText().toString());
startActivity(intent);
Then
String value = getIntent().getStringExtra("key");
Change
public static TextView text1;
to
public TextView text1;
Also follow java naming conventions
Replace
public static TextView text1;
with
TextView text1;
text1 can not be static.
Next time, please click on the file name in the error log and indicate which line number in your code listing is the line that the error actually points to.
Learn to start all your class names with capital letters (athough, this is not what's causing the problem). And while I'm at it, please stop using numbers in class names and in variables, especially the number 1, which can be ambiguously read as an "l" in some fonts.
Look for your LogCat, it will told you where is NPE.
The other question is : don't use equals to compare String instead of ==
== is compare two object's address and equals is compare their value.
if(String.valueOf(spinner1.getSelectedItem()).equals("Small")) {
String mytext = "Something else ";
view11.small(mytext); // view11 is clas view1 reference
}
else if(String.valueOf(spinner1.getSelectedItem()).equals("Medium")) {
finish();
}

Unable to getText from editText

public class screen2 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);
final Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//AInteger.parseInt(string)
System.out.println("1");
EditText et = (EditText)findViewById(R.id.editText1);
System.out.println("2");
int zipCode = Integer.parseInt(et.getText().toString());
System.out.println("3");
System.out.println(zipCode);
System.out.println("dude...5");
}
});
}
}
This code shows the errror in the logcat :
11-13 19:58:06.806: W/KeyCharacterMap(281): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
11-13 19:58:09.471: I/System.out(281): 1
11-13 19:58:09.471: I/System.out(281): 2
11-13 19:58:09.477: D/AndroidRuntime(281): Shutting down VM
11-13 19:58:09.477: W/dalvikvm(281): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
11-13 19:58:09.527: E/AndroidRuntime(281): FATAL EXCEPTION: main
11-13 19:58:09.527: E/AndroidRuntime(281): java.lang.NullPointerException
11-13 19:58:09.527: E/AndroidRuntime(281): at com.example.andtwi.screen2$1.onClick(screen2.java:23)
11-13 19:58:09.527: E/AndroidRuntime(281): at android.view.View.performClick(View.java:2408)
11-13 19:58:09.527: E/AndroidRuntime(281): at android.view.View$PerformClick.run(View.java:8816)
11-13 19:58:09.527: E/AndroidRuntime(281): at android.os.Handler.handleCallback(Handler.java:587)
11-13 19:58:09.527: E/AndroidRuntime(281): at android.os.Handler.dispatchMessage(Handler.java:92)
11-13 19:58:09.527: E/AndroidRuntime(281): at android.os.Looper.loop(Looper.java:123)
11-13 19:58:09.527: E/AndroidRuntime(281): at android.app.ActivityThread.main(ActivityThread.java:4627)
11-13 19:58:09.527: E/AndroidRuntime(281): at java.lang.reflect.Method.invokeNative(Native Method)
11-13 19:58:09.527: E/AndroidRuntime(281): at java.lang.reflect.Method.invoke(Method.java:521)
11-13 19:58:09.527: E/AndroidRuntime(281): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-13 19:58:09.527: E/AndroidRuntime(281): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-13 19:58:09.527: E/AndroidRuntime(281): at dalvik.system.NativeStart.main(Native Method)
Though it looks like an Null Pointer exception , i think i am doing it things exactly i found on forums. Here is code of my related xml file as well. Can anyone suggest where am i doing it wrong?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Zipcode" />
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:maxLength="5" >
<requestFocus />
</EditText>
<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get movies from Flixster" />
</LinearLayout>
The code breaks at this as well :
int zipCode = Integer.parseInt(et.getText().toString());
Try this:
Button button1 = (Button)findViewById(R.id.button1);
EditText et = (EditText)findViewById(R.id.editText1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("1");
System.out.println("2");
String zipCode = et.getText().toString();
System.out.println("3");
System.out.println(zipCode);
}
}
I think,you don't need to write String zipCode = (String)et.getText().toString(); there as it is already returns a String object.
And hope,you don't miss to include setContentView(R.layout.your_xml_file); before declaring a Button and EditText.
Edit 1:
You don't seem to get problem with
int zipCode=Integer.parseInt(et.getText().toString()); there.Try this with above code modification.
You might be getting null pointer exception because you are getting String s=et.getText().toString() as null.Please check it for null before casting it to int.
Button button1 = (Button)findViewById(R.id.button1);
EditText et = (EditText)findViewById(R.id.editText1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("1");
System.out.println("2");
String check = et.getText().toString();
int zipCode=0;
if(!check.equals(""))
zipCode=Integer.parseInt(check);
System.out.println("3");
System.out.println(zipCode);
}
}
Could you post your onCreate method, as well as line 23 on its own? The most likely problem is that you neglect to call setContentView and that is why findViewById returns null.

Categories