I am using numbers stored in shared preferences to send text messages but when i run the app it crashes and the logcat says there is an illegal destination address how?
here is my logcat
12-30 21:01:30.758 12239-12239/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.beez.help2, PID: 12239
java.lang.IllegalArgumentException: Invalid destinationAddress
at android.telephony.SmsManager.sendTextMessage(SmsManager.java:127)
at com.android.beez.help2.MainActivity.sendSms(MainActivity.java:63)
at com.android.beez.help2.MainActivity$2.onClick(MainActivity.java:41)
at android.view.View.performClick(View.java:4475)
at android.view.View$PerformClick.run(View.java:18790)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5328)
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:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
and here is my
MainActivity.java
package com.android.beez.help2;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonInit();
Button setupMa = (Button) findViewById(R.id.setupMA);
setupMa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent a = new Intent(MainActivity.this,Setup.class);
startActivity(a);
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadCredit();
sendSms();
}
});
}
protected void sendSms() {
spInit();
String number1 = sharedPreferences.getString("first", "");
String number2 = sharedPreferences.getString("second", "");
String number3 = sharedPreferences.getString("third", "");
String name = sharedPreferences.getString("name", "");
String text = "Help, this is " + name + ", if you are reading this I am in trouble please help me" +
" Iam located at " + "http://www.google.com/maps/place/"+GPSTracker.latitude+","+GPSTracker.longitude+ " " +
"" +
"" +
"-Sent via the Emergency App";
SmsManager manager = SmsManager.getDefault();
manager.sendTextMessage(number1, null, text, null, null);
manager.sendTextMessage(number2, null, text, null, null);
manager.sendTextMessage(number3, null, text, null, null);
boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
Intent launchSetups = new Intent(MainActivity.this, Setup.class);
startActivity(launchSetups);
}
}
protected void loadCredit() {
spInit();
String creditLine = sharedPreferences.getString("dialLoadSp","");
Uri number = Uri.parse("tel:"+creditLine);
Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
startActivity(callIntent);
}
public void buttonInit() {
button = (Button) findViewById(R.id.button_main);
}
public void spInit() {
sharedPreferences = MainActivity.this.getSharedPreferences("com.android.beez.help2",MODE_PRIVATE);
}
}
The numbers the messages are being sent to are from editTexts and are the stored in sharedPreferences. could the problem be from shared preferences or is it and issue of the text manager
I think you should specify the destination address add an if... if(num1!="" || num2!="" || num3...)
manager.sendText...
Oh, I know this one :) Hope I'm not to late.
IllegalArgumentException is thrown if destinationAddress or text are empty.
In your case, you have this String number1 = sharedPreferences.getString("first", ""); which means that your number1 is empty at first run of the app, and therefore you get that exception.
Also you didn't provide full code here, where you said that numbers would be fill from edit text.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I want to move all data 5 (EditText) from activity 1 to 2
public class MainActivity extends Activity
private EditText fName_ET;
private EditText lName_ET;
private EditText phoneNum_ET;
private EditText eMail_ET;
private EditText deviceModel_ET;
private EditText nameDevice_ET;
private Button nextPage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
fName_ET = (EditText)findViewById(R.id.fName_ET);
lName_ET = (EditText)findViewById(R.id.lName_ET);
phoneNum_ET = (EditText)findViewById(R.id.phone_ET);
eMail_ET = (EditText)findViewById(R.id.mail_ET);
nameDevice_ET = (EditText)findViewById(R.id.name_device);
deviceModel_ET = (EditText)findViewById(R.id.model_device);
nextPage = (Button)findViewById(R.id.next_btn);
nextPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
String fName = fName_ET.getText().toString().trim();
String lName = lName_ET.getText().toString().trim();
String email = eMail_ET.getText().toString().trim();
String phone = phoneNum_ET.getText().toString().trim();
String nameDevice = nameDevice_ET.getText().toString().trim();
String modelDevice =deviceModel_ET.getText().toString().trim();
intent.putExtra("modelDevice",modelDevice);
intent.putExtra("fName", fName);
intent.putExtra("lName", lName);
intent.putExtra("phone", phone);
intent.putExtra("email", email);
intent.putExtra("nameDevice", nameDevice);
startActivity(intent);
}
});
public class Main2Activity extends Activity
{
package com.example.eranp.cp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Main2Activity extends Activity {
private EditText pro_device_det;
private Button saveDataBase;
private DatabaseReference databaseCustomer, databaseDevice, databaseProblem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main3);
databaseCustomer = FirebaseDatabase.getInstance().getReference("customers");
databaseDevice = FirebaseDatabase.getInstance().getReference("device");
databaseProblem = FirebaseDatabase.getInstance().getReference("problem");
saveDataBase = (Button) findViewById(R.id.save_btn);
pro_device_det = (EditText) findViewById(R.id.pro_device_det);
Intent intent = getIntent();
final String fName = intent.getStringExtra("fName");
final String lName = intent.getStringExtra("lName");
final String phone = intent.getStringExtra("phone");
final String email = intent.getStringExtra("email");
final String modelDevice = intent.getStringExtra("modelDevice");
final String nameDevice = intent.getStringExtra("nameDevice");
saveDataBase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String proDeviceDet = pro_device_det.getText().toString().trim();
String shortProDeviceDet = string3Words(proDeviceDet);
DateFormat df = new SimpleDateFormat("d MMM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());
if (!TextUtils.isEmpty(proDeviceDet)) {
String id = databaseCustomer.push().getKey();
Customer customer = new Customer(id, fName, lName, email, phone);
databaseCustomer.child(id).setValue(customer);
Device device = new Device(id, nameDevice, modelDevice);
databaseDevice.child(id).setValue(device);
Problem problem = new Problem(id, date, proDeviceDet, 0, shortProDeviceDet);
// Toast.makeText(this , "Customer added", Toast.LENGTH_LONG).show();
} else {
// Toast.makeText(this, "Please write on an empty cell", Toast.LENGTH_LONG).show();
}
}
});
}
private String string3Words(String s) {
String[] splitted = s.split("\\s+");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < splitted.length; i++) {
sb.append(splitted[i]);
if (i == 3) {
break;
}
}
String newS = sb.toString();
return newS;
}
}
log when I press:
down VM 03-09 14:47:16.903 3476-3476/com.example.eranp.clientpage
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.eranp.clientpage, PID: 3476
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.eranp.clientpage/com.example.eranp.clientpage.Main2Activity}:
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:2924)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2985)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1635)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
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.example.eranp.clientpage.Main2Activity.onCreate(Main2Activity.java:50)
at android.app.Activity.performCreate(Activity.java:6912)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2877)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2985)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1635)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Why when I press the next button the app crashing?
Thank you for helping!
You are trying to set a click listener on a button in Main2Activity. Most likely the button can't be inflated from the second activity's layout because it doesn't exist.
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference at
com.example.eranp.clientpage.Main2Activity.onCreate(Main2Activity.java:50)
at
As per your error log you are getting error because of this
Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference at com.example.eranp.clientpage.Main2Activity.onCreate(Main2Activity.java:50)
saveDataBase = (Button) findViewById(R.id.save_btn);
saveDataBase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// code...
}
});
Check weather button id is correct and is in same layout of the activity or not.
Im very new new to Firebase and Im creating my first app.
Im having 2 issues that I would like to get some help please.
I have linked my Android Studio application to my Firebase project and created the code for the Sigup of new user.
SignupActivity.java
package com.company.fbaseapp.activities;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.company.fbaseapp.R;
public class SignupActivity extends AppCompatActivity {
private static final String TAG = "SignupActivity";
private EditText mUsername;
private EditText mEmail;
private EditText mPassword;
private Button mSignup;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
//mUsername = (EditText) findViewById(R.id.input_username);
mEmail = (EditText) findViewById(R.id.input_email);
mPassword = (EditText) findViewById(R.id.input_password);
mSignup = (Button) findViewById(R.id.btn_signup);
mSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: attempting to signup.");
// Check for null valued EditText fields
if (!isEmpty (mEmail.getText().toString()) && !isEmpty (mPassword.getText().toString())) {
signupNewUser(mEmail.getText().toString(), mPassword.getText().toString());
//Toast.makeText(SignupActivity.this, "Thank you for signing up", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(SignupActivity.this, "You must fill out all the fields", Toast.LENGTH_SHORT).show();
}
}
} );
hideSoftKeyboard();
}
private void signupNewUser(String email, String password) {
showDialog();
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
.addOnCompleteListener( new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "onComplete: onComplete: " + task.isSuccessful());
if (task.isSuccessful()) {
Log.d(TAG, "onComplete: AuthState: " + FirebaseAuth.getInstance()
.getCurrentUser()
.getUid());
FirebaseUser currentperson=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Users").child(currentperson.getUid());
ref.child("Username").setValue(name);
FirebaseAuth.getInstance().signOut();
redirectLoginScreen();
}
if (!task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "Unable to signup", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Return true if the #param is null
* #param string
* #return
*/
private boolean isEmpty(String string){
return string.equals("");
}
/**
* Redirects the user to the login screen
*/
private void redirectLoginScreen(){
Log.d(TAG, "redirectLoginScreen: redirecting to login screen.");
Intent intent = new Intent(SignupActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
private void showDialog(){
mProgressBar.setVisibility(View.VISIBLE);
}
private void hideDialog(){
if(mProgressBar.getVisibility() == View.VISIBLE){
mProgressBar.setVisibility(View.INVISIBLE);
}
}
private void hideSoftKeyboard(){
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}
LogCat
12-30 01:19:18.492 31917-31917/com.company.fbaseapp D/SignupActivity: onClick: attempting to signup.
12-30 01:19:18.493 31917-31917/com.company.fbaseapp D/AndroidRuntime: Shutting down VM
12-30 01:19:18.497 31917-31917/com.company.fbaseapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.company.fbaseapp, PID: 31917
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference
at com.company.fbaseapp.activities.SignupActivity.showDialog(SignupActivity.java:126)
at com.company.fbaseapp.activities.SignupActivity.signupNewUser(SignupActivity.java:72)
at com.company.fbaseapp.activities.SignupActivity.access$300(SignupActivity.java:21)
at com.company.fbaseapp.activities.SignupActivity$1.onClick(SignupActivity.java:54)
at android.view.View.performClick(View.java:6289)
at android.view.View$PerformClick.run(View.java:24800)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6809)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
12-30 01:19:18.499 31917-31917/com.company.fbaseapp D/AppTracker: App Event: crash
The first issue is that the application is crashing when I click on the mSignup button.
Thesecond issue is that I would like to know how I can add a Unique Username to each registerd user.
Please help me figure out how to fix these 2 issues.
Thanks
This is the error:
`Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference`
the progressbar is null, you need to add this:
mProgressBar = (ProgressBar) findViewById(R.id.progressBar); //your id in xml
Regarding unique username for each user, you can do this:
FirebaseUser currentperson=FirebaseAuth.getInstance().getCurrentUser();
then if you are saving to the database, you can do this:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Users");
ref.child(currentperson.getUid());
The above will add a unique userid to each username.
If you mean to add a unique username in authentication, you cannot do that. But the email is unique there by default so if you try to register another user with same email then you will get error:authentication failed
Edit:
You cannot add username in authentication, if you go to the console then you will see the userid and email there added. The authentication provides you with a userid but username cannot be added in the authentication, it can only be added in the database, can do this:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Users").child(currentperson.getUid());
ref.child("Username").setValue(name);
then in your firebase database you would have this:
Users
LA0rRvP4TrewYbMSl0bDA3ork8h2
Username: hisname_here
I am facing the problem when I use Intent to send a value to another activity by click a button. I have tried to solve it in many ways but it always show NullPointerException although I declared it clearly.
Here is my code.
Manufacturer.java
package com.example.student.macheckcar;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class Manufacturer extends AppCompatActivity {
public String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manufacturer);
Button toyota = (Button) findViewById(R.id.Toyota);
Button subaru = (Button) findViewById(R.id.Subaru);
Button audi = (Button) findViewById(R.id.Audi);
toyota.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Toyota";
goAnother(message.toString());
}
});
subaru.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Subaru";
goAnother(message);
}
});
audi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Audi";
goAnother(message);
}
});
}
protected void goAnother(String brand){
Intent i = new Intent(Manufacturer.this, ShowCarPrice.class);
i.putExtra("brand", brand);
startActivity(i);
}
}
Showcarprice.java
package com.example.student.macheckcar;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.view.Window;
import java.util.ArrayList;
public class ShowCarPrice extends AppCompatActivity {
private Cursor cursor;
private ArrayList<String> price;
private ArrayAdapter<String> aa;
private DBprice dbPrice;
private Manufacturer maFact;
SQLiteDatabase db;
ListView list;
Intent intent = getIntent();
String brand = intent.getStringExtra("brand");
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_car_price);
list = (ListView) findViewById(R.id.listView);
dbPrice = new DBprice(this);
db = dbPrice.getWritableDatabase();
cursor = db.rawQuery("SELECT " + dbPrice.KEY_TASK + " FROM " + dbPrice.TABLE_NAME + " WHERE Manufacturer = ?", new String[] {brand});
price = new ArrayList<String>();
cursor.moveToFirst();
while ( !cursor.isAfterLast() ){
price.add(cursor.getString(cursor.getColumnIndex(dbPrice.KEY_TASK)));
cursor.moveToNext();
}
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, price);
list.setAdapter(aa);
}
public void onPause() {
super.onPause();
dbPrice.close();
db.close();
}
}
And the error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.student.macheckcar, PID: 934
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.student.macheckcar/com.example.student.macheckcar.ShowCarPrice}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.student.macheckcar.ShowCarPrice.<init>(ShowCarPrice.java:22)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Please help.
UPDATE
public class ShowCarPrice extends AppCompatActivity {
// OK, Create the objects, variables here if needed
Intent intent;
String brand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout);
// You should assign the intent here (in onCreate method)
intent = getIntent();
// Then, the string variable
brand = intent.getStringExtra("brand");
// You can also check whether or not received a valid value
if (brand != null && !brand.isEmpty())
// do something with brand value
else
// brand value is null or empty
}
}
Well, you call getIntent() at the wrong position. You should call getIntent() in method onCreate() , and I don't know why you keep intent as a member of your activity. If I were you I just do
String brand = getIntent().getStringExtra("brand");
in onCreate() method.
get your intent and extras of intent in onCreate() method of activity just check below link for this
https://stackoverflow.com/a/5265952/5316836
I have recently started a new project, at the moment I am trying to create a SQLite database from within the main activity and read from a text file located in my assests folder. Here is my code:
package com.example.kingmarkmcc.universe;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
private Button simulator;
private Button helper;
private Button settings;
private Button milkyway;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
if (v == simulator) {
Intent intent = new Intent(MainActivity.this, Simulator.class);
startActivity(intent);
} else if (v == helper) {
Intent intent = new Intent(MainActivity.this, HelpOptions.class);
startActivity(intent);
} else if (v == settings) {
Intent intent = new Intent(MainActivity.this, Settings.class);
startActivity(intent);
} else {
Intent intent = new Intent(MainActivity.this, MilkyWay.class);
startActivity(intent);
}
}
};
simulator = (Button) findViewById(R.id.buttonr1b1);
simulator.setOnClickListener(listener);
helper = (Button) findViewById(R.id.buttonr1b2);
helper.setOnClickListener(listener);
settings = (Button) findViewById(R.id.buttonr2b1);
settings.setOnClickListener(listener);
milkyway = (Button) findViewById(R.id.buttonr2b2);
milkyway.setOnClickListener(listener);
}
#Override
protected void onStart()
{
super.onStart();
MainActivity myMain = new MainActivity();
myMain.createDB();
}
#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);
}
private void createDB(){
SQLiteDatabase db= null;
final String dbName = "starDB";
final String tableName = "starTable";
String[] rowRead;
String line;
try {
InputStream input;
input = getAssets().open("refinedData.txt");
InputStreamReader inputReader = new InputStreamReader(input);
BufferedReader bufferReader = new BufferedReader(inputReader);
//Retrieve or create DataBase
db = this.openOrCreateDatabase(dbName, MODE_PRIVATE, null);
//Creating table
db.execSQL("CREATE TABLE IF NOT EXISTS "
+ tableName
+ " (id INTEGER, proper TEXT, dist INTEGER , absmag INTEGER , spect TEXT , ci INTEGER , x INTEGER , y INTEGER , z INTEGER , vx INTEGER , vy INTEGER , vz INTEGER);");
while((line = bufferReader.readLine())!= null) {
rowRead = line.split(",");
// Put data into table
db.execSQL("INSERT INTO "
+ tableName
+ " (id, proper, dist, absmag, spect, ci, x, y, z, vx, vy, vz)"
+ " VALUES (" + rowRead[0] + "," + rowRead[1] + "," + rowRead[2] + "," + rowRead[3] + "," + rowRead[4] + "," + rowRead[5] + "," + rowRead[6] + "," + rowRead[7] + "," + rowRead[8] + "," + rowRead[9] + "," + rowRead[10] + "," + rowRead[11] + ");");
}
bufferReader.close();
Cursor c = db.rawQuery("SELECT * FROM " + tableName, null);
int Column1 = c.getColumnIndex("id");
int Column2 = c.getColumnIndex("x");
c.moveToFirst();
int id = c.getInt(Column1);
int x = c.getInt(Column2);
System.out.println(id);
System.out.println(x);
Toast.makeText(MainActivity.this, "End", Toast.LENGTH_LONG).show();
}
catch(Exception e) {
Log.e("Error", "Error", e);}
finally {
if (db != null)
db.close();
}
}
This is the error that I am receiving:
02-04 17:41:28.973 27362-27362/com.example.kingmarkmcc.universe D/AndroidRuntime: Shutting down VM
02-04 17:41:28.974 27362-27362/com.example.kingmarkmcc.universe E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kingmarkmcc.universe, PID: 27362
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kingmarkmcc.universe/com.example.kingmarkmcc.universe.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2362)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424)
at android.app.ActivityThread.access$900(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1323)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:139)
at android.app.ActivityThread.main(ActivityThread.java:5298)
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:950)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
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:106)
at com.example.kingmarkmcc.universe.MainActivity.createDB(MainActivity.java:114)
at com.example.kingmarkmcc.universe.MainActivity.onStart(MainActivity.java:83)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1236)
at android.app.Activity.performStart(Activity.java:6088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424)
at android.app.ActivityThread.access$900(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1323)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:139)
at android.app.ActivityThread.main(ActivityThread.java:5298)
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:950)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
02-04 17:41:28.977 27362-27362/com.example.kingmarkmcc.universe D/AppTracker: App Event: crash
I have tried to correct this error but cannot seem to figure out the problem! Any help would be much appreciated
Your immediate problem is this:
MainActivity myMain = new MainActivity();
Never create your own instances of activities this way. For starters, they do not work, as you are seeing. Besides, you are in an instance of MainActivity. You do not need a second one. Just call createDB().
Also, you are performing a lot of disk I/O on the main application thread. Your UI will be frozen for quite some time as a result. Do not do this. Please move significant disk I/O to a background thread.
Note that it would be faster for your user, and simpler for you as a developer, to use SQLiteAssetHelper, to package a prepared database in your app, rather than do a bunch of SQL statements to accomplish the same thing.
program sudenly close when any edittext is left empty when ever i pressed a button to move to next to activity. here is the code.
package cme.ws.com.ws.cme;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* Created by Waqas Aamer on 5/27/2015.
*/
public class areaActivity extends Activity {
int plotarea, coveredarea;
int brickprice, blockprice, cementprice, sandprice, crushprice, ironprice;
int brickprice1, blockprice1, cementprice1, sandprice1, crushprice1, ironprice1;
int plotarea1, coveredarea1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_area);
{
final Context context = getApplicationContext();
final int duration = Toast.LENGTH_SHORT;
Button movenextarea=(Button) findViewById(R.id.buttonnextexteriorwall);
movenextarea.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = getIntent();
if (null != intent)
{
// test = intent.getStringExtra("NameOfVariable");
brickprice1 = intent.getIntExtra("anything00", brickprice);
blockprice1 = intent.getIntExtra("anything11", blockprice);
sandprice1 = intent.getIntExtra("anything22", sandprice);
ironprice1 = intent.getIntExtra("anything33", ironprice);
cementprice1 = intent.getIntExtra("anything44", cementprice);
crushprice1 = intent.getIntExtra("anything55", crushprice);
}
EditText areanumber1 = (EditText) findViewById(R.id.editTextplotarea);
if(areanumber1 == null)
{
Toast toast = Toast.makeText(context, "Please fill the plot area field ", duration);
toast.show();
}
else
{
plotarea1 = Integer.parseInt(areanumber1.getText().toString());
}
EditText areanumber2 = (EditText) findViewById(R.id.editTextcoveredarea);
if(areanumber2 == null)
{
Toast toast1 = Toast.makeText(context, "Please fill the covered area field ", duration);
toast1.show();
}
else
{
coveredarea1 = Integer.parseInt(areanumber2.getText().toString());
}
int sqrt = (int) Math.sqrt(plotarea1);
int oneside = sqrt;
Intent secondActivity = new Intent (getApplicationContext(), exteriorwallActivity.class);
secondActivity.putExtra("anything000", brickprice1);
secondActivity.putExtra("anything111", blockprice1);
secondActivity.putExtra("anything222", cementprice1);
secondActivity.putExtra("anything333", sandprice1);
secondActivity.putExtra("anything444", ironprice1);
secondActivity.putExtra("anything555", crushprice1);
secondActivity.putExtra("anything", oneside);
secondActivity.putExtra("anything1", coveredarea1);
startActivity(secondActivity);
}
});
}
}
}
i want this that whenver a edittext box is left empty .the variable in whcih it is storing that value automatically stores 0.
eroor log is
07-05 23:20:42.206 14348-14348/cme.ws.com.ws.cme E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NumberFormatException: unable to parse '' as integer
at java.lang.Integer.parseInt(Integer.java:412)
at java.lang.Integer.parseInt(Integer.java:382)
at cme.ws.com.ws.cme.areaActivity$1.onClick(areaActivity.java:52)
at android.view.View.performClick(View.java:2408)
at android.view.View$PerformClick.run(View.java:8816)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Your EditText fields cannot be equals null because in previous line of your verification you have initialized them. Instead of using if (areanumber1 == null) and if (areanumber2 == null), check your EditText like this:
boolean isEmpty(EditText textField) {
return textField.getText().toString().trim().length() == 0;
}
If function return false means that EditText is not empty and return true means that EditText is empty.
This test...
if(areanumber1 == null)
does not check if the EditText called areanumber1 has no text. This checks if the variable named areanumber1 is a null reference. Hopefully it's not since you know what IDs your layout XML is using. What's happening is your code is trying to use parseInt() on an empty string.
You should instead do something like this:
String area1text = areanumber1.getText().toString(); // works even if empty
if (TextUtils.isEmpty(area1Text)) { // text is empty
plotarea1 = 0;
} else {
plotarea1 = Integer.parseInt(area1text);
}
TextUtils is an Android class with some useful static methods like the one I used above. Also, make sure your EditTexts are using the proper android:inputType to restrict the text to numbers only, or else the parseInt() will throw an exception.