Error creating Relative Layout using Java Code - java

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

Related

API doesnt work and progressBar keeps spinning

I am a beginner and i am trying to learn how to use APIs on android. I am doing a bitcoin price app to learn APIs. But i have a few problems.I created a progressbar and a price TextView in mainactivity.xml . I set progressbar visible and textview invisible by default.My thought is very simple, i created a new AsyncTask class and after background things are done , i will set the progressbar invisible and the textview visible in the onPostExecute() to show price. But it didn't work. The progressbar keeps spinning, it doesn't show the price i dont understand why it doesn't work.
The API i am using
MainActivity
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class MainActivity extends AppCompatActivity {
public static String line;
public static ProgressBar progressBar;
static String API_URL="https://api.coindesk.com/v1/bpi/currentprice/try.json";
static TextView priceTextView;
static TextView timeTextView;
static int priceInt;
#Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
priceTextView=(TextView)findViewById(R.id.priceText);
timeTextView=(TextView)findViewById(R.id.timeText);
progressBar=(ProgressBar)findViewById(R.id.progressBar);
retrievePriceTask retrievePriceTask=new retrievePriceTask();
retrievePriceTask.execute();
}
}
class retrievePriceTask extends AsyncTask <Void,Void,String>{
#Override
protected void onPreExecute() {
MainActivity.progressBar.setVisibility(View.VISIBLE);
MainActivity.priceTextView.setVisibility(View.INVISIBLE);
}
#Override
protected String doInBackground(Void... urls) {
try {
URL url = new URL(MainActivity.API_URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
while ((MainActivity.line = bufferedReader.readLine()) != null) {
stringBuilder.append(MainActivity.line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
#Override
protected void onPostExecute(String s) {
MainActivity.priceTextView.setVisibility(View.VISIBLE);
MainActivity.progressBar.setVisibility(View.INVISIBLE);
try{
JSONObject jsonObject=(JSONObject)new JSONTokener(MainActivity.line).nextValue();
MainActivity.priceInt=jsonObject.getJSONObject("bpi").getJSONObject("TRY").getInt("rate");
MainActivity.priceTextView.setText(MainActivity.priceInt);
}
catch (Exception e){
e.printStackTrace();
}
}
}
My Logcat
07-16 10:20:08.884 2269-2269/zaaa.trinki E/AndroidRuntime: FATAL EXCEPTION: main
Process: zaaa.trinki, PID: 2269
java.lang.RuntimeException: Unable to start activity ComponentInfo{zaaa.trinki/zaaa.trinki.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference
at zaaa.trinki.retrievePriceTask.onPreExecute(MainActivity.java:94)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at zaaa.trinki.MainActivity.onCreate(MainActivity.java:55)
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) 
07-16 10:37:42.062 16262-16262/zaaa.trinki E/AndroidRuntime: FATAL EXCEPTION: main
Process: zaaa.trinki, PID: 16262
java.lang.RuntimeException: Unable to start activity ComponentInfo{zaaa.trinki/zaaa.trinki.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x0
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: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:274)
at android.support.v7.widget.ResourcesWrapper.getText(ResourcesWrapper.java:52)
at android.widget.TextView.setText(TextView.java:4122)
at zaaa.trinki.MainActivity.onCreate(MainActivity.java:63)
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) 
Use a ProgressDialog instead of a ProgressBar:
ProgressDialog myProgressDialog = ProgressDialog.show(Context CONTEXT, String TITLE, String MESSAGE, boolean INDETERMINATE, boolean CANCELABLE);
myProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
and in your onPostExecute() just put myProgressDialog.dismiss()

Unable to instantiate activity ComponentInfo - AndroidStudio

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

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

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.

Android MediaRecorder NullPointerException

Im just starting out with Java Development and i am fiddling around with the Android Media recorder. However I am getting a NullPointerException which I click the record button using the following source code:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
//import android.net.Uri;
import android.view.Menu;
import android.view.MenuItem;
import android.os.Environment;
import android.view.View;
import java.io.File;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import java.lang.String;
public class MainActivity extends ActionBarActivity {
String outputFile = "test.3gp";
private MediaRecorder myAudioRecorder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaRecorder myAudioRecorder = new MediaRecorder();
myAudioRecorder = new MediaRecorder();
// Uri target = Uri.parse(outputFile.getAbsolutePath());
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
}
public void Start_Record(View v)
{
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myAudioRecorder.stop();
myAudioRecorder.release();
}
#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);
}
}
I realise that this probably due to the fill pointer being set to NULL, however I am struggling to see how to initialize the file reference for this to vanish. I am getting th exception on mediaRecorderPrepare()
Here is the Exception thrown:
03-09 22:53:56.548 31836-31836/uk.co.spectralgear.spectralboost E/AndroidRuntime﹕ FATAL EXCEPTION: main
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 'void android.media.MediaRecorder.prepare()' on a null object reference
at uk.co..MainActivity.Start_Record(MainActivity.java:38)
            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)
Any help would be greatly appreciated:)
PROBLEM:
Your class variable "myAudioRecord" is null when "Start_Record()" tries to use it:
Caused by: java.lang.NullPointerException:
Attempt to invoke virtual method 'void Android.media.MediaRecorder.prepare()' on a null object reference
SOLUTION: Delete this line from your "onCreate()" method:
public class MainActivity extends ActionBarActivity {
String outputFile = "test.3gp";
private MediaRecorder myAudioRecorder; // Your class variable: OK...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// MediaRecorder myAudioRecorder = new MediaRecorder(); // DELETE THIS LINE!!!
myAudioRecorder = new MediaRecorder(); // OK...
...
The declaration of "myAudioRecorder" inside onCreate() HIDES the outer declaration. So the outer (class-level) "myAudioRecorder" never gets initialized ... and your program dies with an NPE when "Start_Record()" tries to access it.
PS:
Please consider changing the method name to "start_Record()". Or better, "startRecord()". This is more consistent with Java naming conventions.
I think you are using stop() function while it was already stopped. Check your code and logic.

Categories