java.lang.RuntimeException: Unable to instantiate service: java.lang.NullPointerException - java

I' m a complete newcome to android and java and I'm writing an android app with android studio that should show some points on a map each 5 seconds (it's just a test). When I run the app on the emulator I get this on the logcat:
03-13 13:22:28.373 2964-2964/com.example.francesca.geoapp
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.francesca.geoapp, PID: 2964
java.lang.RuntimeException: Unable to instantiate service com.example.francesca.geoapp.DataService: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.handleCreateService(ActivityThread.java:2716)
at android.app.ActivityThread.access$1800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1361)
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 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:105)
at android.support.v4.content.LocalBroadcastManager.getInstance(LocalBroadcastManag er.java:102) at com.example.francesca.geoapp.DataService.<init> (DataService.java:56)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1572)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:2713)
            at android.app.ActivityThread.access$1800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1361)
            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)
the intentService DataService code is
public class DataService extends IntentService {
private LocalBroadcastManager BroadcastNotifier ;
private Timer timer = new Timer();
private List dataList = new ArrayList<testData>();
int i = 0;
//constructor
public DataService() {
super("DataService");
dataList.add(new testData(new LatLng(52.519804, 13.404988), new LatLng(52.519125, 13.406061), 50, 30));
dataList.add(new testData(new LatLng(52.520692, 13.403722), new LatLng(52.519804, 13.404988), 60, 40));
dataList.add(new testData(new LatLng(52.522023, 13.404730), new LatLng(52.520692, 13.403722), 50, 30));
dataList.add(new testData(new LatLng(52.523388, 13.407143), new LatLng(52.522023, 13.404730), 40, 20));
dataList.add(new testData(new LatLng(52.522911, 13.408807), new LatLng(52.523388, 13.407143), 80, 30));
dataList.add(new testData(new LatLng(52.523982, 13.409623), new LatLng(52.522911, 13.408807), 50, 40));
dataList.add(new testData(new LatLng(52.524713, 13.407434), new LatLng(52.523982, 13.409623), 30, 50));
BroadcastNotifier = LocalBroadcastManager.getInstance(this);
timer.scheduleAtFixedRate(task, 0, 5000 );
}
protected void onHandleIntent(Intent i) {
}
//timerTask to send request to the webservice
TimerTask task = new TimerTask() {
#Override
public void run() {
if(i <7 ) {
testData test = (testData) dataList.get(i);
data.setCurrentPosition(test.currentPosition);
data.setLatestPosition(test.latestPosition);
data.setSpeed(test.speed);
data.setMediumSpeed(test.mediumSpeed);
i++;
}
}
};
//method to tell subscribers that a newData has arrived
private void OnNewDataSeen() {
Intent localIntent = new Intent();
localIntent.setAction("com.example.android.threadsample.BROADCAST");
localIntent.addCategory(Intent.CATEGORY_DEFAULT);
// Broadcasts the Intent
BroadcastNotifier.sendBroadcast(localIntent);
}
}
And the MenuActivity that should start the intentService is
public class MenuActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
Intent mServiceIntent = new Intent(this, DataService.class);
this.startService(mServiceIntent);
}
public void goToMap(View view){
Intent intent = new Intent(this, MapActivity.class);
startActivity(intent);
}
public void goToData(View view){
Intent intent = new Intent(this, ShowDataActivity.class);
startActivity(intent);
}
}
What have I done wrong?

You can't have this
BroadcastNotifier = LocalBroadcastManager.getInstance(this);
in you constructor. Put it into the onHandleIntent()
this isn't fully initialised in your constructor and a Context cannot be obtained, which it why it is null and you get that NPE.

You should leave constructor with super call only and use onCreate lifecycle callback method.

Related

Null Error attempting to create an intent in AsyncTask

Apologizes if this is a stupid question but I'm attempting to create a Intent to the next activity in AsynTask after it has pulled a user from my AWS Database. Note that this class is HomeActivity and the next one is GroupActivity. Below I have the button that will run the AsynTask:
Button groupPageBtm = findViewById(R.id.groupPage);
groupPageBtm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoadGroupUser loadGroupUser = new LoadGroupUser(HomeActivity.this);
loadGroupUser.execute(makeUserIDString.uniqueIDCreater(userProfile));
}
});
Here is my AsynTask subclass:
class LoadGroupUser extends AsyncTask<String, Void, GroupDO>{
private DynamoDBMapper dynamoDBMapper;
Activity activity;
public LoadGroupUser(Activity mActivity){
this.activity = mActivity;
}
Intent groupLoadIntent = new Intent(activity, GroupActivity.class);
#Override
protected GroupDO doInBackground(String... groupPresidentGroups) {
AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient(AWSMobileClient.getInstance().getCredentialsProvider());
this.dynamoDBMapper = DynamoDBMapper.builder()
.dynamoDBClient(dynamoDBClient)
.awsConfiguration(AWSMobileClient.getInstance().getConfiguration())
.build();
GroupDO groupPresDO = dynamoDBMapper.load(GroupDO.class, groupPresidentGroups[0]);
Log.i("loadedPresident: ", groupPresDO.getGroupId().toString());
return null;
}
#Override
protected void onPostExecute(GroupDO groupDO) {
super.onPostExecute(groupDO);
groupLoadIntent.putExtra("groupPresident", groupDO.getGroupPresident().toString());
activity.startActivity(groupLoadIntent);
Log.i("groupPresident", groupDO.getGroupPresident().toString());
}
}
Error Message:
-12 17:02:59.424 10503-10503/com.ronone.securesender E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ronone.securesender, PID: 10503
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ComponentName.<init>(ComponentName.java:130)
at android.content.Intent.<init>(Intent.java:5780)
at com.ronone.securesender.LoadGroupUser.<init>(HomeActivity.java:188)
at com.ronone.securesender.HomeActivity$1.onClick(HomeActivity.java:77)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
The problem is here:
public LoadGroupUser(Activity mActivity){
this.activity = mActivity;
}
Intent groupLoadIntent = new Intent(activity, GroupActivity.class);
The field initializer runs before the constructor, so activity is still null. Do this instead:
Intent groupLoadIntent;
public LoadGroupUser(Activity mActivity){
this.activity = mActivity;
groupLoadIntent = new Intent(activity, GroupActivity.class);
}
But note that you're potentially leaking your activity by having a strong reference to it in an AsyncTask. That's a whole other topic. Search this site for "AsyncTask activity leak."

Playing sound via button crash (Android)

I have 3 buttons, when the buttons are tapped a sound will play. But for some reason i am starting to get this error now, after i implemented all 3 buttons. When i did just 1 button, it played the sound with no error. After i implemented 2 more, the app started to always crash.
Here is my code for the button in my .xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play!"
android:id="#+id/play1"
android:layout_below="#+id/imageView"
android:layout_toLeftOf="#+id/play3"
android:layout_toStartOf="#+id/play3" />
And here is my code in the mainactivity.java
// final MediaPlayer mp = MediaPlayer.create(this, R.raw.sounds1);
// final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.sounds2);
// final MediaPlayer mp3 = MediaPlayer.create(this, R.raw.sounds3);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Button play_button = (Button)this.findViewById(R.id.play1);
//// Button play_button2 = (Button)this.findViewById(R.id.play2);
//// Button play_button3 = (Button)this.findViewById(R.id.play3);
//
// play_button.setOnClickListener(new View.OnClickListener() {
// public void onClick(View v) {
//
//
// mp.start();
// }
// });
//
// play_button2.setOnClickListener(new View.OnClickListener() {
// public void onClick(View v) {
//
//
// mp2.start();
// }
// });
//
// play_button3.setOnClickListener(new View.OnClickListener() {
// public void onClick(View v) {
//
//
// mp3.start();
// }
// });
}
Here is the log too!
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.sounds.apps.sounds/com.sounds.apps.sounds.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
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 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:85)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:74)
at android.media.MediaPlayer.create(MediaPlayer.java:919)
at android.media.MediaPlayer.create(MediaPlayer.java:902)
at com.sounds.apps.sounds.MainActivity.<init>(MainActivity.java:14)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1572)
at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
            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)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.sounds1);
final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.sounds2);
final MediaPlayer mp3 = MediaPlayer.create(this, R.raw.sounds3);
Button play_button = (Button)this.findViewById(R.id.play1);
Button play_button2 = (Button)this.findViewById(R.id.play2);
Button play_button3 = (Button)this.findViewById(R.id.play3);
play_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.start();
}
});
play_button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp2.start();
}
});
play_button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp3.start();
}
});
}

How can i solve getApplicationContext() java.lang.NullPointerExeception

I am trying to connect to an azure application, using android, but I am getting this error. Here is my code and my logs.
I have checked everything and it seen to be right, but the problem I think is with getApplicationContext(). I am unable to debug.
can someone help me please?
public class login extends Activity {
UserServicesImpl usv;
private EditText txtemail;
private EditText txtpassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
txtemail = (EditText) findViewById(R.id.txtemail);
txtpassword = (EditText) findViewById(R.id.txtpassword);
}
public void LoginKarrega(View view){
usv = new UserServicesImpl();
AlertDialog alertDialog = new AlertDialog.Builder(login.this).create();
alertDialog.setTitle("Alert");
if(usv.exist(txtemail.getText().toString(), txtpassword.getText().toString()) == true) {
alertDialog.setMessage("Sucessful login");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
else {
alertDialog.setMessage("wrong login");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
alertDialog.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.menu_login, 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);
}
}
Logcat:
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4007)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java: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.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java: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 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:105)
at com.microsoft.windowsazure.mobileservices.notifications.MobileServicePush.<init>(MobileServicePush.java:134)
at com.microsoft.windowsazure.mobileservices.MobileServiceClient.initialize(MobileServiceClient.java:1473)
at com.microsoft.windowsazure.mobileservices.MobileServiceClient.<init>(MobileServiceClient.java:182)
at com.microsoft.windowsazure.mobileservices.MobileServiceClient.<init>(MobileServiceClient.java:158)
at ao.co.karrega.services.customers.UserServicesImpl.<init>(UserServicesImpl.java:39)
at ao.co.karrega.login.LoginKarrega(login.java:32)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at android.view.View$1.onClick(View.java:4002)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java: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)
Use below code to solve this error. Currently you are using this instead of getApplicationContext().
try {
mClient = new MobileServiceClient(
"https://newvbdemo.azure-mobile.net/",
"SUFYiOYEAlbEoKfsDgfWNIywaPSMhC29",
getApplicationContext()
);
mTable = mClient.getTable("Users",Users.class);
}catch (MalformedURLException e) {
e.printStackTrace();
}
Your class UserServicesImpl extends Activity but it does not seem to be an Activity.
In particular, activities usually don't have an explicit constructor, and you cannot use an Activity as a Context before its onCreate() lifecycle method. Construction phase <init> in your stacktrace is too early.
The stacktrace also shows that you're trying to instantiate an activity with new in LoginKarrega. Never instantiate an activity with new yourself.
Looks like you should be removing the extends Activity and pass a Context as an argument instead.

MediaPlayer with Internal Files

I'm trying to select an audio file from internal storage, which I then create a media player from.
public void openPressed(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Audio.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
MediaPlayer player = MediaPlayer.create(this, data.getData());
player.start();
}
}
All of this is in my main activity, but after selecting a file, the app crashes.
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/audio/media/29 }} to activity {com.malik.mixtape/com.malik.mixtape.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3539)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582)
at android.app.ActivityThread.access$1300(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
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.media.MediaPlayer.start()' on a null object reference
at com.malik.mixtape.MainActivity.onActivityResult(MainActivity.java:65)
at android.app.Activity.dispatchActivityResult(Activity.java:6135)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3535)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582)
            at android.app.ActivityThread.access$1300(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
            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)
Try to do this instead, I am assuming that data.getData() returns the path to the file,
MediaPlayer player = new MediaPlayer();
player.setOnPreparedListener(mPreparedListener);
player.setDataSource(MyActivity.this, Uri.fromFile(new File(data.getData())));
MediaPlayer.OnPreparedListener mPreparedListener = new MediaPlayer.OnPreparedListener()
{
/** Called when MediaPlayer is ready */
public void onPrepared(MediaPlayer player)
{
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
player.start();
}
};

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

Categories