During development, there was a similar problem and also because of the fact that I am a novice, do not know how to handle it, thanks in advance to those who help!
I tried to change something to rewrite over and all else fails, I can not understand at what point I did something wrong
Activity
public class FormActivity extends AppCompatActivity {
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.form);
///=================================
/////Автоматическийм расчет веремени
EditText et1 = (EditText) findViewById(R.id.formtime);
EditText et2 = (EditText) findViewById(R.id.formdate);
SimpleDateFormat df1 = new SimpleDateFormat("HH:mm:ss");
SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd ");
Calendar c = Calendar.getInstance();
String e1 = df1.format(c.getTime());
String e2 = df2.format(c.getTime());
et1.setText(e1);
et2.setText(e2);
/////Конец расчета времени
}
public void GeoClick(View v){
String svcName = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(svcName);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(true);
String provider = locationManager.getBestProvider(criteria, true);
Location l = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(l);
locationManager.requestLocationUpdates(provider, 5000, 10, locationListener);
}
private void updateWithNewLocation(Location location) {
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
String latLongString = "No location found";
String addressString = "No address found";
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
} catch (IOException e) {}
}
myLocationText.setText("Your Current Position is:\n" +
latLongString + "\n\n" + addressString);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {updateWithNewLocation(location);}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status,
Bundle extras) {}
};
}
Error
{FATAL EXCEPTION: main java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3591)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3586)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: provider==null
at android.location.LocationManager.getLastKnownLocation(LocationManager.java:1153)
at ru.ochakovo.ochakoco.FormActivity.GeoClick(FormActivity.java:56)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3586)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method) }
You are getting this error most probably, due to un-avialability of GPS Providers. Please ask the person to check settings if Gps Provider or Network Provider has been enabled into Location settings..Hope so it is helpful for you
I think your provider empty null value...
Related
I am trying to create an android app on android studio which scans WIFI signals, and passes all the WIFI signal SSIDs containing "WDT_" to another intent.
When I run the app, it crashes due to a NPE.
I debugged the app, and it says that intent.getStringArrayExtra() in MultipleWifi.java is null.
Am I doing something wrong with passing the string array?
MainActivity.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
WifiConfiguration conf = new WifiConfiguration();
int WDTWifiCount = 0;
List<ScanResult> results = wifiManager.getScanResults();
for (ScanResult scanResult : results) {
if (scanResult.SSID.contains("WDT_")) {
SSIDString[0] = (scanResult.SSID);
WDTWifiCount++;
}
}
WDTWifiCount = 2;
SSIDString[0] = "WDT_12345";
SSIDString[1] = "WDT_14445";
if (WDTWifiCount < 1) {
startActivity(new Intent(this, NoWifi.class));
} else if (WDTWifiCount > 1) {
Intent intent = new Intent(this, MultipleWifi.class);
intent.putExtra("SSIDList", SSIDString);
startActivityForResult(intent, 1);
}
conf.SSID = "\"" + networkSSID + "\"";
conf.preSharedKey = "\"" + networkPass + "\"";
WDTWifiCount = 0;
wifiManager.addNetwork(conf);
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"") && WDTWifiCount != 0) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
break;
}
}
myWebView = new WebView(this);
myWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
myWebView.setWebChromeClient(new WebChromeClient());
myWebView.loadUrl("http://192.168.1.1/index.html");
}
MultipleWifi.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.multiplewifi);
Intent intent = getIntent();
final String[] StringSSID = intent.getStringArrayExtra("SSIDstring");
List<String> SSIDList = new ArrayList<String>(Arrays.asList(StringSSID));
final Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, SSIDList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String SSID = spinner.getSelectedItem().toString();
Intent intent = new Intent();
intent.putExtra("SSID", SSID);
setResult(RESULT_OK, intent);
finish();
}
});
}
Debug:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.wdt, PID: 9031
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.wdt/com.example.wdt.MultipleWifi}: java.lang.NullPointerException: storage == null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2200)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5105)
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:792)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException: storage == null
at java.util.Arrays$ArrayList.<init>(Arrays.java:38)
at java.util.Arrays.asList(Arrays.java:155)
at com.example.wdt.MultipleWifi.onCreate(MultipleWifi.java:23)
at android.app.Activity.performCreate(Activity.java:5275)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2164)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5105)
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:792)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
at dalvik.system.NativeStart.main(Native Method)
EDIT: After editing the key in "intent.putExtra" to SSIDString it still returns null.
Debug:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.wdt, PID: 31443
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.wdt/com.example.wdt.MultipleWifi}: java.lang.NullPointerException: storage == null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2200)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5105)
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:792)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException: storage == null
at java.util.Arrays$ArrayList.<init>(Arrays.java:38)
at java.util.Arrays.asList(Arrays.java:155)
at com.example.wdt.MultipleWifi.onCreate(MultipleWifi.java:23)
at android.app.Activity.performCreate(Activity.java:5275)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2164)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5105)
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:792)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
at dalvik.system.NativeStart.main(Native Method)
You are using wrong key
Intent intent = new Intent(this, MultipleWifi.class);
intent.putExtra("SSIDList", SSIDString);
there is key that you are passing
startActivityForResult(intent, 1);
//change key you are using wrong key here
final String[] StringSSID = intent.getStringArrayExtra("SSIDList");
First take the user permisison!
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSIONS_REQUEST_CODE_ACCESS_COARSE_LOCATION);
//After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method
}else{
getScanningResults();
//do something, permission was previously granted; or legacy device
}
I was using an integer for the money factor in this little test app but I realized that long was more appropriate and I changed the code so that money is a long instead of an int and I changed SharedPreferences appropriately as well, however it does not work wheras it did when I used int. Thank you for the help!
public class Home extends AppCompatActivity {
SharedPreferences pref;
SharedPreferences.Editor editor;
Intent intent;
TextView home_money_view;
long money; // this is the variable that is causing problems
int initial;
final long TEST = (long)-1;
int gold_pieces;
int gold_price = 50;
TimerTask timerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
home_money_view = (TextView) findViewById(R.id.home_money_view)
pref = getApplicationContext().getSharedPreferences("MY_PREFS", MODE_PRIVATE);
editor = pref.edit();
money = pref.getLong("temp_money",Long.MIN_VALUE); // get value
if (money==Long.MIN_VALUE){
money=0;
}
gold_pieces = pref.getInt("temp_gold",-1);
if (gold_pieces==-1){
gold_pieces=0;
}
initial = pref.getInt("initial",0);
money+=initial;
editor.putInt("initial",0);
editor.commit();
home_money_view = (TextView) findViewById(R.id.home_money_view);
home_money_view.setText(money+"");
editor.commit();
}
public void backToSplash(View view){
intent = new Intent(Home.this,BusinessSelector.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
public void goToSecondView(View view){
long temp_money = money;
editor.putLong("temp_money",temp_money); // set value
int temp_gold = gold_pieces;
editor.putInt("temp_gold",temp_gold);
editor.commit();
intent = new Intent(Home.this,SecondView.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
public void goToOtherView(View view) {
long temp_money = money;
editor.putLong("temp_money",temp_money); // set value
int temp_gold = gold_pieces;
editor.putInt("temp_gold", temp_gold);
editor.commit();
intent = new Intent(Home.this, Next.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
Logcat:
04-13 19:01:03.675 12896-12896/com.exampleryancocuzzo.ryan.markettycoon E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exampleryancocuzzo.ryan.markettycoon/com.exampleryancocuzzo.ryan.markettycoon.Home}: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
at android.app.SharedPreferencesImpl.getLong(SharedPreferencesImpl.java:228)
at com.exampleryancocuzzo.ryan.markettycoon.Home.onCreate(Home.java:56)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
I am working on a financial app and i have to use BigDecimal to calculate currency.Now I am trying to make one entrance activity which is searching in the SharedPreferences for a previous registration and if their is one it starts another activity , if not it starts the registration activity.The problem is the registration activity causes NumberFormatException Error while I am trying to construct a new object of time Profit (the Profit class contains BigDecimal field).Also I am not quite sure that I am using SharedPreferences right.I am not quite sure that my idea and my coding are fine because I am new at android development and i am stuck with this problem so I am giving you all the classes.
the Registration activity:
public class Registration extends Activity {
private static String enteredPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final EditText password1 = (EditText) findViewById(R.id.password1);
final EditText password2 = (EditText) findViewById(R.id.password2);
final EditText availability = (EditText) findViewById(R.id.availability);
EditText profitEditText = (EditText) findViewById(R.id.profit);
Spinner spinner = (Spinner) findViewById(R.id.period_spinner);
Button registrationButton = (Button) findViewById(R.id.registrationButton);
DatePicker picker = (DatePicker) findViewById(R.id.thePicker);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.periods_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final String balance = availability.getText().toString().replace(",",".");
String profitPeriod = ((Period) spinner.getSelectedItem()).name();
final Profit profit = new Profit("regular_profit", profitEditText.getText().toString(),
profitPeriod ,picker);
registrationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (password1.getText().toString().equals(password2.getText().toString())) {
enteredPassword = password1.getText().toString();
Repository.setPassword(enteredPassword, mContext);
}
Repository.setBalance(balance, mContext);
Repository.setProfit(profit, mContext);
}
});
}
}
the profit activity
public class Profit {
private Date mProfitDate;
private Date mNextProfitDate;
private BigDecimal value;
public final static String TITLE = "title";
public final static String PERIOD = "period";
Profit(String title,String value, String period, DatePicker picker) {
this.mTitle = title;
if(value!=null){this.value = new BigDecimal(value);}else{ this.value = new BigDecimal("0.0");};
this.mPeriod = Period.class.cast(period);
this.mProfitDate = Repository.getDateFromPicker(picker);
}
public long getNextProfitDate(Date profitDate, Period period){
long unixProfitDate = profitDate.getTime() / 1000L;
long nextProfitDate=0;
switch (period){
case DAILY:
nextProfitDate = DateUtils.DAY_IN_MILLIS/1000 + unixProfitDate;
break;
case WEEKLY:
nextProfitDate = DateUtils.WEEK_IN_MILLIS/1000 + unixProfitDate;
break;
case MONTHLY:
Date dateNow = new Date();
dateNow.getTime();
nextProfitDate = Repository.monthsToSeconds(Calendar.getInstance()
.get(Calendar.MONTH)) + unixProfitDate;
break;
case YEARLY:
nextProfitDate = DateUtils.YEAR_IN_MILLIS/1000 + unixProfitDate;
break;
}
return nextProfitDate;
}
}
the entrance activity
public class EnterActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter);
CountDownTimer timer = new CountDownTimer(3000, 100) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
if(Repository.getPassword(mContext.getApplicationContext()).equals("No Value")){
Intent registrationIntent = new Intent(mContext, Registration.class);
startActivity(registrationIntent);
}
else{
Intent configurationIntent = new Intent(mContext, Configuration.class);
startActivity(configurationIntent);
}
}
}.start();
}
}
the Repository
public class Repository {
public static SharedPreferences sharedPreferences;
private static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
}
public static String getPassword(Context context){
return getPrefs(context).getString(PASSWORD,"No Value");
}
public Repository() {
}
public static void setPassword(String password, Context context){
SharedPreferences.Editor editor = getPrefs(context).edit();
editor.putString(PASSWORD, password);
editor.commit();
}
public static void setBalance(String balance, Context context){
SharedPreferences.Editor editor = getPrefs(context).edit();
editor.putString(BALANCE, balance);
editor.commit();
}
public static void setProfit(Profit profit, Context context){
SharedPreferences.Editor editor = getPrefs(context).edit();
editor.putString(BALANCE, profit.getValue().toString());
editor.commit();
}
}
the output
E/AndroidRuntime: FATAL EXCEPTION: main
E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{/.Registration}: java.lang.NumberFormatException: Bad offset/length: offset=0 len=0 in.length=0
E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
E/AndroidRuntime: at android.app.ActivityThread.access$600(ActivityThread.java:123)
E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:4424)
E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime: Caused by: java.lang.NumberFormatException: Bad offset/length: offset=0 len=0 in.length=0
E/AndroidRuntime: at java.math.BigDecimal.<init>(BigDecimal.java:282)
E/AndroidRuntime: at java.math.BigDecimal.<init>(BigDecimal.java:438)
E/AndroidRuntime: at .Profit.<init>(Profit.java:41)
E/AndroidRuntime: at .Registration.onCreate(Registration.java:57)
E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:4466)
E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
E/AndroidRuntime: at android.app.ActivityThread.access$600(ActivityThread.java:123)
E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:4424)
E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
You instantiate a Profit in only one place in the code you presented:
Profit profit = new Profit("regular_profit", profitEditText.getText().toString(),
profitPeriod, picker);
If that causes a NumberFormatException then it must come from this code in the Profit constructor:
if(value!=null){this.value = new BigDecimal(value);}else{ this.value = new BigDecimal("0.0");};
Since the value String will have come from invoking toString() on an object, you can rely on it to not be null (and anyway, if it were null then you would end up at new BigDecimal("0.0"), and you can verify for yourself that that works fine). That leaves us with new BigDecimal(value) as the culprit. The docs for this constructor provide details of the expected format of the argument string. If the argument does not comply with that format then a NumberFormatException will be thrown.
Among the more likely malformed strings that one might imagine in a scenario such as you describe is an empty string, which is not the same as null in Java. Given that the text is coming from a UI field, you also have to watch out for fun and difficult-to-spot malformations such as leading and trailing whitespace.
Perhaps it would be better to write the affected part of the constructior like so:
if (value != null) {
value = value.trim();
this.value = value.length() == 0 ? BigDecimal.ZERO : new BigDecimal(value);
} else {
this.value = BigDecimal.ZERO;
}
Do note that even with that change, this constructor will still throw NumberFormatException in the event of other kinds of malformation. Wherever you are uncertain about the validity of the data, you should be prepared to handle such an exception.
You aren't parsing your string to a Big Decimal correctly.
The following in your Profit contructor:
if(value!=null)
{
this.value = new BigDecimal(value);
}
else
{
this.value = new BigDecimal("0.0");
}
Needs to parse the string to a BigDecimal. Like the following where this.value is of type BigDecimal:
this.value = (BigDecimal) decimalFormat.parse(value);
Also keep in mind that decimalFormat.parse can throw a ParseException. You will need to handle it with try/catch or throw it.
I'm using achartengine to plot a graph in my app. I declare points in a table in table.xml which is connected to Table.java. Now should my graph get this points and use them. My graph is coded in Graph.java and gets called through Graphdisplay.java.
EDIT2: I changed the code a bit. First of all I added the code from Graphdisplay.java into the onCreate method of Graph.java and deleted Graphdisplay.java.
Second I added some get and set methods like here in the first answer in Graph.java and get the data from Table.java in the onCreate method.
Third I put the get method in the GraphicalView
Graph.java:
public class Graph extends Activity{
//only for x1 for now
public double ds_x1;
public Double getX1(){return this.ds_x1;}
public void setX1(Double ds_x1){this.ds_x1=ds_x1;}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.graph);
//getting the data from Table.java
ds_x1 = getIntent().getExtras().getDouble("s_x1");
Graph line = new Graph();
final GraphicalView gView = line.getView(getApplicationContext());
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
layout.addView(gView);
}
public GraphicalView getView(Context context) {
Double d_x1 = getX1();
ArrayList<Double> xList = new ArrayList<Double>();
double x1 = d_x1;
xList.add(x1);
double x2 = 2;
xList.add(x2);
double x3 = 3;
xList.add(x3);
ArrayList<Double> yList = new ArrayList<Double>();
double y1 = 1;
yList.add(y1);
double y2 = 2;
yList.add(y2);
double y3 = 3;
yList.add(y3);
XYSeries series = new XYSeries("List");
for (int i = 0; i < xList.size(); i++) {
series.add(i, xList.get(i), yList.get(i));
}
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
dataset.addSeries(series);
XYSeriesRenderer renderer = new XYSeriesRenderer();
XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
return ChartFactory.getLineChartView(context, dataset, mRenderer);
}
}
Table.java: Now Double not Strings
EditText x1 = (EditText) findViewById(R.id.x1);
EditText x2 = (EditText) findViewById(R.id.x2);
EditText x3 = (EditText) findViewById(R.id.x3);
EditText y1 = (EditText) findViewById(R.id.y1);
EditText y2 = (EditText) findViewById(R.id.y2);
EditText y3 = (EditText) findViewById(R.id.y3);
Button b_continue = (Button) findViewById(R.id.b_continue);
b_continue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Double s_x1 = Double.parseDouble(x1.getText().toString());
Double s_x2 = Double.parseDouble(x2.getText().toString());
Double s_x3 = Double.parseDouble(x3.getText().toString());
Double s_y1 = Double.parseDouble(y1.getText().toString());
Double s_y2 = Double.parseDouble(y2.getText().toString());
Double s_y3 = Double.parseDouble(y3.getText().toString());
Intent myIntent = new Intent(view.getContext(), Graph.class);
myIntent.putExtra("s_x1", s_x1);
myIntent.putExtra("s_x2", s_x2);
myIntent.putExtra("s_x3", s_x3);
myIntent.putExtra("s_y1", s_y1);
myIntent.putExtra("s_y2", s_y2);
myIntent.putExtra("s_y3", s_y3);
startActivity(myIntent);
}
});
Logcat:
08-29 14:31:00.720 17322-17322/test.com.myApp E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity
ComponentInfo{test.com.myApp/test.com.myApp.Graph}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
at android.app.ActivityThread.access$700(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at test.com.myApp.Graph.getView(Graph.java:96)
at test.com.myApp.Graph.onCreate(Graph.java:44)
at android.app.Activity.performCreate(Activity.java:5372)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
at android.app.ActivityThread.access$700(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Problem: When clicking on the button to get to the graph the app crashes instead of showing the graph with the values! I figured out that the problem is that it isn't a defined value like double double = 5.0. aChartEngine has got problems with the values wich are getting entered in the table.
There's also a method to set "double extras" to your intent:
Intent android.content.Intent.putExtra(String name, double value)
and a method to get double extras:
double android.content.Intent.getDoubleExtra(String name, double defaultValue)
so you don't need to parse the strings...
But yeah, in general that's the right approach. Or do you have a specific problem with it?
EDIT:
use this instead of valueOf:
double y2 = Double.parseDouble(getIntent().getStringExtra("s_y2"))
EDIT2, try:
Button b_continue = (Button) findViewById(R.id.b_continue);
b_continue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String s_x1 = x1.getText().toString();
String s_x2 = x2.getText().toString();
String s_x3 = x3.getText().toString();
String s_y1 = y1.getText().toString();
String s_y2 = y2.getText().toString();
String s_y3 = y3.getText().toString();
Intent myIntent2 = new Intent(view.getContext(), Graph.class);
myIntent2.putExtra("s_x1", s_x1);
myIntent2.putExtra("s_x2", s_x2);
myIntent2.putExtra("s_x3", s_x3);
myIntent2.putExtra("s_y1", s_y1);
myIntent2.putExtra("s_y2", s_y2);
myIntent2.putExtra("s_y3", s_y3);
Intent myIntent = new Intent(view.getContext(), Graphdisplay.class);
startActivity(myIntent);
}
});
I have a problem again with AsyncTask in Android.
I made a simple AsyncTask class to display multiple markers on a MapView. But starting the activity, there is a NullPointerException - I think this is caused by the MapView...
public class MapDetail extends MapActivity {
// JSON Node names
private static final String TAG_NEWNAME = "name";
private static final String TAG_LONG = "long";
private static final String TAG_LAT = "lat";
// Variablen
private MapController mc;
private List<Overlay> mapOverlays;
private Drawable drawable;
private MapItemizedOverlay itemizedoverlay;
private MapView mapView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.offers);
// getting intent data
Bundle extras = getIntent().getExtras();
String url = extras.getString("url");
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
mapOverlays = mapView.getOverlays();
drawable = this.getResources().getDrawable(R.drawable.marker);
itemizedoverlay = new MapItemizedOverlay(drawable, this);
new MyAsyncTask().execute(url);
}
And this is my AsyncTask:
public class MyAsyncTask extends AsyncTask<String, Void, MapItemizedOverlay > {
#Override
protected MapItemizedOverlay doInBackground(String... params) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
JSONArray locations = jParser.getJSONArrayFromUrl(params[0]);
for (int i = 0; i < locations.length(); i++) {
JSONObject c;
try {
c = locations.getJSONObject(i);
// Storing each json item in variable
String firma = c.getString(TAG_NEWNAME);
String longitude = c.getString(TAG_LONG);
String latitude = c.getString(TAG_LAT);
System.out.println("Kriege ich daten"+longitude+"und"+latitude);
double x = Double.parseDouble(latitude);
double y = Double.parseDouble(longitude);
GeoPoint point = new GeoPoint((int)(x * 1E6),(int)(y * 1E6) );
OverlayItem overlayitem = new OverlayItem(point, firma, null);
itemizedoverlay.addOverlay(overlayitem);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(itemizedoverlay.toString());
return itemizedoverlay;
}
#Override
protected void onPostExecute(MapItemizedOverlay result) {
mapOverlays.add(result);
mapView.getOverlays().add(result);
LocationManager myLocationManager;
LocationListener myLocationListener;
myLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
myLocationListener = new MyLocationListener();
myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,myLocationListener);
GeoPoint initGeoPoint = new GeoPoint( (int)(myLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude()*1000000),
(int)(myLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude()*1000000));
mc.animateTo(initGeoPoint);
mc.setZoom(6);
mapView.invalidate();
}
}}
My Log:
01-06 19:49:23.703: E/AndroidRuntime(6064): FATAL EXCEPTION: main
01-06 19:49:23.703: E/AndroidRuntime(6064): java.lang.NullPointerException
01-06 19:49:23.703: E/AndroidRuntime(6064): at de.main.MapDetail$MyAsyncTask.onPostExecute(MapDetail.java:150)
01-06 19:49:23.703: E/AndroidRuntime(6064): at de.main.MapDetail$MyAsyncTask.onPostExecute(MapDetail.java:1)
01-06 19:49:23.703: E/AndroidRuntime(6064): at android.os.AsyncTask.finish(AsyncTask.java:631)
01-06 19:49:23.703: E/AndroidRuntime(6064): at android.os.AsyncTask.access$600(AsyncTask.java:177)
01-06 19:49:23.703: E/AndroidRuntime(6064): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
01-06 19:49:23.703: E/AndroidRuntime(6064): at android.os.Handler.dispatchMessage(Handler.java:99)
01-06 19:49:23.703: E/AndroidRuntime(6064): at android.os.Looper.loop(Looper.java:137)
01-06 19:49:23.703: E/AndroidRuntime(6064): at android.app.ActivityThread.main(ActivityThread.java:4745)
01-06 19:49:23.703: E/AndroidRuntime(6064): at java.lang.reflect.Method.invokeNative(Native Method)
01-06 19:49:23.703: E/AndroidRuntime(6064): at java.lang.reflect.Method.invoke(Method.java:511)
01-06 19:49:23.703: E/AndroidRuntime(6064): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-06 19:49:23.703: E/AndroidRuntime(6064): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-06 19:49:23.703: E/AndroidRuntime(6064): at dalvik.system.NativeStart.main(Native Method)