Unable to instantiate activity ComponentInfo - AndroidStudio - java

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());
}

Related

Onclick button method in fragment

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

Trying to save JSON string into a class to parce between activities (NPE)

I am trying to save my JSON string into a class so that I can pass around that object between activities and not lose any data when pressing the back button. However as I try to set the string into the object I receive a NullPointerException. Here is the code for my java file where the exception is occurring, the class java file, and the error. I am using GSON to serialize and deserialize. Any suggestions as to why this is happening?
NewLocation.java
package com.customledsupply.ledaudit;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Parcelable;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import com.google.gson.Gson;
public class NewLocation extends ActionBarActivity {
public EditText editCoName;
public EditText editCoAddress;
public EditText editCoContact;
public EditText editSqFt;
public EditText editTaxed;
public EditText editConcerns;
public JSON_String json;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_location);
findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveInfo();
Intent i = new Intent(NewLocation.this, RoomList.class);
i.putExtra("json", (Parcelable) json);
startActivity(i);
}
});
editCoName = (EditText) findViewById(R.id.CoName);
editCoAddress = (EditText) findViewById(R.id.CoAddress);
editCoContact = (EditText) findViewById(R.id.CoContact);
editSqFt = (EditText) findViewById(R.id.SqFt);
editTaxed = (EditText) findViewById(R.id.Taxed);
editConcerns = (EditText) findViewById(R.id.Concerns);
SaveInfo();
}
#Override
protected void onResume() {
super.onResume();
LoadInfo();
}
#Override
protected void onDestroy() {
super.onDestroy();
SaveInfo();
}
public void SaveInfo() {
Gson gson = new Gson();
CompanyInfo companyInfo = new CompanyInfo();
companyInfo.setName(editCoName.getText().toString());
companyInfo.setAddress(editCoAddress.getText().toString());
companyInfo.setContact(editCoContact.getText().toString());
companyInfo.setTaxed(editTaxed.getText().toString());
companyInfo.setSqFt(editSqFt.getText().toString());
companyInfo.setConcerns(editConcerns.getText().toString());
json.setJson(gson.toJson(companyInfo));
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("json", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("json", json.getJson());
editor.apply();
}
public void LoadInfo() {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("json", MODE_PRIVATE);
json.setJson(sharedPreferences.getString("json", null));
Gson gson = new Gson();
CompanyInfo companyInfo = gson.fromJson(json.getJson(), CompanyInfo.class);
if (companyInfo != null) {
editCoName.setText(companyInfo.getName());
editCoAddress.setText(companyInfo.getAddress());
editCoContact.setText(companyInfo.getContact());
editTaxed.setText(companyInfo.getTaxed());
editSqFt.setText(companyInfo.getSqFt());
editConcerns.setText(companyInfo.getConcerns());
}
}
#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_new_location, 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();
switch(item.getItemId())
{
case R.id.home:
startActivity(new Intent(getApplicationContext(), MainPage.class));
break;
}
return super.onOptionsItemSelected(item);
}
}
JSON_String.java
package com.customledsupply.ledaudit;
public class JSON_String {
private String json;
public void setJson(String json) {
this.json = json;
}
public String getJson() {
return json;
}
}
NPE error
08-03 08:46:52.081 24423-24423/com.customledsupply.ledaudit E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.customledsupply.ledaudit, PID: 24423
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.customledsupply.ledaudit/com.customledsupply.ledaudit.NewLocation}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2248)
at android.app.ActivityThread.access$800(ActivityThread.java:138)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1199)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5061)
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:780)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:596)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.customledsupply.ledaudit.NewLocation.SaveInfo(NewLocation.java:78)
at com.customledsupply.ledaudit.NewLocation.onCreate(NewLocation.java:52)
at android.app.Activity.performCreate(Activity.java:5237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2248)
            at android.app.ActivityThread.access$800(ActivityThread.java:138)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1199)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5061)
            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:780)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:596)
            at dalvik.system.NativeStart.main(Native Method)
You're trying to cast your json to Parcelable:
i.putExtra("json", (Parcelable) json);
Just pass as a string and in your RoomList.class get from bundle. Cast it to your class with gson and use it.
Your json is null, hence the error. To onCreate add
json = new JSON_String();
If you want to keep passing the object between activites, and not lose it when back button is pressed, you should use startActivityForResults(). This will require you to implement a couple of methods that take care of passing objects between activities. This is a good tutorial.
The problem is You didn't initialize your JSON_String class. You need to initialize the JSON_String like
public JSON_String json = new JSON_String();
Have you tried to initlize the json string?

Error creating Relative Layout using Java Code

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

I can't find this NullPointerException [duplicate]

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

Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first

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.

Categories