I am making an android weather app that fetches the data from a third party API and present 5 days of weather data to the user. Whenever I try to run my app it crashes. Any help would be appreciated.
Main Activity-
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private TextView mylocation;
private TextView Entry1, Entry2, Entry3, Entry4, Entry5;
private JSONObject jobject1, jobject2, jarray, tempjobject;
private JSONArray temparray;
private String provider, string, city;
private String[] maximum = new String[5];
private String[] minimum = new String[5];
private String[] conditions = new String[5];
private String[] pictureLink = new String[5];
private Bitmap[] imageCases = new Bitmap[5];
private ImageView iv1, iv2, iv3, iv4, iv5;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
mylocation = (TextView) findViewById(R.id.TextView06);
iv1 = (ImageView) findViewById(R.id.iv1);
iv2 = (ImageView) findViewById(R.id.iv2);
iv3 = (ImageView) findViewById(R.id.iv3);
iv4 = (ImageView) findViewById(R.id.iv4);
iv5 = (ImageView) findViewById(R.id.iv5);
Entry1 = (TextView) findViewById(R.id.day1);
Entry2 = (TextView) findViewById(R.id.day2);
Entry3 = (TextView) findViewById(R.id.day3);
Entry4 = (TextView) findViewById(R.id.day4);
Entry5 = (TextView) findViewById(R.id.day5);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
String result;
try {
result = new WeatherHttpClient().execute("http://api.wunderground.com/api/796da11422ba3dc2/forecast10day/q/"+city+".json").get();
try {
jobject1 = new JSONObject(result);
jarray = jobject1.getJSONObject("forecast");
jobject2 = jarray.getJSONObject("simpleforecast");
temparray = jobject2.getJSONArray("forecastday");
string = result;
for(int i=0;i<2;i++){
tempjobject= temparray.getJSONObject(i);
maximum[i] =tempjobject.getString("high");
minimum[i] = tempjobject.getString("low");
conditions[i] = tempjobject.getString("conditions");
}
JSONObject j1 = new JSONObject(maximum[0]);
JSONObject j2 = new JSONObject(minimum[0]);
JSONObject j3 = new JSONObject(maximum[1]);
JSONObject j4 = new JSONObject(minimum[1]);
JSONObject j5 = new JSONObject(maximum[2]);
JSONObject j6 = new JSONObject(minimum[2]);
JSONObject j7 = new JSONObject(maximum[3]);
JSONObject j8 = new JSONObject(minimum[3]);
JSONObject j9 = new JSONObject(maximum[4]);
JSONObject j10 = new JSONObject(minimum[4]);
Entry1.setText("Maximum" + j1.getString("fahrenheit")+"°F" + "Minimum" + j2.getString("fahrenheit")+"°F "+ conditions[0]);
Entry2.setText("Maximum" + j3.getString("fahrenheit")+"°F" + "Minimum" + j4.getString("fahrenheit")+"°F "+ conditions[1]);
Entry3.setText("Maximum" + j5.getString("fahrenheit")+"°F" + "Minimum" + j6.getString("fahrenheit")+"°F "+ conditions[2]);
Entry4.setText("Maximum" + j7.getString("fahrenheit")+"°F" + "Minimum" + j8.getString("fahrenheit")+"°F "+ conditions[3]);
Entry5.setText("Maximum" + j9.getString("fahrenheit")+"°F" + "Minimum" + j10.getString("fahrenheit")+"°F "+ conditions[4]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0;i<5;i++){
imageCases[i] = new Image().execute(pictureLink[i]).get();
}
iv1.setImageBitmap(imageCases[0]);
iv2.setImageBitmap(imageCases[1]);
iv3.setImageBitmap(imageCases[2]);
iv4.setImageBitmap(imageCases[3]);
iv5.setImageBitmap(imageCases[5]);
Toast.makeText(getBaseContext(), string, Toast.LENGTH_SHORT).show();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
Geocoder geoCoder1 = new Geocoder(getBaseContext(), Locale.getDefault());
try {
String add = "";
List<Address> addresses;
List<Address> fromLocation;
fromLocation = (List<Address>) geoCoder1.getFromLocation(lat,lng, 1);
addresses = fromLocation;
if (addresses.size() > 0)
{
for (int i=0; i<((android.location.Address) addresses.get(0)).getMaxAddressLineIndex();i++)
add += ((android.location.Address) addresses.get(0)).getAddressLine(i) + "\n";
}
mylocation.setText(String.valueOf(add));
Bundle extras = getIntent().getExtras();
if (extras != null) {
city = extras.getString("ZipCode");
}
else{
city = ((android.location.Address) addresses.get(0)).getPostalCode();
}
Toast.makeText(getBaseContext(), city, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.action_settings:
Intent aboutIntent = new Intent(MainActivity.this, Options.class);
startActivity(aboutIntent);
return true;
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
XML-
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
android:orientation="vertical" >
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:text="#string/Lati"
android:textSize="20sp" >
</TextView>
<TextView
android:id="#+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp" >
</TextView>
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:text="#string/Longi"
android:textSize="20sp" >
</TextView>
<TextView
android:id="#+id/TextView04"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp" >
</TextView>
<TextView
android:id="#+id/TextView05"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:text="#string/Locati"
android:textSize="20sp" >
</TextView>
<TextView
android:id="#+id/TextView06"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp" >
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:paddingTop="15dip"
android:text="#string/d1"
android:textSize="20sp" >
</TextView>
<ImageView
android:id="#+id/iv1"
android:layout_width="100dp"
android:layout_height="100dp"
android:contentDescription="Image for climate"
android:maxHeight="100dp"
android:maxWidth="100dp" />
<TextView
android:id="#+id/day1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="xxxxxxx"
android:textSize="20sp" >
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:paddingTop="15dip"
android:text="#string/d2"
android:textSize="20sp" >
</TextView>
<ImageView
android:id="#+id/iv2"
android:layout_width="100dp"
android:layout_height="100dp"
android:contentDescription="Image for climate"
android:maxHeight="100dp"
android:maxWidth="100dp" />
<TextView
android:id="#+id/day2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yyyyyyyyy"
android:textSize="20sp" >
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:paddingTop="15dip"
android:text="#string/d3"
android:textSize="20sp" >
</TextView>
<ImageView
android:id="#+id/iv3"
android:layout_width="100dp"
android:layout_height="100dp"
android:contentDescription="Image for climate"
android:maxHeight="100dp"
android:maxWidth="100dp" />
<TextView
android:id="#+id/day3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yyyyyyyyy"
android:textSize="20sp" >
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:paddingTop="15dip"
android:text="#string/d4"
android:textSize="20sp" >
</TextView>
<ImageView
android:id="#+id/iv4"
android:layout_width="100dp"
android:layout_height="100dp"
android:contentDescription="Image for climate"
android:maxHeight="100dp"
android:maxWidth="100dp" />
<TextView
android:id="#+id/day4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yyyyyyyyy"
android:textSize="20sp" >
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:paddingTop="15dip"
android:text="#string/d5"
android:textSize="20sp" >
</TextView>
<ImageView
android:id="#+id/iv5"
android:layout_width="100dp"
android:layout_height="100dp"
android:contentDescription="Image for climate"
android:maxHeight="100dp"
android:maxWidth="100dp" />
<TextView
android:id="#+id/day5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yyyyyyyyy"
android:textSize="20sp" >
</TextView>
</LinearLayout>
</ScrollView>
LogCat Output
10-17 22:26:33.834: D/ActivityThread(29954): setTargetHeapUtilization:0.25
10-17 22:26:33.834: D/ActivityThread(29954): setTargetHeapIdealFree:8388608
10-17 22:26:33.834: D/ActivityThread(29954): setTargetHeapConcurrentStart:2097152
10-17 22:26:34.014: I/System.out(29954): Provider network has been selected.
10-17 22:26:34.705: W/dalvikvm(29954): threadid=1: thread exiting with uncaught exception (group=0x41e90438)
10-17 22:26:34.705: E/AndroidRuntime(29954): FATAL EXCEPTION: main
10-17 22:26:34.705: E/AndroidRuntime(29954): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.checkweather/com.example.checkweather.MainActivity}: java.lang.NullPointerException
10-17 22:26:34.705: E/AndroidRuntime(29954): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
10-17 22:26:34.705: E/AndroidRuntime(29954): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
10-17 22:26:34.705: E/AndroidRuntime(29954): at android.app.ActivityThread.access$700(ActivityThread.java:143)
10-17 22:26:34.705: E/AndroidRuntime(29954): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
10-17 22:26:34.705: E/AndroidRuntime(29954): at android.os.Handler.dispatchMessage(Handler.java:99)
10-17 22:26:34.705: E/AndroidRuntime(29954): at android.os.Looper.loop(Looper.java:137)
10-17 22:26:34.705: E/AndroidRuntime(29954): at android.app.ActivityThread.main(ActivityThread.java:4950)
10-17 22:26:34.705: E/AndroidRuntime(29954): at java.lang.reflect.Method.invokeNative(Native Method)
10-17 22:26:34.705: E/AndroidRuntime(29954): at java.lang.reflect.Method.invoke(Method.java:511)
10-17 22:26:34.705: E/AndroidRuntime(29954): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
10-17 22:26:34.705: E/AndroidRuntime(29954): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
10-17 22:26:34.705: E/AndroidRuntime(29954): at dalvik.system.NativeStart.main(Native Method)
10-17 22:26:34.705: E/AndroidRuntime(29954): Caused by: java.lang.NullPointerException
10-17 22:26:34.705: E/AndroidRuntime(29954): at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
10-17 22:26:34.705: E/AndroidRuntime(29954): at org.json.JSONTokener.nextValue(JSONTokener.java:94)
10-17 22:26:34.705: E/AndroidRuntime(29954): at org.json.JSONObject.<init>(JSONObject.java:154)
10-17 22:26:34.705: E/AndroidRuntime(29954): at org.json.JSONObject.<init>(JSONObject.java:171)
10-17 22:26:34.705: E/AndroidRuntime(29954): at com.example.checkweather.MainActivity.onCreate(MainActivity.java:103)
10-17 22:26:34.705: E/AndroidRuntime(29954): at android.app.Activity.performCreate(Activity.java:5179)
10-17 22:26:34.705: E/AndroidRuntime(29954): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
10-17 22:26:34.705: E/AndroidRuntime(29954): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
10-17 22:26:34.705: E/AndroidRuntime(29954): ... 11 more
You only create values for maximum[0] and maximum[1], same for minimum.
So when you call
JSONObject j4 = new JSONObject(minimum[2]);
you pass null to the JSONObject.
Related
I developing app with ccavenue payment gateway Integration. I searched in google, I download code. but it works fine in eclipse, then comes in studio it crashes. I tried. but I didn't get output. please any one help me.
public class WebViewActivity extends Activity {
private ProgressDialog dialog;
Intent mainIntent;
String html, encVal;
public static final String TAG = "WebViewStatus : ";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
mainIntent = getIntent();
Log.d(TAG,"main 1 ");
new RenderView().execute();
}
private class RenderView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(WebViewActivity.this);
dialog.setMessage("Please wait...");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
Log.d(TAG,"main 3 ");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add((NameValuePair) new BasicNameValuePair(AvenuesParams.ACCESS_CODE, mainIntent.getStringExtra(AvenuesParams.ACCESS_CODE)));
params.add((NameValuePair) new BasicNameValuePair(AvenuesParams.ORDER_ID, mainIntent.getStringExtra(AvenuesParams.ORDER_ID)));
String vResponse = sh.makeServiceCall(mainIntent.getStringExtra(AvenuesParams.RSA_KEY_URL), ServiceHandler.POST,params);//, params
System.out.println(vResponse);
if(!ServiceUtility.chkNull(vResponse).equals("")
&& ServiceUtility.chkNull(vResponse).toString().indexOf("ERROR")==-1){
StringBuffer vEncVal = new StringBuffer("");
vEncVal.append(ServiceUtility.addToPostParams(AvenuesParams.AMOUNT, mainIntent.getStringExtra(AvenuesParams.AMOUNT)));
vEncVal.append(ServiceUtility.addToPostParams(AvenuesParams.CURRENCY, mainIntent.getStringExtra(AvenuesParams.CURRENCY)));
encVal = RSAUtility.encrypt(vEncVal.substring(0,vEncVal.length()-1), vResponse);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (dialog.isShowing())
dialog.dismiss();
Log.d(TAG,"main 4 ");
#SuppressWarnings("unused")
class MyJavaScriptInterface
{
#JavascriptInterface
public void processHTML(String html)
{
// process the html as needed by the app
String status = null;
if(html.indexOf("Failure")!=-1){
status = "Transaction Declined!";
}else if(html.indexOf("Success")!=-1){
status = "Transaction Successful!";
}else if(html.indexOf("Aborted")!=-1){
status = "Transaction Cancelled!";
}else{
status = "Status Not Known!";
}
Intent intent = new Intent(getApplicationContext(),StatusActivity.class);
intent.putExtra("transStatus", status);
startActivity(intent);
}
}
final WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
webview.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(webview, url);
if(url.indexOf("/ccavResponseHandler.jsp")!=-1){
webview.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
StringBuffer params = new StringBuffer();
params.append(ServiceUtility.addToPostParams(AvenuesParams.ACCESS_CODE,mainIntent.getStringExtra(AvenuesParams.ACCESS_CODE)));
params.append(ServiceUtility.addToPostParams(AvenuesParams.MERCHANT_ID,mainIntent.getStringExtra(AvenuesParams.MERCHANT_ID)));
params.append(ServiceUtility.addToPostParams(AvenuesParams.ORDER_ID,mainIntent.getStringExtra(AvenuesParams.ORDER_ID)));
params.append(ServiceUtility.addToPostParams(AvenuesParams.REDIRECT_URL,mainIntent.getStringExtra(AvenuesParams.REDIRECT_URL)));
params.append(ServiceUtility.addToPostParams(AvenuesParams.CANCEL_URL,mainIntent.getStringExtra(AvenuesParams.CANCEL_URL)));
params.append(ServiceUtility.addToPostParams(AvenuesParams.ENC_VAL,URLEncoder.encode(encVal)));
String vPostParams = params.substring(0,params.length()-1);
try {
webview.postUrl(Constants.TRANS_URL, EncodingUtils.getBytes(vPostParams, "UTF-8"));
} catch (Exception e) {
showToast("Exception occured while opening webview.");
}
}
}
public void showToast(String msg) {
Toast.makeText(this, "Toast: " + msg, Toast.LENGTH_LONG).show();
}
}
The Error is :
--------- beginning of crash
11-16 11:19:56.256 21909-21909/com.reports.com.ccavenueseamless
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.reports.com.ccavenueseamless, PID: 21909
java.lang.IllegalStateException: Could not find method Next(View)
in a parent or ancestor Context for android:onClick attribute defined on
view class android.support.v7.widget.AppCompatButton with id 'nextButton'
at android.support.v7.app.AppCompatViewInflater
$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:325)
at android.support.v7.app.AppCompatViewInflater
$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
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:5254)
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:903)
at com.android.internal.os.ZygoteInit.main
(ZygoteInit.java:698)
The MainActivity is----
public class MainActivity extends AppCompatActivity {
private EditText accessCode, merchantId, currency, amount, orderId, rsaKeyUrl, redirectUrl, cancelUrl;
private Button webview;
private void init() {
accessCode = (EditText) findViewById(R.id.accessCode);
merchantId = (EditText) findViewById(R.id.merchantId);
orderId = (EditText) findViewById(R.id.orderId);
currency = (EditText) findViewById(R.id.currency);
amount = (EditText) findViewById(R.id.amount);
rsaKeyUrl = (EditText) findViewById(R.id.rsaUrl);
redirectUrl = (EditText) findViewById(R.id.redirectUrl);
cancelUrl = (EditText) findViewById(R.id.cancelUrl);
webview = (Button) findViewById(R.id.nextButton);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
setContentView(R.layout.activity_main);
init();
webview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Next();
}
});
//generating order number
Integer randomNum = ServiceUtility.randInt(0, 9999999);
orderId.setText(randomNum.toString());
}
public void Next() {
//Mandatory parameters. Other parameters can be added if required.
String vAccessCode = ServiceUtility.chkNull(accessCode.getText()).toString().trim();
String vMerchantId = ServiceUtility.chkNull(merchantId.getText()).toString().trim();
String vCurrency = ServiceUtility.chkNull(currency.getText()).toString().trim();
String vAmount = ServiceUtility.chkNull(amount.getText()).toString().trim();
if(!vAccessCode.equals("") && !vMerchantId.equals("") && !vCurrency.equals("") && !vAmount.equals("")){
Intent intent = new Intent(this,WebViewActivity.class);intent.putExtra(AvenuesParams.ACCESS_CODE, ServiceUtility.chkNull(accessCode.getText()).toString().trim());
intent.putExtra(AvenuesParams.MERCHANT_ID, ServiceUtility.chkNull(merchantId.getText()).toString().trim());
intent.putExtra(AvenuesParams.ORDER_ID, ServiceUtility.chkNull(orderId.getText()).toString().trim());
intent.putExtra(AvenuesParams.CURRENCY, ServiceUtility.chkNull(currency.getText()).toString().trim());
intent.putExtra(AvenuesParams.AMOUNT, ServiceUtility.chkNull(amount.getText()).toString().trim());
intent.putExtra(AvenuesParams.REDIRECT_URL, ServiceUtility.chkNull(redirectUrl.getText()).toString().trim());
intent.putExtra(AvenuesParams.CANCEL_URL, ServiceUtility.chkNull(cancelUrl.getText()).toString().trim());
intent.putExtra(AvenuesParams.RSA_KEY_URL, ServiceUtility.chkNull(rsaKeyUrl.getText()).toString().trim());
startActivity(intent);
}else{
showToast("All parameters are mandatory.");//09438576355
}
}
public void showToast(String msg) {
Toast.makeText(this, "Toast: " + msg, Toast.LENGTH_LONG).show();
}
}
the activity_main.xml is---
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="left"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/access_code" />
<EditText
android:id="#+id/accessCode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:text="AVPE07CL82AO87EPOA" >
</EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/merchant_id" />
<EditText
android:id="#+id/merchantId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:text="84472"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="Order Id" />
<EditText
android:id="#+id/orderId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/currency" />
<EditText
android:id="#+id/currency"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:text="INR"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/amount" />
<EditText
android:id="#+id/amount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:text="1.00"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/redirect_url" />
<EditText
android:id="#+id/redirectUrl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textUri"
android:text="http://122.182.6.216/merchant/ccavResponseHandler.jsp"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/cancel_url" />
<EditText
android:id="#+id/cancelUrl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textUri"
android:text="http://122.182.6.216/merchant/ccavResponseHandler.jsp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/rsa_url" />
<EditText
android:id="#+id/rsaUrl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textUri"
android:text="http://122.182.6.216/merchant/GetRSA.jsp" />
<Button
android:id="#+id/nextButton"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="48dp"
android:text="#string/pay_button" />
</LinearLayout>
</ScrollView>
I am trying to create a login page. Onclick of the button, I am calling a method to verify the login credentials if already present in the backend django server. I am able to fetch the values of the username and password. The problem that I am currently facing is, if I give the login credentials already present in the backend server, the application works fine. But if I give login credentials which are not in the backend database, the application crashes. Kindly help
Code for Login.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/login_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#drawable/login_background"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<TextView
android:id="#+id/appName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="50dp"
android:text="Teacher Diary"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="By"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
<ImageView
android:id="#+id/logo"
android:layout_width="100sp"
android:layout_height="100sp"
android:layout_gravity="center"
android:contentDescription="#string/home_screen_description"
android:src="#drawable/lo_logo" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
<EditText
android:id="#+id/etUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="25dp"
android:background="#drawable/apptheme_edit_text_holo_light"
android:ems="10"
android:hint="#string/edit_text_username"
android:singleLine="true"
android:textColor="#color/blue" />
<EditText
android:id="#+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#drawable/apptheme_edit_text_holo_light"
android:ems="10"
android:hint="#string/edit_text_password"
android:imeOptions="actionGo"
android:inputType="textPassword"
android:textColor="#color/blue" />
<Button
android:id="#+id/btLogin"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="20dp"
android:background="#drawable/button_background"
android:text="#string/login"
android:textColor="#color/white"
android:textSize="20dp" />
<TextView
android:id="#+id/tvDisplayMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="5dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/white" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="150dp"
android:text="The easiest way to conduct assessments!"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
</LinearLayout>
Code for login.java
public class Login extends Activity implements View.OnClickListener {
private SQLiteDatabase m_database;
private LODatabaseHelper m_databaseHelper;
private Button m_btLogin;
private Animation m_anim;
private EditText m_etUsername, m_etPassword;
private String m_username, m_password, m_role, m_schoolId;
private TextView m_displayMessage;
private String ACCESS_TOKEN = "f59Gh28E6#2h13Y";
private static RequestToServiceCallback mGetRequestToServiceCallback;
public static void setCallback(RequestToServiceCallback callback) {
mGetRequestToServiceCallback = callback;
}
public interface RequestToServiceCallback {
void statusReporting(int id);
void stopService();
}
boolean login = true;
ProgressDialog pDialog;
//List of type books this list will store type Book which is our data model
private static List<LoginModel> logindata;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getActionBar().hide();
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#CC25AAE2")));
int titleId = getResources().getIdentifier("action_bar_title", "id",
"android");
TextView abTitle = (TextView) findViewById(titleId);
abTitle.setTextSize(15.5f);
abTitle.setTextColor(Color.WHITE);
SharedPreferences prefs = this.getSharedPreferences("global_settings",
Context.MODE_PRIVATE);
m_username = prefs.getString("username", "");
m_role = prefs.getString("role", "");
if (m_username.contentEquals("")) {
// do Nothing and continue further the user hasn't logged in yet.
// mSync.adminSync("2");
} else {
Intent intent;
if (m_role.contentEquals("admin"))
intent = new Intent(getApplicationContext(), AdminSync.class);
else
intent = new Intent(getApplicationContext(), Home.class);
finish();
startActivity(intent);
}
setContentView(R.layout.login);
/** Initialise m_database variables */
m_databaseHelper = LODatabaseHelper.getHelper(getApplicationContext());
m_database = m_databaseHelper.getWritableDatabase();
LODatabaseUtility.getInstance().setDatabase(m_database);
m_btLogin = (Button) findViewById(R.id.btLogin);
m_btLogin.setOnClickListener(this);
m_displayMessage = (TextView) findViewById(R.id.tvDisplayMessage);
m_etUsername = (EditText) findViewById(R.id.etUserName);
m_etPassword = (EditText) findViewById(R.id.etPassword);
/* Put the last login credentials into the edit texts */
String lastUsername = prefs.getString("username_last", "");
String lastPassword = prefs.getString("password_last", "");
if (lastUsername.contentEquals("")) {
/* Do Nothing */
} else {
m_etUsername.setText(lastUsername);
m_etPassword.setText(lastPassword);
}
setAnimationValue();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void setAnimationValue() {
m_anim = new AlphaAnimation(0.0f, 1.0f);
m_anim.setDuration(100); // You can manage the time of the blink with
// this parameter
m_anim.setStartOffset(20);
m_anim.setRepeatMode(Animation.REVERSE);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btLogin:
/* check the username and password */
if (m_etUsername.getText().length() == 0) {
m_displayMessage.setText("Enter User Name");
if (m_etPassword.getText().length() == 0) {
m_displayMessage.setText("Enter User Name and Password");
}
return;
}
if (m_etPassword.getText().length() == 0) {
m_displayMessage.setText("Enter User Password");
return;
}
m_username = m_etUsername.getText().toString();
m_password = m_etPassword.getText().toString();
//Calling the method that will fetch data
getLoginDetails(m_username, m_password, ACCESS_TOKEN);
break;
}
}
private void getLoginDetails(final String m_username, final String m_password, final String ACCESS_TOKEN) {
//While the app fetched data we are displaying a progress dialog
final ProgressDialog loading = ProgressDialog.show(Login.this, "Please wait... ", "Login in progress", false, false);
Log.e("m_username:", m_username);
Log.e("m_password:", m_password);
App.getRestClient()
.getLoginService()
.getLoginData(m_username, m_password, ACCESS_TOKEN,
new Callback<List<LoginAPIModel>>() {
#Override
public void failure(RetrofitError arg0) {
if(arg0.getKind() == RetrofitError.Kind.CONVERSION || arg0.getKind() == RetrofitError.Kind.NETWORK){
Log.e("Exception","");
}
/*Log.e( "TAG" + "ERROR", "Logindetails table: start = "
+ "" + retrofitError.getMessage());
if (retrofitError.getKind() == RetrofitError.Kind.CONVERSION
|| retrofitError.getKind() == RetrofitError.Kind.NETWORK) {
getLoginDetails(m_username, m_password, ACCESS_TOKEN);
} else {
mGetRequestToServiceCallback.stopService();
}*/
}
#Override
public void success(List<LoginAPIModel> arg0,
Response response) {
//Dismissing the loading progressbar
loading.dismiss();
Log.e("schoolid", arg0.get(0).getSchoolId());
Log.e("username:", arg0.get(0).getUsername());
Log.e("role:", arg0.get(0).getRole());
SharedPreferences prefs = getSharedPreferences(
"global_settings",
Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString("school_id",
arg0.get(0).getSchoolId());
editor.putString("username",
arg0.get(0).getUsername());
editor.putString("password",
arg0.get(0).getPassword());
editor.putString("role",
arg0.get(0).getRole());
editor.putString("email",
arg0.get(0).getEmail());
editor.putString("user",
arg0.get(0).getUser());
editor.putString("otp",
arg0.get(0).getOtp());
editor.putString("telephone_no",
arg0.get(0).getTelephoneNo());
editor.commit();
String temp1 = arg0.get(0).getRole();
Log.e("Temp1 values:", temp1);
String tempUsername=arg0.get(0).getUsername();
Log.e("username values:", tempUsername);
String tempPassword=arg0.get(0).getPassword();
Log.e("password values:", tempPassword);
Intent intent = null;
if (temp1.contentEquals("admin")) {
intent = new Intent(Login.this, AdminSync.class);
intent.putExtra("mSchoolId", m_schoolId);
finish();
startActivity(intent);
new loginUser().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}else if (temp1.contentEquals("teacher")) {
loading.dismiss();
m_displayMessage.setText("Invalid username password !");
} else {
//intent = new Intent(Login.this, Home.class);
}
//
}
});
}
My Logcat:
05-03 13:02:17.156 13719-13719/? E/m_username:: GChjvbj
05-03 13:02:17.156 13719-13719/? E/m_password:: chknmnvv
05-03 13:02:17.293 7409-7419/? E/Parcel: Reading a NULL string not supported here.
05-03 13:02:17.555 13719-13719/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.learningoutcomes, PID: 13719
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.learningoutcomes.Login$1.success(Login.java:206)
at com.learningoutcomes.Login$1.success(Login.java:184)
at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
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:5341)
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:825)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
at dalvik.system.NativeStart.main(Native Method)
I am experiencing issues relating my textview to my seekbar, and have received the below message as such. I am under the premises that it was due for the following reasons: 1) Trying to store the seekbar values information recorded by the user into parse to be able to retrieve it later. Storing the EditText such as name, age, headline and radiobox such as gender works fine, but its when I include the seek that the application fails to run.
I have tried doing a project clean, and rewording ID with the "right prefix" such as sb for seekbar, and tv for textview.
Below is the logcat message:
update logcat posted below
Below is the activity code
public class ProfileCreation extends Activity {
private static final int RESULT_LOAD_IMAGE = 1;
FrameLayout layout;
Button save;
protected EditText mName;
protected EditText mAge;
protected EditText mHeadline;
protected ImageView mprofilePicture;
RadioButton male, female;
String gender;
RadioButton lmale, lfemale;
String lgender;
protected SeekBar seekBarMinimum;
protected SeekBar seekBarMaximum;
protected SeekBar seekBarDistance;
protected Button mConfirm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_creation);
RelativeLayout v = (RelativeLayout) findViewById(R.id.main);
v.requestFocus();
Parse.initialize(this, "ID", "ID");
mName = (EditText)findViewById(R.id.etxtname);
mAge = (EditText)findViewById(R.id.etxtage);
mHeadline = (EditText)findViewById(R.id.etxtheadline);
mprofilePicture = (ImageView)findViewById(R.id.profilePicturePreview);
male = (RadioButton)findViewById(R.id.rimale);
female = (RadioButton)findViewById(R.id.rifemale);
lmale = (RadioButton)findViewById(R.id.rlmale);
lfemale = (RadioButton)findViewById(R.id.rlfemale);
seekBarMinimum = (SeekBar) findViewById(R.id.sbseekBarMinimumAge);
seekBarMaximum = (SeekBar) findViewById(R.id.sbseekBarMaximumAge);
seekBarDistance = (SeekBar) findViewById(R.id.tvseekBarDistanceValue);
mConfirm = (Button)findViewById(R.id.btnConfirm);
mConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = mName.getText().toString();
String age = mAge.getText().toString();
String headline = mHeadline.getText().toString();
age = age.trim();
name = name.trim();
headline = headline.trim();
if (age.isEmpty() || name.isEmpty() || headline.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(R.string.signup_error_message)
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else {
// create the new user!
setProgressBarIndeterminateVisibility(true);
ParseUser currentUser = ParseUser.getCurrentUser();
seekBarMaximum.getProgress();
seekBarMinimum.getProgress();
seekBarDistance.getProgress();
if(male.isChecked())
gender = "Male";
else
gender = "Female";
if(lmale.isChecked())
lgender = "Male";
else
lgender = "Female";
currentUser.put("Name", name);
currentUser.put("Age", age);
currentUser.put("Headline", headline);
currentUser.put("Gender", gender);
currentUser.put("Looking_Gender", lgender);
currentUser.put("Minimum_Age", seekBarMinimum);
currentUser.put("Maximum_Age", seekBarMaximum);
currentUser.put("Maximum_Distance_Age", seekBarDistance);
currentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// Success!
Intent intent = new Intent(ProfileCreation.this, MoodActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
SeekBar seekBar = (SeekBar) findViewById(R.id.sbseekBarDistance);
final TextView seekBarValue = (TextView) findViewById(R.id.tvseekBarDistanceValue);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
seekBarValue.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
Button mcancel = (Button)findViewById(R.id.btnBack);
mcancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProfileCreation.this.startActivity(new Intent(ProfileCreation.this, LoginActivity.class));
}
});
SeekBar seekBarMinimum = (SeekBar) findViewById(R.id.sbseekBarMinimumAge);
final TextView txtMinimum = (TextView) findViewById(R.id.tvMinAge);
seekBarMinimum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMinimum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
SeekBar seekBarMaximum = (SeekBar) findViewById(R.id.sbseekBarMaximumAge);
final TextView txtMaximum = (TextView) findViewById(R.id.tvMaxAge);
seekBarMaximum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMaximum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
private byte[] readInFile(String path) throws IOException {
// TODO Auto-generated method stub
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(
file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
}
Below is the layout xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollProfile"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/dark_texture_blue" >
<RelativeLayout
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="797dp"
android:gravity="center"
android:orientation="vertical" >
<ImageView
android:id="#+id/profilePicturePreview"
android:layout_width="132dp"
android:layout_height="120dp"
android:layout_below="#+id/textView5"
android:layout_centerHorizontal="true"
android:layout_marginTop="7dp"
android:layout_marginBottom="9dp"
android:padding="3dp"
android:scaleType="centerCrop"
android:cropToPadding="true"
android:background="#drawable/border_image"
android:alpha="1" />
<Button
android:id="#+id/bRemove"
android:layout_width="120dp"
android:layout_height="60dp"
android:layout_above="#+id/etxtage"
android:layout_alignLeft="#+id/etxtname"
android:alpha="0.8"
android:background="#330099"
android:text="Upload from Facebook"
android:textColor="#ffffff"
android:textSize="17sp"
android:textStyle="bold" />
<Button
android:id="#+id/btnPictureSelect"
android:layout_width="118dp"
android:layout_height="60dp"
android:layout_alignRight="#+id/etxtname"
android:layout_below="#+id/profilePicturePreview"
android:layout_marginRight="8dp"
android:alpha="0.8"
android:background="#000000"
android:onClick="pickPhoto"
android:text="Select photo from gallery"
android:textColor="#ffffff"
android:textSize="17sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView4"
android:layout_centerHorizontal="true"
android:layout_marginTop="9dp"
android:text="Preferred Name"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="39dp"
android:gravity="center"
android:text="Profile Creation"
android:textColor="#ffffff"
android:textSize="28sp"
android:textStyle="bold"
android:typeface="serif" />
<EditText
android:id="#+id/etxtname"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView6"
android:layout_centerHorizontal="true"
android:ems="10"
android:enabled="true"
android:hint="Please type your name here"
android:inputType="textPersonName"
android:textColor="#ffffff"
android:textSize="18sp" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/etxtname"
android:layout_centerHorizontal="true"
android:layout_marginTop="8dp"
android:text="Upload your Profile Picture"
android:textColor="#f2f2f2"
android:textSize="18sp"
android:textStyle="bold"
android:typeface="sans" />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_alignLeft="#+id/etxtheadline"
android:layout_height="wrap_content"
android:layout_below="#+id/texperience"
android:layout_toLeftOf="#+id/textView3" >
<RadioButton
android:id="#+id/rimale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Male"
android:textColor="#f2f2f2" />
<RadioButton
android:id="#+id/rifemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:textColor="#f2f2f2" />
</RadioGroup>
<SeekBar
android:id="#+id/sbseekBarDistance"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView12"
android:layout_centerHorizontal="true"
android:layout_marginTop="11dp"
android:progress="50" />
<RadioGroup
android:id="#+id/radioGroup3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView4"
android:layout_alignTop="#+id/radioGroup2"
android:layout_marginTop="10dp" >
</RadioGroup>
<RadioGroup
android:id="#+id/radioGroup2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/etxtheadline"
android:layout_below="#+id/textView2" >
<RadioButton
android:id="#+id/rlmale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Male"
android:textColor="#f2f2f2" />
<RadioButton
android:id="#+id/rlfemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:textColor="#f2f2f2" />
</RadioGroup>
<SeekBar
android:id="#+id/sbseekBarMinimumAge"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView7"
android:layout_centerHorizontal="true"
android:layout_marginTop="11dp"
android:progress="25" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/etxtage"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Minimum Age Looking For"
android:textColor="#f2f2f2"
android:textSize="16sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/tvseekBarDistanceValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/tvMinAge"
android:layout_below="#+id/sbseekBarDistance"
android:text="50"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f2f2f2"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioGroup1"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp"
android:text="Search Distance "
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/tvMinAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/sbseekBarMinimumAge"
android:layout_centerHorizontal="true"
android:text="25"
android:textColor="#f2f2f2"
android:textSize="18sp" />
<TextView
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvMaxAge"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:text="Headline"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/textView14"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvMinAge"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:text="Maximum Age Looking For"
android:textColor="#f2f2f2"
android:textSize="16sp"
android:textStyle="bold"
android:typeface="serif" />
<SeekBar
android:id="#+id/sbseekBarMaximumAge"
android:layout_width="221dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView14"
android:layout_centerHorizontal="true"
android:layout_marginTop="11dp"
android:progress="50" />
<TextView
android:id="#+id/tvMaxAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/sbseekBarMaximumAge"
android:layout_centerHorizontal="true"
android:text="50"
android:textColor="#f2f2f2"
android:textSize="18sp" />
<TextView
android:id="#+id/conditions"
android:layout_width="280dp"
android:layout_height="130dp"
android:layout_below="#+id/btnConfirm"
android:layout_centerHorizontal="true"
android:layout_marginBottom="7dp"
android:layout_marginTop="7dp"
android:alpha="0.6"
android:gravity="center"
android:text="#string/disclaimer"
android:textColor="#99CCFF"
android:textSize="12sp" />
<Button
android:id="#+id/btnConfirm"
android:layout_width="120dp"
android:layout_height="60dp"
android:layout_below="#+id/tvseekBarDistanceValue"
android:layout_marginBottom="7dp"
android:layout_marginTop="14dp"
android:layout_toRightOf="#+id/tvseekBarDistanceValue"
android:alpha="0.8"
android:background="#151B54"
android:text="Confirm"
android:textColor="#ffffff"
android:textSize="17sp"
android:textStyle="bold" />
<EditText
android:id="#+id/etxtheadline"
android:layout_width="270dp"
android:layout_height="70dp"
android:layout_below="#+id/textView8"
android:layout_centerHorizontal="true"
android:hint="A quick description of yourself"
android:singleLine="true"
android:textAlignment="center"
android:textColor="#f2f2f2"
android:textSize="18dp" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/etxtage"
android:layout_width="230dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView4"
android:layout_below="#+id/btnPictureSelect"
android:layout_marginTop="48dp"
android:ems="10"
android:hint="Please type your age here"
android:inputType="number"
android:maxLength="2"
android:textAlignment="center"
android:textColor="#f2f2f2"
android:textSize="18dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/radioGroup1"
android:layout_alignRight="#+id/btnConfirm"
android:text="Looking for"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/texperience"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/radioGroup1"
android:layout_below="#+id/etxtheadline"
android:layout_marginTop="39dp"
android:text="I am a"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold" />
/>
</RelativeLayout>
</ScrollView>
Any help would be greatly appreciated. All the best.
Update
Upon resolving the previous, another error related was triggered. I have tried resolving it, but is still experiencing issues. Below is the logcat
08-13 14:56:24.366: E/AndroidRuntime(1306): FATAL EXCEPTION: main
08-13 15:49:13.758: E/AndroidRuntime(1365): FATAL EXCEPTION: main
08-13 15:49:13.758: E/AndroidRuntime(1365): Process: com.dooba.beta, PID: 1365
08-13 15:49:13.758: E/AndroidRuntime(1365): java.lang.IllegalArgumentException: invalid type for value: class android.widget.SeekBar
08-13 15:49:13.758: E/AndroidRuntime(1365): at com.parse.ParseObject.put(ParseObject.java:2152)
08-13 15:49:13.758: E/AndroidRuntime(1365): at com.parse.ParseUser.put(ParseUser.java:315)
08-13 15:49:13.758: E/AndroidRuntime(1365): at com.dooba.beta.ProfileCreation$1.onClick(ProfileCreation.java:136)
08-13 15:49:13.758: E/AndroidRuntime(1365): at android.view.View.performClick(View.java:4438)
08-13 15:49:13.758: E/AndroidRuntime(1365): at android.view.View$PerformClick.run(View.java:18422)
08-13 15:49:13.758: E/AndroidRuntime(1365): at android.os.Handler.handleCallback(Handler.java:733)
08-13 15:49:13.758: E/AndroidRuntime(1365): at android.os.Handler.dispatchMessage(Handler.java:95)
08-13 15:49:13.758: E/AndroidRuntime(1365): at android.os.Looper.loop(Looper.java:136)
08-13 15:49:13.758: E/AndroidRuntime(1365): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-13 15:49:13.758: E/AndroidRuntime(1365): at java.lang.reflect.Method.invokeNative(Native Method)
08-13 15:49:13.758: E/AndroidRuntime(1365): at java.lang.reflect.Method.invoke(Method.java:515)
08-13 15:49:13.758: E/AndroidRuntime(1365): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-13 15:49:13.758: E/AndroidRuntime(1365): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-13 15:49:13.758: E/AndroidRuntime(1365): at dalvik.system.NativeStart.main(Native Method)
Your XML has defined tvseekBarDistanceValue as a TextView, not a SeekBar. Since you're trying to change a TextView to a SeekBar (which is impossible), you are getting this error.
Based on your XML, I think you want to replace
seekBarDistance = (SeekBar) findViewById(R.id.tvseekBarDistanceValue);
with
seekBarDistance = (SeekBar) findViewById(R.id.sbseekBarDistance);
I have a code to check PNR number. Because of internet issues, i thought to give users to check PNR by SMS. So I added 2 Radio Buttons, one for internet and one for SMS. But the problem is now when I click the PNR Button, it gives nullPointer Exception.
Here is my Main Activity.java
public class MainActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
private EditText pnrNumber;
private TextView errMsg;
private Button getPnr;
private Button pnrClear;
Button Yes, No;
RadioButton checkbyinternet, checkbysms;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
errMsg = (TextView) findViewById(R.id.errMsg);
pnrNumber = (EditText) findViewById(R.id.pnrNumber_p01);
getPnr = (Button) findViewById(R.id.checkPNRButton);
pnrClear = (Button) findViewById(R.id.pnrClear);
getPnr.setOnClickListener(this);
pnrClear.setOnClickListener(this);
}
public void onClick(View src) {
// Perform action on click
if (src.getId() == R.id.checkPNRButton)
{
if (checkbyinternet.isChecked())
{
int pnr2 = pnrNumber.getEditableText().length();
if (pnr2 != 10)
{
errMsg.setText("Length of PNR is Invalid.");
}
else
{
String pnr = pnrNumber.getEditableText().toString();
Bundle b = new Bundle();
b.putString("pnr", pnr);
System.out.println("Connectivity : "
+ this.isNetworkAvailable());
PNRStatus pnrStatus = null;
// Connect to the Server and Get the PNR status
try
{
String captcha = "37819";
String pnr1 = pnrNumber.getText().toString();
String reqStr = "lccp_pnrno1=" + pnr1
+ "&lccp_cap_val=" + captcha
+ "&lccp_capinp_val=" + captcha
+ "&submitpnr=Get+Status";
PNRStatusCheck check = new PNRStatusCheck();
StringBuffer data = check
.getPNRResponse(reqStr,
"http://www.indianrail.gov.in/cgi_bin/inet_pnstat_cgi_28688.cgi");
// String pnr1 = pnr; //"1154177041";
// String reqStr = "lccp_pnrno1=" + pnr1 +
// "&submitpnr=Get+Status";
// PNRStatusCheck check = new PNRStatusCheck();
// StringBuffer data = check.getPNRResponse(reqStr,
// "http://www.indianrail.gov.in/cgi_bin/inet_pnrstat_cgi.cgi");
if (data != null)
{
pnrStatus = check.parseHtml(data);
b.putSerializable("pnrStatus", pnrStatus);
}
else
{
// error
}
}
catch (Exception e)
{
e.printStackTrace();
}
Intent to = null;
if (pnrStatus != null)
{
to = new Intent(this, PNRStatusActivity.class);
to.putExtras(b);
startActivity(to);
}
else
{
errMsg.setText("Error prcessing PNR. Please try again.");
}
}
}
else if (checkbysms.isChecked())
{
// Toast.makeText(this, "SMS", Toast.LENGTH_SHORT).show();
int pnr2 = pnrNumber.getEditableText().length();
if (pnr2 != 10)
{
errMsg.setText("Length of PNR is Invalid.");
}
else
{
openSMSWarningDialog(src);
}
}
}
else if (src.getId() == R.id.pnrClear)
{
errMsg.setText("");
pnrNumber.setText("");
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null, otherwise check
// if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
public void openSMSWarningDialog(View view) {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.smsdialog);
dialog.setTitle("Are you sure to use SMS.?");
Yes = (Button) dialog.findViewById(R.id.yes);
No = (Button) dialog.findViewById(R.id.no);
Yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String PnrNum = pnrNumber.getText().toString();
String messageToSend = ("PNR " + PnrNum);
String number = "139";
SmsManager.getDefault().sendTextMessage(number, null,
messageToSend, null, null);
dialog.dismiss();
Toast.makeText(
getBaseContext(),
"Please check your inbox in sometime for your PNR Status",
Toast.LENGTH_LONG).show();
}
});
No.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog.show();
}
}
And here is my layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:background="#drawable/background"
android:gravity="center_horizontal"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="17dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:text="#string/title"
android:gravity="center_horizontal"
android:textColor="#android:color/black"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/errMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="17dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:textColor="#android:color/black"
android:text="10 Digits Mandatory" />
<EditText
android:id="#+id/pnrNumber_p01"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_gravity="center_horizontal"
android:paddingLeft="10dp"
android:background="#drawable/edittextellipsedbackground"
android:layout_marginTop="17dp"
android:layout_marginBottom="7dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:hint="#string/pnrTextView" >
<requestFocus />
</EditText>
<Button
android:id="#+id/checkPNRButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#drawable/bluebutton"
android:layout_marginTop="17dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:padding="10dp"
android:shadowColor="#000000"
android:shadowRadius="5.9"
android:text="#string/checkPNRButton"
android:textColor="#ffffff"
android:textSize="20sp" />
<Button
android:id="#+id/pnrClear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/bluebutton"
android:layout_marginTop="7dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:padding="10dp"
android:shadowColor="#000000"
android:shadowRadius="5.9"
android:text="Clear"
android:textColor="#ffffff"
android:textSize="20sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:layout_marginTop="20dp"
android:background="#drawable/roundlayoutborder"
android:gravity="center"
android:paddingBottom="5dp" >
<RadioGroup
android:id="#+id/checkvia"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:orientation="vertical" >
<RadioButton
android:id="#+id/internet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:textColor="#android:color/black"
android:text="#string/CheckByInternet"
android:textAppearance="?android:attr/textAppearanceSmall" />
<RadioButton
android:id="#+id/sms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:text="#string/CheckBySMS"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RadioGroup>
</LinearLayout>
</LinearLayout>
SMS Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#9bafb0"
android:orientation="vertical" >
<TextView
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:textColor="#ff0000"
android:ems="27"
android:text="#string/CheckThroughSMSWarning" >
</TextView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:layout_marginTop="15dp"
android:layout_marginBottom="15dp" >
<Button
android:id="#+id/yes"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="2dp"
android:textColor="#android:color/white"
android:layout_weight="1"
android:background="#drawable/bluebutton"
android:text="Yes" />
<Button
android:id="#+id/no"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="5dp"
android:textColor="#android:color/white"
android:layout_weight="1"
android:background="#drawable/bluebutton"
android:text="No" />
</LinearLayout>
</LinearLayout>
Here is my LOG:
02-06 13:54:22.810: E/AndroidRuntime(858): FATAL EXCEPTION: main
02-06 13:54:22.810: E/AndroidRuntime(858): java.lang.NullPointerException
02-06 13:54:22.810: E/AndroidRuntime(858): at akshat.jaiswal.indianrailways.MainActivity.onClick(MainActivity.java:50)
02-06 13:54:22.810: E/AndroidRuntime(858): at android.view.View.performClick(View.java:4084)
02-06 13:54:22.810: E/AndroidRuntime(858): at android.view.View$PerformClick.run(View.java:16966)
02-06 13:54:22.810: E/AndroidRuntime(858): at android.os.Handler.handleCallback(Handler.java:615)
02-06 13:54:22.810: E/AndroidRuntime(858): at android.os.Handler.dispatchMessage(Handler.java:92)
02-06 13:54:22.810: E/AndroidRuntime(858): at android.os.Looper.loop(Looper.java:137)
02-06 13:54:22.810: E/AndroidRuntime(858): at android.app.ActivityThread.main(ActivityThread.java:4745)
02-06 13:54:22.810: E/AndroidRuntime(858): at java.lang.reflect.Method.invokeNative(Native Method)
02-06 13:54:22.810: E/AndroidRuntime(858): at java.lang.reflect.Method.invoke(Method.java:511)
02-06 13:54:22.810: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-06 13:54:22.810: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-06 13:54:22.810: E/AndroidRuntime(858): at dalvik.system.NativeStart.main(Native Method)
Please help, I am not able to get any solution for this.
Your checkbyinternet and checkbysms buttons are uninitialized and that is why you're getting the NullPointerException when if (checkbyinternet.isChecked()) is executed in the onClick() method.
if (src.getId() == R.id.checkPNRButton) // true if you pressed the getPnr button
{
if (checkbyinternet.isChecked()) // checkbyinternet is uninitialized yet, so it'll throw a NPE
You need to initialize them as well in the onCreate() method.
checkbyinternet = (RadioButton) findViewById(R.id.internet);
checkbysms = (RadioButton) findViewById(R.id.sms);
This is my main activity's source, I have tried to start it in Android 2.3.7 and Android 4.1 and above, it runs successfuly in Android 2.3.7 but crashes in Android 4.1.
public class CalculatorActivity extends Activity implements LocationListener
{
protected static final String TAG = "123";
public static Handler h;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
final SharedPreferences unitpreference = PreferenceManager.getDefaultSharedPreferences(this);
final String unitstring = unitpreference.getString("unit_type", "");
final int unit = Integer.parseInt(unitstring);
changecityname();
changeusername();
if (unit==1)
{
TextView kms1 = (TextView) findViewById(R.id.textView7);
kms1.setText("kms.");
TextView kml = (TextView) findViewById(R.id.textView8);
kml.setText("km/lt");
TextView kms2 = (TextView) findViewById(R.id.textView9);
kms2.setText("kms.");
TextView rs = (TextView) findViewById(R.id.textView10);
rs.setText("Rs.");
}
else
{
TextView kms1 = (TextView) findViewById(R.id.textView7);
kms1.setText("mi.");
TextView kml = (TextView) findViewById(R.id.textView8);
kml.setText("mi/ga");
TextView kms2 = (TextView) findViewById(R.id.textView9);
kms2.setText("mi.");
TextView rs = (TextView) findViewById(R.id.textView10);
rs.setText("$");
}
clickbutton();
};
private void changeusername()
{
final SharedPreferences currentusername = getSharedPreferences("PREFS_NAME",0);
final String loggedInUser = currentusername.getString("username", "");
TextView loggedInUsername = (TextView) findViewById(R.id.textView11);
loggedInUsername.setText("Logged in as "+loggedInUser);
}
private void changecityname()
{
final SharedPreferences citypreference = PreferenceManager.getDefaultSharedPreferences(this);
final String citystring = citypreference.getString("example_list", "");
int city = Integer.parseInt(citystring);
TextView cityname = (TextView) findViewById(R.id.textView12);
if (city==1)
{
cityname.setText("Panchkula ");
}
else if (city==2)
{
cityname.setText("Chandigarh ");
}
else if (city==3)
{
cityname.setText("Mohali ");
}
else
{
cityname.setText("Your City ");
}
}
#Override
public void onResume() {
super.onResume();
final SharedPreferences unitpreference = PreferenceManager.getDefaultSharedPreferences(this);
final String unitstring = unitpreference.getString("unit_type", "");
final int unit = Integer.parseInt(unitstring);
final SharedPreferences citypreference = PreferenceManager.getDefaultSharedPreferences(this);
final String citystring = citypreference.getString("example_list", "");
int city = Integer.parseInt(citystring);
final SharedPreferences fuelpreference = PreferenceManager.getDefaultSharedPreferences(this);
final String fuelstring = fuelpreference.getString("fuel_type", "");
int fuel = Integer.parseInt(fuelstring);
if (unit==1)
{
TextView kms1 = (TextView) findViewById(R.id.textView7);
kms1.setText("kms.");
TextView kml = (TextView) findViewById(R.id.textView8);
kml.setText("km/lt");
TextView kms2 = (TextView) findViewById(R.id.textView9);
kms2.setText("kms.");
TextView rs = (TextView) findViewById(R.id.textView10);
rs.setText("Rs.");
}
else
{
TextView kms1 = (TextView) findViewById(R.id.textView7);
kms1.setText("mi.");
TextView kml = (TextView) findViewById(R.id.textView8);
kml.setText("mi/ga");
TextView kms2 = (TextView) findViewById(R.id.textView9);
kms2.setText("mi.");
TextView rs = (TextView) findViewById(R.id.textView10);
rs.setText("$");
}
clickbutton();
changecityname();
changeusername();
h = new Handler()
{
public void handleMessage(Message msg)
{
super.handleMessage(msg);
switch (msg.what)
{
case 0:
finish();
break;
}
}
};
}
#Override
protected void onPause() {
super.onPause();
final SharedPreferences unitpreference = getSharedPreferences("unit_type",MODE_PRIVATE);
SharedPreferences.Editor uniteditor = unitpreference.edit();
uniteditor.commit();
}
public void clickbutton()
{
final SharedPreferences unitpreference = PreferenceManager.getDefaultSharedPreferences(this);
final String unitstring = unitpreference.getString("unit_type", "");
final int unit = Integer.parseInt(unitstring);
final SharedPreferences citypreference = PreferenceManager.getDefaultSharedPreferences(this);
final String citystring = citypreference.getString("example_list", "");
int city = Integer.parseInt(citystring);
final SharedPreferences fuelpreference = PreferenceManager.getDefaultSharedPreferences(this);
final String fuelstring = fuelpreference.getString("fuel_type", "");
int fuel = Integer.parseInt(fuelstring);
SharedPreferences petrolPricesetting = getSharedPreferences("PREFS_NAME", 0);
SharedPreferences dieselPricesetting = getSharedPreferences("PREFS_NAME", 0);
float citypetrolprice =petrolPricesetting.getFloat("petrolprice", 70.0f);
float citydieselprice =dieselPricesetting.getFloat("dieselprice", 60.0f);
final double price;
if (fuel==1)
{
if (city==1)
{
price=69.19;
}
else if (city==2)
{
price=69.59;
}
else if (city==3)
{
price=76.18;
}
else
{
price=citypetrolprice;
}
}
else
{
if (city==1)
{
price=47.24;
}
else if (city==2)
{
price=49.42;
}
else if (city==3)
{
price=47.56;
}
else
{
price=citydieselprice;
}
}
Button livecost = (Button) findViewById(R.id.button3);
livecost.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
Intent startlive = new Intent(CalculatorActivity.this,Live.class);
CalculatorActivity.this.startActivity(startlive);
}
});
Button calculatemileage = (Button) findViewById(R.id.button1);
calculatemileage.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
EditText distancetravelled= (EditText) findViewById(R.id.editText1);
EditText refillingcost= (EditText) findViewById(R.id.editText2);
if (distancetravelled.length()==0 || refillingcost.length()==0 )
{
Log.v(TAG, "Setting has been changed!");
Toast.makeText(getApplicationContext(), "Please fill both the distance travelled and the cost!", Toast.LENGTH_SHORT).show();
}
else
{
String stringdistancetravelled=distancetravelled.getText().toString();
String stringrefillingcost=refillingcost.getText().toString();
Log.v(TAG, "Setting has been changed!");
float floatdistancetravelled =Float.valueOf(stringdistancetravelled);
float floatrefillingcost =Float.valueOf(stringrefillingcost);
double mileageanswer = (floatdistancetravelled/floatrefillingcost)*price;
final float floatmileageanswer = (float) mileageanswer;
double mileageanswerroundoff = Math.round(floatmileageanswer*100.0)/100.0;
double mileageanswerimperial = mileageanswer*0.621371192;
final float floatmileageanswerimperial = (float) mileageanswerimperial;
double mileageanswerimperialroundoff = Math.round(floatmileageanswerimperial*100.0)/100.0;
if (unit==1)
{
Toast.makeText(getApplicationContext(), mileageanswerroundoff+" km/l", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), mileageanswerimperialroundoff+" mi/ga", Toast.LENGTH_LONG).show();
}
}
}});
Button calculatecost= (Button) findViewById(R.id.button2);
calculatecost.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
EditText mileage= (EditText) findViewById(R.id.editText3);
EditText distance= (EditText) findViewById(R.id.editText4);
if (mileage.getText().length()==0 || distance.getText().length()==0 )
{
Toast.makeText(getApplicationContext(), "Please fill both the distance to travel and the mileage!", Toast.LENGTH_SHORT).show();
}
else
{
String stringmileage=mileage.getText().toString();
String stringdistance=distance.getText().toString();
float floatmileage =Float.valueOf(stringmileage);
float floatdistance =Float.valueOf(stringdistance);
double costanswer = (floatdistance)*(price/floatmileage);
final float floatcostanswer = (float) costanswer;
double costanswerroundoff = Math.round(floatcostanswer*100.0)/100.0;
double costanswerimperial = costanswer*0.621371192*0.01661;
final float floatcostanswerimperial = (float) costanswerimperial;
double costanswerimperialroundoff = Math.round(floatcostanswerimperial*100.0)/100.0;
if (unit==1)
{
Toast.makeText(getApplicationContext(), "Rs."+costanswerroundoff, Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "$"+costanswerimperialroundoff, Toast.LENGTH_LONG).show();
}
}
}});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_calculator, menu);
return true;
}
public boolean onMenuItemSelected(int featureId, MenuItem item)
{
if (item.getItemId()==R.id.menu_settings)
{
Intent startsettings = new Intent(CalculatorActivity.this,SettingsActivity.class);
CalculatorActivity.this.startActivity(startsettings);
}
else
{
Intent startlogin = new Intent(CalculatorActivity.this,Login.class);
CalculatorActivity.this.startActivity(startlogin);
CheckBox keeplog = (CheckBox) findViewById(R.id.checkBox1);
boolean isChecked = false;
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("isChecked", isChecked);
editor.commit();
finish();
}
return true;
}
#Override
public void onLocationChanged(Location location)
{
}
#Override
public void onProviderDisabled(String arg0)
{
}
#Override
public void onProviderEnabled(String arg0)
{
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2)
{
}
}
Layout File:
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginLeft="24dp"
android:layout_marginTop="32dp"
android:text="Distance: "
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/white" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/textView2"
android:layout_marginTop="39dp"
android:text="Cost:"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/white" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView3"
android:layout_alignBottom="#+id/textView3"
android:layout_alignLeft="#+id/editText1"
android:ems="10"
android:inputType="numberDecimal"
android:width="50dp" />
<TextView
android:id="#+id/textView10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editText2"
android:layout_toLeftOf="#+id/editText2"
android:text="Rs."
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/white" />
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView6"
android:layout_toRightOf="#+id/editText4"
android:text="kms."
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/white" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textView1"
android:layout_alignTop="#+id/textView2"
android:ems="10"
android:height="10dp"
android:inputType="numberDecimal"
android:maxHeight="10dp"
android:width="50dp" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/editText1"
android:layout_alignBottom="#+id/editText1"
android:layout_toRightOf="#+id/editText1"
android:text="kms."
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/white" />
<EditText
android:id="#+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView5"
android:layout_alignBottom="#+id/textView5"
android:layout_toRightOf="#+id/textView10"
android:ems="10"
android:inputType="numberDecimal"
android:width="50dp" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/button1"
android:layout_below="#+id/button1"
android:layout_marginTop="26dp"
android:text="Distance Cost Calculator"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#android:color/white"
android:textStyle="bold" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp"
android:text="Mileage Calculator"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#android:color/white"
android:textStyle="bold" />
<EditText
android:id="#+id/editText4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView6"
android:layout_alignBottom="#+id/textView6"
android:layout_toLeftOf="#+id/textView7"
android:ems="10"
android:inputType="numberDecimal"
android:width="50dp" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView3"
android:layout_below="#+id/textView4"
android:layout_marginTop="32dp"
android:text="Distance: "
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/white" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView6"
android:layout_below="#+id/editText4"
android:layout_marginTop="34dp"
android:text="Mileage: "
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/white" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button2"
android:layout_alignBottom="#+id/button2"
android:layout_alignRight="#+id/textView8"
android:background="#drawable/btn_normal"
android:paddingBottom="12dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="12dp"
android:text="Live Cost"
android:textColor="#android:color/white" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText3"
android:layout_marginTop="18dp"
android:layout_toLeftOf="#+id/button3"
android:background="#drawable/btn_normal"
android:paddingBottom="12dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="12dp"
android:text="Calculate Cost"
android:textColor="#android:color/white" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:background="#drawable/btn_normal"
android:paddingBottom="12dp"
android:paddingLeft="55dp"
android:paddingRight="55dp"
android:paddingTop="12dp"
android:text="Calculate Mileage"
android:textColor="#android:color/white" />
<TextView
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/editText3"
android:layout_alignBottom="#+id/editText3"
android:layout_alignLeft="#+id/textView9"
android:text="km/lt"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/white" />
<TextView
android:id="#+id/textView11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:text="Logged in as" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:paddingBottom="5dp"
android:text="City"
android:textAppearance="?android:attr/textAppearanceSmall" />
Manifest:
Changing the theme in Manifest has no effect, I have tried the themes which run with other successful activities!
Log:
08-01 10:38:14.374: E/Trace(14994): error opening trace file: No such file or directory (2)
08-01 10:38:14.390: V/ActivityThread(14994): com.basic.mileagecalculatorwithsettings white listed for hwui
08-01 10:38:14.452: I/System.out(14994): Sending WAIT chunk
08-01 10:38:14.452: W/ActivityThread(14994): Application com.basic.mileagecalculatorwithsettings is waiting for the debugger on port 8100...
08-01 10:38:14.499: I/dalvikvm(14994): Debugger is active
08-01 10:38:14.655: I/System.out(14994): Debugger has connected
08-01 10:38:14.655: I/System.out(14994): waiting for debugger to settle...
08-01 10:38:14.858: I/System.out(14994): waiting for debugger to settle...
08-01 10:38:15.061: I/System.out(14994): waiting for debugger to settle...
08-01 10:38:15.257: I/System.out(14994): waiting for debugger to settle...
08-01 10:38:15.460: I/System.out(14994): waiting for debugger to settle...
08-01 10:38:15.663: I/System.out(14994): waiting for debugger to settle...
08-01 10:38:15.858: I/System.out(14994): waiting for debugger to settle...
08-01 10:38:16.061: I/System.out(14994): waiting for debugger to settle...
08-01 10:38:16.265: I/System.out(14994): waiting for debugger to settle...
08-01 10:38:16.460: I/System.out(14994): waiting for debugger to settle...
08-01 10:38:16.663: I/System.out(14994): debugger has settled (1366)
08-01 10:38:29.194: D/AndroidRuntime(14994): Shutting down VM
08-01 10:38:29.194: W/dalvikvm(14994): threadid=1: thread exiting with uncaught exception (group=0x40aa0440)
08-01 10:38:29.257: E/AndroidRuntime(14994): FATAL EXCEPTION: main
08-01 10:38:29.257: E/AndroidRuntime(14994): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.basic.mileagecalculatorwithsettings/com.basic.mileagecalculatorwithsettings.CalculatorActivity}: java.lang.NumberFormatException: Invalid int: ""
08-01 10:38:29.257: E/AndroidRuntime(14994): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2187)
08-01 10:38:29.257: E/AndroidRuntime(14994): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2212)
08-01 10:38:29.257: E/AndroidRuntime(14994): at android.app.ActivityThread.access$600(ActivityThread.java:144)
08-01 10:38:29.257: E/AndroidRuntime(14994): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
08-01 10:38:29.257: E/AndroidRuntime(14994): at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 10:38:29.257: E/AndroidRuntime(14994): at android.os.Looper.loop(Looper.java:137)
08-01 10:38:29.257: E/AndroidRuntime(14994): at android.app.ActivityThread.main(ActivityThread.java:4966)
08-01 10:38:29.257: E/AndroidRuntime(14994): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 10:38:29.257: E/AndroidRuntime(14994): at java.lang.reflect.Method.invoke(Method.java:511)
08-01 10:38:29.257: E/AndroidRuntime(14994): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
08-01 10:38:29.257: E/AndroidRuntime(14994): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
08-01 10:38:29.257: E/AndroidRuntime(14994): at dalvik.system.NativeStart.main(Native Method)
08-01 10:38:29.257: E/AndroidRuntime(14994): Caused by: java.lang.NumberFormatException: Invalid int: ""
08-01 10:38:29.257: E/AndroidRuntime(14994): at java.lang.Integer.invalidInt(Integer.java:138)
08-01 10:38:29.257: E/AndroidRuntime(14994): at java.lang.Integer.parseInt(Integer.java:359)
08-01 10:38:29.257: E/AndroidRuntime(14994): at java.lang.Integer.parseInt(Integer.java:332)
08-01 10:38:29.257: E/AndroidRuntime(14994): at com.basic.mileagecalculatorwithsettings.CalculatorActivity.onCreate(CalculatorActivity.java:55)
08-01 10:38:29.257: E/AndroidRuntime(14994): at android.app.Activity.performCreate(Activity.java:5008)
08-01 10:38:29.257: E/AndroidRuntime(14994): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
08-01 10:38:29.257: E/AndroidRuntime(14994): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2141)
08-01 10:38:29.257: E/AndroidRuntime(14994): ... 11 more
The error I think is Invalid Int: "". What could be the reason?
final String unitstring = unitpreference.getString("unit_type", "");
final int unit = Integer.parseInt(unitstring);
should fail on every Android version!
Try:
final String unitstring = unitpreference.getString("unit_type", "0");
final int unit = Integer.parseInt(unitstring);
Note: a better way to achieve that would be to store "unit_type" as an int, not as a String
your unitstring must be coming as empty string. Please check that
final String unitstring = unitpreference.getString("unit_type", "");
final int unit = Integer.parseInt(unitstring);
You should catch the NumberFormatException at the least.
final String unitstring = unitpreference.getString("unit_type", "");
final int unit = Integer.parseInt(unitstring);
At initial point it gets " " in unitstring.
so it cant be parsed in integer.
so your preference is may be null
Try to use:
final String unitstring = unitpreference.getString("unit_type", "1");
final int unit = Integer.parseInt(unitstring);
so unitstring's default value will be "1".
In preferences, while getting some value. always put some default value in "keyvalue(here "1" is default)". so whenever your "key preference(here, "unit_type")" is null or "" or undefined. then it will give the "keyvalue" which is default value for that key.