This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I have an issue I need help with. I am running into a NullPointerException no matter what I do with this app, and at this point it is seriously holding up this project. I have reviewed the logcat multiple times, made changes and re run the app and every time it turns out a nullpointerexception. For the life of me I can't seem to figure out what is causing it. Can someone point out where it is, and if possible, why it occurred since as far as I can tell I have everything assigned a value.
GameStart.java:
package com.saphiric.simproject;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by Saphiric on 11/12/14.
*/
public class GameStart extends Activity {
/**
* Necessary activity variables
*/
int clickCount = 0;
TextView storyText;
Button advanceGame;
DecisionFragment decisionFragment;
ControlsFragment controlsFragment;
public View.OnClickListener decisionTime = new View.OnClickListener(){
public void onClick(View v) {
clickCount = clickCount + 1; // Increments clickCount by 1 per click
// /**
// * Will handle checking how far into the story the player is
// * and update components as necessary.
// */
// switch (clickCount) {
// case 1:
// storyText.setText(R.string.story_opening_two);
// break;
//
// case 2:
// FragmentTransaction decisionTime = fragmentManager.beginTransaction();
// // Replace the fragment currently inside of the fragmentContainer
// decisionTime.replace(R.id.fragmentContainer, decisionFragment);
// decisionTime.commit();
// break;
//
// default:
// System.out.println("An error occurred");
// }
// System.out.println(clickCount);
}
};
/**
* Android activity methods
* #param savedInstanceState is the apps savedInstanceState
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_start);
// UI element handles
advanceGame = (Button) findViewById(R.id.advanceButton);
storyText = (TextView) findViewById(R.id.storyText);
decisionFragment = new DecisionFragment();
controlsFragment = new ControlsFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// UI will add the ControlsFragment in it's starting state for that activity.
fragmentTransaction.add(R.id.fragmentContainer, controlsFragment).commit();
// Sets the advanceButton to run decisionTime method
advanceGame.setOnClickListener(decisionTime);
}
}
LogCat:
12-07 13:16:10.142 19915-19915/com.saphiric.simproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.saphiric.simproject, PID: 19915
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.saphiric.simproject/com.saphiric.simproject.GameStart}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
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:1069)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.saphiric.simproject.GameStart.onCreate(GameStart.java:75)
at android.app.Activity.performCreate(Activity.java:5312)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2552)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
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:1069)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)
at dalvik.system.NativeStart.main(Native Method)
The null pointer happens at line 75 , i.e.
advanceGame.setOnClickListener(decisionTime);
Here, the only thing that can be null is advanceGame. This means that
advanceGame = (Button) findViewById(R.id.advanceButton);
is not able to find your button from your view. Check the id of the button if its exactly the same as you defined it in your android xml.
I believe that advanceGame is null.
You can't find button by findViewById(R.id.advanceButton);
NPE is at line 75
advanceGame.setOnClickListener(decisionTime);
it is clear from
at com.saphiric.simproject.GameStart.onCreate(GameStart.java:75)
Looks like at
advanceGame = (Button) findViewById(R.id.advanceButton);
view was not found. You can debug that or add check at 75
if(null != advanceGame) advanceGame = (Button) findViewById(R.id.advanceButton);
I think just check #+id of your activity_game_start.xml layout of advanceGame button
it might have different name
Related
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
What is false in my program that gives "App keeps stopping" while opening that activity?
(2 answers)
Closed 5 years ago.
//I'm new to programming and android studio
package com.example.calc;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import static com.example.calc.R.id.editText;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText editTexts = (EditText) findViewById(editText);
double a = 0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Buttons to take input and display
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
Button button3 = (Button) findViewById(R.id.button3);
Button button4 = (Button) findViewById(R.id.button4);
Button button5 = (Button) findViewById(R.id.button5);
Button button6 = (Button) findViewById(R.id.button6);
//using to make the buttons react
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);
button5.setOnClickListener(this);
button6.setOnClickListener(this);
}
#Override
public void onClick (View v){
double res; //Display and taking input from same textfield
if (TextUtils.isEmpty(editTexts.getText().toString())) {
return;
}
res = Double.parseDouble(editTexts.getText().toString());
switch (v.getId()) {
case R.id.button1:
a += res;
editTexts.setText(" ");
break;
case R.id.button2:
a -= res;
editTexts.setText(" ");
break;
case R.id.button3:
a *= res;
editTexts.setText(" ");
break;
case R.id.button4:
a /= res;
editTexts.setText(" ");
break;
case R.id.button5:
editTexts.setText((int) a);
break;
case R.id.button6:
a = 0.0;
editTexts.setText(" ");
break;
}
}
}
Unfortunately, App crashed.
Gradle is building but crashing as soon as opening.
How to resolve this error??
logCat:
06-24 22:36:42.926 4983-4983/? E/libprocessgroup: failed to make and chown
/acct/uid_10058: Read-only file system
06-24 22:36:42.926 4983-4983/? W/Zygote: createProcessGroup failed, kernel
missing CONFIG_CGROUP_CPUACCT?
06-24 22:36:42.930 4983-4983/? I/art: Not late-enabling -Xcheck:jni (already
on)
06-24 22:36:43.400 4983-4983/com.example.calc I/InstantRun: starting instant
run server: is main process
06-24 22:36:43.626 4983-4983/com.example.calc W/art: Verification of boolean
android.support.v7.app.AppCompatDelegateImplV9.initializePanelContent(android.support.v7.app.AppCompatDelegateImplV9$PanelFeatureState) took 139.729ms
06-24 22:36:43.741 4983-4983/com.example.calc W/art: Verification of
android.support.v7.view.ActionMode
android.support.v7.app.AppCompatDelegateImplV9.startSupportActionModeFromWindow(android.support.v7.view.ActionMode$Callback) took 109.701ms
06-24 22:36:43.743 4983-4983/com.example.calc D/AndroidRuntime: Shutting down VM
--------- beginning of crash
06-24 22:36:43.746 4983-4983/com.example.calc E/AndroidRuntime: FATAL
EXCEPTION: main
Process:
com.example.calc, PID: 4983
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.example.calc/com.example.calc.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.view.Window$Callback android.view.Window.getCallback()' on a null
object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at
android.app.ActivityThread.access$800(ActivityThread.java:151)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at
android.os.Handler.dispatchMessage(Handler.java:102)
at
android.os.Looper.loop(Looper.java:135)
at
android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.view.Window$Callback android.view.Window.getCallback()' on a null
object reference
at
android.support.v7.app.AppCompatDelegateImplBase.<init>
(AppCompatDelegateImplBase.java:118)
at
android.support.v7.app.AppCompatDelegateImplV9.<init>
(AppCompatDelegateImplV9.java:152)
at
android.support.v7.app.AppCompatDelegateImplV11.<init>
(AppCompatDelegateImplV11.java:29)
at
android.support.v7.app.AppCompatDelegateImplV14.<init>
(AppCompatDelegateImplV14.java:53)
at
android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:204)
at
android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:184)
at
android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:518
)
at
android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:189
)
at
com.example.calc.MainActivity.<init>(MainActivity.java:15)
at
java.lang.reflect.Constructor.newInstance(Native Method)
at
java.lang.Class.newInstance(Class.java:1606)
at
android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at
android.app.ActivityThread.access$800(ActivityThread.java:151)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at
android.os.Handler.dispatchMessage(Handler.java:102)
at
android.os.Looper.loop(Looper.java:135)
at
android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I am a complete beginner to android/Java development and I massively appreciate any pointers anyone is able to give me on the issue I'm having. Here is the MainActivity.java.
package com.example.harris.enterappman;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// 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);
}
EditText enterName;
TextView usersName;
String str = enterName.getText().toString();
public void getName(View view){
enterName = (EditText) findViewById(R.id.enterName);
usersName = (TextView) findViewById(R.id.helloNameView);
usersName.setText(str);
}
public void printUsersName(){
}
}
Everytime I try and run the program, it fails with the error:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.harris.enterappman/com.example.harris.enterappman.Main Activity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
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:5021)
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:827)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.harris.enterappman.MainActivity.<init>(MainActivity.java:48)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1064)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
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:5021)
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:827)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
at dalvik.system.NativeStart.main(Native Method)
From others posts online I have come to the conclusion that the problem is related to abstract methods? I was unable to work out how my code was wrong.
Cheers,
Harris
String str = enterName.getText().toString();
enterName is null at this point, as you are not setting it ever. You are welcome to declare String str; as a field, but you cannot initialize it until after you set a value on enterName.
You have code to initialize enterName in a somewhat strange getName() method, but you do not appear to be calling that ever.
you have not initialised entername properly
either use:
....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enterName = (EditText) findViewById(R.id.enterName);
usersName = (TextView) findViewById(R.id.helloNameView);
usersName.setText(str);
}
...
or use it like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getName();
}
public void getName(){
enterName = (EditText) findViewById(R.id.enterName);
usersName = (TextView) findViewById(R.id.helloNameView);
usersName.setText(str);
}
You call enterName.getText() when enterName is null, which leads to NullPointerException.
Few things I suggest:
If you want to own references to the layout components, call these in the onCreate method:
enterName = (EditText) findViewById(R.id.enterName);
usersName = (TextView) findViewById(R.id.helloNameView);
Don't call methods in the class itself (except some constructors), call them in a method (I refer to the str variable).
how possible you are setting your str using enterName, as enterName is not initialized and hence it is null causing Null pointer exception
you must have to initilize enterName before using it, as you are doing initialization in your getName() method, and then use it to get its text
your code must be like this and you have to call this method from onCreate()
public void getName(View view){
enterName = (EditText) findViewById(R.id.enterName);
usersName = (TextView) findViewById(R.id.helloNameView);
usersName.setText(enterName.getText().toString());
}
I created simple application in android. I have a user profile in navigation drawer. when choose address option in that drawer Open that fragment (Example:Address fragment). In that layout i put save button. While click that save button i want validate all the fields. But, when i choose that option from the drawer, application unfortunately stopped.
My code here:
AddressFragment.java
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddressFragment extends Fragment {
EditText line2;
Button addrsave;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout_address, container, false);
addrsave = (Button) getActivity().findViewById(R.id.addrsave);
// Get a reference to the AutoCompleteTextView in the layout
AutoCompleteTextView textView = (AutoCompleteTextView) view.findViewById(R.id.city_autoCompleteTextView);
// Get the string array
String[] city = getResources().getStringArray(R.array.city);
// Create the adapter and set it to the AutoCompleteTextView
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, city);
textView.setAdapter(adapter);
addrsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String addr = line2.getText().toString();
if (addr.equals("")) {
Toast.makeText(getActivity().getApplicationContext(), "Field cannot be left blank.", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
}
My logcat:
07-22 12:47:46.235 6355-6355/com.h2o E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.h2o, PID: 6355
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.h2o/com.h2o.AccountActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' 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.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.h2o.AddressFragment.onCreateView(AddressFragment.java:38)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:551)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1220)
at android.app.Activity.performStart(Activity.java:5953)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2261)
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)
Please anyone help!!
Thanks in advance!!!
Change this:
addrsave = (Button) getActivity().findViewById(R.id.addrsave);
to this:
addrsave = (Button) view.findViewById(R.id.addrsave);
Problem is that you are doing findViewById() on getActivity() which gives you a null. And then setting an onClickListener on it will throw NullPointerException.
Hope it helps! :)
Change this line
addrsave = (Button) getActivity().findViewById(R.id.addrsave);
to
addrsave = (Button) view.findViewById(R.id.addrsave);
Your R.layout.fragment_layout_address is assigned to view so you have to use view variable to get the button from layout. Secondly, Also initialize line2 which will throw an exception of NPE(Null Pointer) once you resolve the first issue
I cant see where you have initialized line2 ?
So line2 is null which might cause the exception
String addr = line2.getText().toString();
I think you have added button in fragment and you are trying to retrive it from activity. So change retrieving the view from getActivity() to view like below
addrsave = (Button) getActivity().findViewById(R.id.addrsave);
Replace the above with the following line
addrsave = (Button) view.findViewById(R.id.addrsave);
And You missed the line2 view initialization in line number 38
i am new to android development and was trying to create RelativeLayout using Java code.
Below is my MainActivty.java
package com.rt.droid.rellayoutjava;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.RelativeLayout.LayoutParams;
public class MainActivity extends Activity {
RelativeLayout r;
public static LayoutParams msgDim;
EditText userNameVal, passwordVal;
TextView message, userName, password;
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
createMessage();
r.addView(message,msgDim);
setContentView(r);
}
public void init() {
r = new RelativeLayout(this);
LayoutParams dimensions = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
r.setLayoutParams(dimensions);
userNameVal = new EditText(this);
passwordVal = new EditText(this);
message=new TextView(this);
userName = new TextView(this);
password = new TextView(this);
login = new Button(this);
}
public void createMessage(){
LayoutParams msgDim = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
msgDim.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
message.setLayoutParams(msgDim);
message.setText("Please login first");
message.setTextColor(Color.rgb(0,0,0));
}
}
However i get the null pointer exception(below from Logcat)
Process: com.rt.droid.rellayoutjava, PID: 2471
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rt.droid.rellayoutjava/com.rt.droid.rellayoutjava.MainActivity}: java.lang.NullPointerException: Attempt to read from field 'int android.view.ViewGroup$LayoutParams.width' 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 read from field 'int android.view.ViewGroup$LayoutParams.width' on a null object reference
at android.view.ViewGroup$LayoutParams.<init>(ViewGroup.java:6403)
at android.view.ViewGroup$MarginLayoutParams.<init>(ViewGroup.java:6685)
at android.widget.RelativeLayout$LayoutParams.<init>(RelativeLayout.java:1345)
at android.widget.RelativeLayout.generateLayoutParams(RelativeLayout.java:1104)
at android.view.ViewGroup.addViewInner(ViewGroup.java:3889)
at android.view.ViewGroup.addView(ViewGroup.java:3733)
at android.view.ViewGroup.addView(ViewGroup.java:3709)
at com.rt.droid.rellayoutjava.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:5933)
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)
Any pointers would be appreciated.
First of all, I suggest you to use XML files to define your layout, instead of writing them programmatically (you can search for any kind of example and tutorial).
Anyway, your specific problem is related to the variable msgDim which is not initialized. Change your onCreate() to this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
createMessage();
msgDim = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
r.addView(message,msgDim);
setContentView(r);
}
Try using this:
r = new RelativeLayout(this);
RelativeLayout.LayoutParams dimensions = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
r.setLayoutParams(dimensions);
The first answer under this question has more complete code: Programatically creating a RelativeLayout in Android
Guys I am getting an error and I am not sure how to solve it please help me.
Here is my code:
package com.appschool.www.projectphase1516;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import com.appschool.www.projectphase1516.R;
import org.w3c.dom.Text;
public class AccountlistActivity extends Activity implements View.OnClickListener {
LinearLayout horiz;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accountlist);
horiz = (LinearLayout) findViewById(R.id.linearlayouthere);
Accountlistcreator();
setContentView(horiz);
}
public void Accountlistcreator(){
SharedPreferences sp = getSharedPreferences("details",1);
int numofaccounts = sp.getInt("numofaccouns",0);
horiz.removeAllViews();
for(int i=0;i<=numofaccounts;i++) {
TextView titleaccount = new TextView(this);
titleaccount.setText(sp.getString("accountTitle" + i, ""));
titleaccount.setTextSize(20);
horiz.addView(titleaccount);
Button seeaccount = new Button(this);
seeaccount.setText("See Details");
seeaccount.setId(i);
seeaccount.setLayoutParams(new FrameLayout.LayoutParams(200,100));
seeaccount.setOnClickListener(this);
horiz.addView(seeaccount);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.accountlist, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View view) {
SharedPreferences sp = getSharedPreferences("details",1);
int num = sp.getInt("numofaccouns",0);
for(int x=0;x<=num;x++){
if(view.getId()==x){
Intent myaccount = new Intent(AccountlistActivity.this,MyaccountActivity.class);
myaccount.putExtra("numbtn",x);
startActivity(myaccount);
}
}
}
}
And here is the error I am getting:
Process: com.appschool.www.projectphase1516, PID: 2751
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.appschool.www.projectphase1516/com.appschool.www.projectphase1516.AccountlistActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
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:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3562)
at android.view.ViewGroup.addView(ViewGroup.java:3415)
at android.view.ViewGroup.addView(ViewGroup.java:3391)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:309)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:299)
at android.app.Activity.setContentView(Activity.java:1949)
at com.appschool.www.projectphase1516.AccountlistActivity.onCreate(AccountlistActivity.java:29)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
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:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Please help me out guys!
The code should create a specific number of buttons and textviews.
I am trying to remove and recreate all of them everytime I am going to that activity and am not sure why I keep getting an error :[
EDIT:
thanks it now runs but there is another problem
it doesnt create more than 1 textview and a button and i am not sure why
(i am pretty new to java development,so i dont know complex features like the comment above me ) i am just doing homework :P
Remove the
setContentView(horiz);
horiz is already a part of the activity's content view.
Your approach is wrong, you want to fill your layout with a lot of information by creating multiple textviews to show information, what you need is a list view and a custom list adapter, so you can get from your shared preferences info you will save in a list, and then pass it to the adapter so the adapter can build all the views you want and doing it better and easier than your approach.
First answer: horiz already has a parent (it's already part of the contentview which you set). Remove setContentView(horiz)
To answer your second question:
SharedPreferences sp = getSharedPreferences("details",1);
int numofaccounts = sp.getInt("numofaccouns",0);
Which means you get sharedpreferences (details) with entry numofaccouns. That one doesnt exist, however, because you never save it. You only get a non-existing entry, and if that one doesnt exist, you default it to 0. The forloop is initialized like for (int i = 0; i <= numofaccouns; i++) which means you always hit index i == 0, because numofaccouns is always 0
final String SHARED_PREFS = "details";
final String NUMBER_OF_ACCOUNTS = "numberOfAccounts";
final int NUMBER_OF_ACCOUNTS_DEFAULT = 10;
int numberOfAccounts = 75;
//to save into sharedpreferences:
getSharedPreferences(SHARED_PREFS, MODE_PRIVATE).edit().put(NUMBER_OF_ACCOUNTS, numberOfAccounts).commit();
//to retrieve that value:
numberOfAccounts = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE).getInt(NUMBER_OF_ACCOUNTS, NUMBER_OF_ACCOUNTS_DEFAULT);
saving all the accounts et cetera can be done in exactly the same manner as the example given above.