Hi im new to android programming and this code produces an error when the button is clicked... It shows unfortunately the application has stopped can anybody check? :(
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.compute);
aButton = (Button) this.findViewById(R.id.Button06);
//get intent
Intent i = getIntent();
Bundle extras = i.getExtras(); // get the parameters
density = getBaseContext().getResources().getDisplayMetrics().density;
int textViewSizeDp = (int)(200 * density);
int textFieldSizeDp = (int)(50 * density);
FieldsLayout = (LinearLayout) findViewById(R.id.FieldsLayout);
if(extras!=null){
items = (extras.getString("items")).split(",");
rows = new LinearLayout[items.length];
labels = new TextView[items.length];
fields = new EditText[items.length];
for (int ctr=0;ctr<items.length;ctr++){
rows[ctr] = new LinearLayout(Compute.this);
rows[ctr].setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
rows[ctr].setOrientation(LinearLayout.HORIZONTAL);
rows[ctr].setLayoutParams(new LayoutParams (LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
FieldsLayout.addView(rows[ctr]);
labels[ctr] = new TextView(Compute.this);
labels[ctr].setText(items[ctr]);
labels[ctr].setMinimumWidth(textViewSizeDp);
rows[ctr].addView(labels[ctr]);
fields[ctr] = new EditText(Compute.this);
fields[ctr].setMinimumWidth(textFieldSizeDp);
rows[ctr].addView(fields[ctr]);
}
}
else{
finish();
}
aButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Compute.this, Total.class);
//I believe this causes the error
for(int ctr=0;ctr<fields.length;ctr++){
itemName[ctr] = labels[ctr].getText().toString();
}
for(int ctr=0;ctr<fields.length;ctr++){
itemHour[ctr] = Integer.parseInt(fields[ctr].getText().toString());
}
//until here
i.putExtra("hours",itemHour);
i.putExtra("items",itemName);
startActivity(i);
}});
}
here's the error log: (or is this it?)
01-14 09:37:16.047: W/Trace(768): Unexpected value from nativeGetEnabledTags: 0
01-14 09:37:16.187: E/AndroidRuntime(768): FATAL EXCEPTION: main
01-14 09:37:16.187: E/AndroidRuntime(768): java.lang.NullPointerException
01-14 09:37:16.187: E/AndroidRuntime(768): at com.example.mpc.Compute$1.onClick(Compute.java:82)
01-14 09:37:16.187: E/AndroidRuntime(768): at android.view.View.performClick(View.java:4202)
01-14 09:37:16.187: E/AndroidRuntime(768): at android.view.View$PerformClick.run(View.java:17340)
01-14 09:37:16.187: E/AndroidRuntime(768): at android.os.Handler.handleCallback(Handler.java:725)
01-14 09:37:16.187: E/AndroidRuntime(768): at android.os.Handler.dispatchMessage(Handler.java:92)
01-14 09:37:16.187: E/AndroidRuntime(768): at android.os.Looper.loop(Looper.java:137)
01-14 09:37:16.187: E/AndroidRuntime(768): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-14 09:37:16.187: E/AndroidRuntime(768): at java.lang.reflect.Method.invokeNative(Native Method)
01-14 09:37:16.187: E/AndroidRuntime(768): at java.lang.reflect.Method.invoke(Method.java:511)
01-14 09:37:16.187: E/AndroidRuntime(768): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-14 09:37:16.187: E/AndroidRuntime(768): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-14 09:37:16.187: E/AndroidRuntime(768): at dalvik.system.NativeStart.main(Native Method)
Check out following things:
Make sure your field array is initialized properly.
Make sure that the length of itemName is same as that of fields.length and it should be properly initialized.
Make sure that the length of labels is same as that of fields.length and it should be properly initialized.
Make sure that the length of itemHour is same as that of fields.length and it should be properly initialized.
Check the following:
The Id of button
Same id more then one button in same layout.
Its map with xml file or not.
As this is NullPointerException, you are either having some null fields or you have forgotten to initialise some of your fields,
Check,
If you have done aButton = (Button)findViewById(R.id.ButtonID);
if you have initialised itemName[] and itemHour[], something like itemHour[ctr] = new String[];
If there are any values in the labels[] and fields[]
If it still doesnt helps, then you should post some more relavent code, only then I could edit my answer.
Related
In my Android application i am creating a pie chart using achartengine library. When click a button it takes data from sqlite database and draw a pie chart. This is my code segment.
btnpieChart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SelectDBAdapter selectDBAdapter = SelectDBAdapter
.getDBAdapterInstance(getActivity());
try {
selectDBAdapter.openDataBase();
chartDataMap = selectDBAdapter
.getPieChartData(strBusinessUnit,
currentPeriod, currentYear);
} catch (Exception e) {
selectDBAdapter.close();
e.printStackTrace();
} finally {
selectDBAdapter.close();
}
System.out.println("chartDataMap === "+ chartDataMap);
if (chartDataMap.size() > 0) {
for (Map.Entry<String, Double> entry : chartDataMap.entrySet()) {
lstBrandNames.add(entry.getKey());
lstAchievedVals.add(entry.getValue());
}
ArrayList<Double> distribution = calc_Percentage(lstAchievedVals);
System.out.println("distribution === " + distribution);
lstBrandNames = set_lables(lstBrandNames, distribution);
CategorySeries distributionSeries = new CategorySeries(
"Brands - Achievement Progress");
for (int i = 0; i < distribution.size(); i++) {
distributionSeries.add(lstBrandNames.get(i), distribution.get(i));
}
DefaultRenderer defaultRenderer = new DefaultRenderer();
defaultRenderer.setApplyBackgroundColor(true);
defaultRenderer.setBackgroundColor(Color.WHITE);
for (int i = 0; i < distribution.size(); i++) {
SimpleSeriesRenderer seriesRenderer = new SimpleSeriesRenderer();
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
seriesRenderer.setColor(color);
seriesRenderer.setGradientEnabled(false);
seriesRenderer.setDisplayChartValues(true);
seriesRenderer.setShowLegendItem(false);
defaultRenderer.setLabelsTextSize(25);
defaultRenderer.addSeriesRenderer(seriesRenderer);
}
defaultRenderer.setLabelsColor(Color.BLACK);
defaultRenderer.setChartTitle("Brands - Achievement Progress");
defaultRenderer.setChartTitleTextSize(30);
defaultRenderer.setZoomButtonsVisible(true);
defaultRenderer.setShowLabels(true);
FragmentTransaction ft = getFragmentManager().beginTransaction();
mChartView = ChartFactory.getPieChartView(getActivity(), distributionSeries, defaultRenderer);
ft.replace(mChartView.getId(), new DummySectionFragment(), "NewFragmentTag");
ft.addToBackStack(null);
ft.commit();
}
}
});
My mChartView is,
private GraphicalView mChartView = null;
Log cat says:
11-25 07:03:58.311: E/AndroidRuntime(2706): FATAL EXCEPTION: main
11-25 07:03:58.311: E/AndroidRuntime(2706): android.content.res.Resources$NotFoundException: Unable to find resource ID #0xffffffff
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.content.res.Resources.getResourceName(Resources.java:1659)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:919)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.os.Handler.handleCallback(Handler.java:725)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.os.Handler.dispatchMessage(Handler.java:92)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.os.Looper.loop(Looper.java:137)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.app.ActivityThread.main(ActivityThread.java:5039)
11-25 07:03:58.311: E/AndroidRuntime(2706): at java.lang.reflect.Method.invokeNative(Native Method)
11-25 07:03:58.311: E/AndroidRuntime(2706): at java.lang.reflect.Method.invoke(Method.java:511)
11-25 07:03:58.311: E/AndroidRuntime(2706): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-25 07:03:58.311: E/AndroidRuntime(2706): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-25 07:03:58.311: E/AndroidRuntime(2706): at dalvik.system.NativeStart.main(Native Method)
I would be much obliged if anyone could explain what's going on here and how can I solve this issue.
Thanks
Check these lines
mChartView = ChartFactory.getPieChartView(getActivity(), distributionSeries, defaultRenderer);
ft.replace(mChartView.getId(), new DummySectionFragment(), "NewFragmentTag");
especially mChartView.getId() log this value and check it with what you expected
I am encountering a problem in my Android application where my app crashes when I try to save a value. I am making an online currency converter. Here is my part of my code:
View.OnClickListener myhandler1 = new View.OnClickListener() {
#Override
public void onClick(View v) {
String text1 = spinner1.getSelectedItem().toString().trim();
String text2 = spinner2.getSelectedItem().toString().trim();
if (text1.equals("US Dollar - USD") && text2.equals("Euro - EUR") && edittextdollars.length() > 0 && edittexteuros.length()==0) {
try {
convertvalues("USD", "EUR");
float k = Float.parseFloat(convertvalues("USD", "EUR"));
SharedPreferences settings = getActivity().getSharedPreferences("Pref", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putFloat("dollarseuros", k);
editor.commit();
}
catch (Exception e) {
SharedPreferences settings = getActivity().getSharedPreferences("Pref", 0);
float val = Float.parseFloat(edittextdollars.getText().toString());
float k = Float.parseFloat(convertvalues("USD", "EUR"));
DecimalFormat df = new DecimalFormat(".##");
String l = df.format(k * val);
edittexteuros.setText(settings.getString("dollarseuros", l));
}
}
What my app is supposed to do is to get the value of the USD to EUR rate, then save it until there is no internet connection. It is supposed to use the cached value when no internet connection is available.
Here is my LogCat:
07-24 00:16:14.804: E/AndroidRuntime(1298): FATAL EXCEPTION: main
07-24 00:16:14.804: E/AndroidRuntime(1298): java.lang.NumberFormatException: Invalid float: ""
07-24 00:16:14.804: E/AndroidRuntime(1298): at java.lang.StringToReal.invalidReal(StringToReal.java:63)
07-24 00:16:14.804: E/AndroidRuntime(1298): at java.lang.StringToReal.parseFloat(StringToReal.java:289)
07-24 00:16:14.804: E/AndroidRuntime(1298): at java.lang.Float.parseFloat(Float.java:300)
07-24 00:16:14.804: E/AndroidRuntime(1298): at com.example.currencyconverter.MainActivity$1.onClick(MainActivity.java:240)
07-24 00:16:14.804: E/AndroidRuntime(1298): at android.view.View.performClick(View.java:4204)
07-24 00:16:14.804: E/AndroidRuntime(1298): at android.view.View$PerformClick.run(View.java:17355)
07-24 00:16:14.804: E/AndroidRuntime(1298): at android.os.Handler.handleCallback(Handler.java:725)
07-24 00:16:14.804: E/AndroidRuntime(1298): at android.os.Handler.dispatchMessage(Handler.java:92)
07-24 00:16:14.804: E/AndroidRuntime(1298): at android.os.Looper.loop(Looper.java:137)
07-24 00:16:14.804: E/AndroidRuntime(1298): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-24 00:16:14.804: E/AndroidRuntime(1298): at java.lang.reflect.Method.invokeNative(Native Method)
07-24 00:16:14.804: E/AndroidRuntime(1298): at java.lang.reflect.Method.invoke(Method.java:511)
07-24 00:16:14.804: E/AndroidRuntime(1298): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-24 00:16:14.804: E/AndroidRuntime(1298): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-24 00:16:14.804: E/AndroidRuntime(1298): at dalvik.system.NativeStart.main(Native Method)
What is wrong? I have checked Google and StackOverflow, but nothing solves my problem. Any help would be greatly appreciated.
You are getting a NumberFormatException which means, in Float.parseFloat(stringToParse), stringToParse cannot be parsed to a float.
For example, Float.parseFloat("") or Float.parseFloat("Not a float") will throw a NumberFormatException because the empty string "" or "Now a float" cannot be parsed to a float value. Check what you are feeding to Float.parseFloat() and you will overcome this issue.
Edit
Based on convertvalues() method you have posted now:
public String convertvalues(String convertfrom, String convertto) {
double current;
double val = Double.parseDouble(
edittextdollars.getText().toString());
DecimalFormat df = new DecimalFormat(".##");
YahooCurrencyConverter ycc = new YahooCurrencyConverter();
try {
current = ycc.convert(convertfrom, convertto);
edittexteuros.setText(df.format(val*current));
return ""; // <----------- Problem
}
catch (Exception e) {
return ""; // <----------- Could be a problem
}
}
Your convertvalues() method returns an empty string no matter what. You are returning an empty string in both try and catch block. Is this what you really want to return?
I have been trying to program a twitter client for Android (using twitter4j). So far the idea is to have a simple GUI, and if there is not a file with the OAuth token in the SD Card, connect to the Twitter API using AsyncTask, get the URL for the authorization and open the default browser. However, the browser never runs. Depending on the different modifications I have made trying to fix this, either the Activity starts normally but the browser never starts or the Activity crashes. I have come to a point of a a little of frustation and confussion. Can someone point out what's wrong with my code?
public class StatusActivity extends Activity {
private static final String TAG = "StatusActivity";
EditText editText;
Button updateButton;
File oauthfile = null;
public Context context = getApplicationContext();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_status);
Log.d(TAG, "started");
// Find views
editText = (EditText) findViewById(R.id.editText); //
updateButton = (Button) findViewById(R.id.buttonUpdate);
oauthfile = new File("sdcard/auth_file.txt");
//Check if the file with the keys exist
if (oauthfile.exists()==false){
Log.d(TAG, "file not created");
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "file not created.", Toast.LENGTH_SHORT);
toast.show();
new Authorization(context).execute();
}
}
public void openBrowser (View v){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
Log.d(TAG, "onclick");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.status, menu);
return true;
}
}
class Authorization extends AsyncTask <String, Integer, String>{
String url = null;
private Context context;
Authorization(Context context) {
this.context = context.getApplicationContext();
}
public void onPreExecute() {
super.onPreExecute();
Toast.makeText(context, "Invoke onPreExecute()", Toast.LENGTH_SHORT).show();
}
#Override
public String doInBackground(String... params) {
ConfigurationBuilder configBuilder = new ConfigurationBuilder();
configBuilder.setDebugEnabled(true)
//I have eliminated the keys from the question :)
.setOAuthConsumerKey("XXXXXXXXXXXXXX")
.setOAuthConsumerSecret("XXXXXXXXXXXXXXX");
Twitter OAuthTwitter = new TwitterFactory(configBuilder.build()).getInstance();
RequestToken requestToken = null;
AccessToken accessToken = null;
do{
try {
requestToken = OAuthTwitter.getOAuthRequestToken();
url = requestToken.getAuthorizationURL();
}
catch (TwitterException ex) {
ex.printStackTrace();
}
}
while (accessToken==null);
return url;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(context, "Opening browser.", Toast.LENGTH_SHORT).show();
Intent browserIntent = new Intent(Intent.ACTION_ALL_APPS, Uri.parse(url));
context.startActivity(browserIntent);
}
}
I know that at least checks if the file for the tokens exists because the toast "file not created" appears, and that the activity is able to run the browser if I press the button. The app has permissions to write in the SD card and use the Internet. Thanks in advance.
Logcat Trace:
03-28 19:02:32.816: E/AndroidRuntime(278): FATAL EXCEPTION: main
03-28 19:02:32.816: E/AndroidRuntime(278): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.versec.pardinus/com.versec.pardinus.StatusActivity}: java.lang.NullPointerException
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.os.Handler.dispatchMessage(Handler.java:99)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.os.Looper.loop(Looper.java:123)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.reflect.Method.invokeNative(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.reflect.Method.invoke(Method.java:521)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-28 19:02:32.816: E/AndroidRuntime(278): at dalvik.system.NativeStart.main(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): Caused by: java.lang.NullPointerException
03-28 19:02:32.816: E/AndroidRuntime(278): at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:100)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.versec.pardinus.StatusActivity.<init>(StatusActivity.java:30)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.Class.newInstanceImpl(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.Class.newInstance(Class.java:1429)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
03-28 19:02:32.816: E/AndroidRuntime(278): ... 11 more
This is what is causing your crash.
public Context context = getApplicationContext();
You're not even using it when you need it, so you can just get rid of this line.
Btw, something else I noticed while looking at your code is this:
oauthfile = new File("sdcard/auth_file.txt");
Don't take the "sdcard/" path for granted. Use this instead:
File dir = Environment.getExternalStorageDirectory();
File oauthfile = new File(dir, "auth_file.txt");
I have a button with set color code:
buttonClicked.setTextColor(Color.GRAY);
Now when I finish my timer, the text of all buttons reset to something else, so I need that text to go back to default. I tried this but I get error (i placed a comment near the end of my code for that error):
final OnClickListener clickListener = new OnClickListener() {
private Button buttonClicked;
private int brojacKlikova = 0;
public void onClick(View v) {
brojacKlikova++;
if (brojacKlikova < 16) {
Button button = (Button) v;
button.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0x003333));
if (buttonClicked == null) {
// first button is clicked
buttonClicked = button;
} else {
// second button is clicked
if (buttonClicked.getTag().equals(button.getTag())) {
button.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0x66FF33));
buttonClicked.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0x66FF33));
buttonClicked.setEnabled(false);
button.setEnabled(false);
counter = counter + 5;
score.setText("Poeni: " + counter);
} else {
buttonClicked.setEnabled(false);
buttonClicked.setTextColor(Color.GRAY);
buttonClicked.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xFFCC99));
button.getBackground().clearColorFilter();
}
buttonClicked = null;
}
}else{
buttonClicked = null;
buttonClicked.setTextColor(Color.WHITE); //<--- here I get error
brojacKlikova = 0;
brojacVremena.cancel();
mHandler.postDelayed(mLaunchTask,2200);
}
}
};
How to reset my button's text color to default?
Here's logcat:
03-28 23:59:29.357: W/dalvikvm(27918): threadid=1: thread exiting with uncaught exception (group=0x40018560)
03-28 23:59:29.467: E/AndroidRuntime(27918): FATAL EXCEPTION: main
03-28 23:59:29.467: E/AndroidRuntime(27918): java.lang.NullPointerException
03-28 23:59:29.467: E/AndroidRuntime(27918): at rs.androidaplikacije.spojnice.Spojnice$1.onClick(Spojnice.java:77)
03-28 23:59:29.467: E/AndroidRuntime(27918): at android.view.View.performClick(View.java:2506)
03-28 23:59:29.467: E/AndroidRuntime(27918): at android.view.View$PerformClick.run(View.java:9112)
03-28 23:59:29.467: E/AndroidRuntime(27918): at android.os.Handler.handleCallback(Handler.java:587)
03-28 23:59:29.467: E/AndroidRuntime(27918): at android.os.Handler.dispatchMessage(Handler.java:92)
03-28 23:59:29.467: E/AndroidRuntime(27918): at android.os.Looper.loop(Looper.java:130)
03-28 23:59:29.467: E/AndroidRuntime(27918): at android.app.ActivityThread.main(ActivityThread.java:3835)
03-28 23:59:29.467: E/AndroidRuntime(27918): at java.lang.reflect.Method.invokeNative(Native Method)
03-28 23:59:29.467: E/AndroidRuntime(27918): at java.lang.reflect.Method.invoke(Method.java:507)
03-28 23:59:29.467: E/AndroidRuntime(27918): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
03-28 23:59:29.467: E/AndroidRuntime(27918): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
03-28 23:59:29.467: E/AndroidRuntime(27918): at dalvik.system.NativeStart.main(Native Method)
03-28 23:59:31.167: I/Process(27918): Sending signal. PID: 27918 SIG: 9
buttonClicked = null;
buttonClicked.setTextColor(Color.WHITE);
Problem is here. You are assigned button to NULL and then you call property on it. This always throw NPE. Solution is to remove first line and it should work.
I have two methods to update and delete data in my app, I have implemeted try catches within my switch statement and am now getting the following error:
01-14 20:38:58.778: D/AndroidRuntime(273): Shutting down VM
01-14 20:38:58.778: W/dalvikvm(273): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-14 20:38:58.798: E/AndroidRuntime(273): FATAL EXCEPTION: main
01-14 20:38:58.798: E/AndroidRuntime(273): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.flybase2/com.example.flybase2.viewEdit}: java.lang.NullPointerException
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.os.Handler.dispatchMessage(Handler.java:99)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.os.Looper.loop(Looper.java:123)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-14 20:38:58.798: E/AndroidRuntime(273): at java.lang.reflect.Method.invokeNative(Native Method)
01-14 20:38:58.798: E/AndroidRuntime(273): at java.lang.reflect.Method.invoke(Method.java:521)
01-14 20:38:58.798: E/AndroidRuntime(273): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-14 20:38:58.798: E/AndroidRuntime(273): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-14 20:38:58.798: E/AndroidRuntime(273): at dalvik.system.NativeStart.main(Native Method)
01-14 20:38:58.798: E/AndroidRuntime(273): Caused by: java.lang.NullPointerException
01-14 20:38:58.798: E/AndroidRuntime(273): at com.example.flybase2.viewEdit.<init>(viewEdit.java:63)
01-14 20:38:58.798: E/AndroidRuntime(273): at java.lang.Class.newInstanceImpl(Native Method)
01-14 20:38:58.798: E/AndroidRuntime(273): at java.lang.Class.newInstance(Class.java:1429)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
01-14 20:38:58.798: E/AndroidRuntime(273): ... 11 more
Can anyone see the issue? It works perfectly without the try catches.
Heres the class:
package com.example.flybase2;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class viewEdit extends Activity implements OnClickListener{
EditText namePassedEdit;
EditText numPassedEdit;
EditText emailPassedEdit;
EditText commentPassedEdit;
Button bUpdate;
Button bDelete;
long passedID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editview);
DBHandler displayEdit = new DBHandler(this, null, null);
Bundle extras = getIntent().getExtras();
if (extras != null) {
passedID = extras.getLong("passedID");
}
displayEdit.open();
String returnedNameToEdit = displayEdit.getName(passedID);
String returnedNumToEdit = displayEdit.getNum(passedID);
String returnedEmailToEdit = displayEdit.getEmail(passedID);
String returnedCommentToEdit = displayEdit.getComments(passedID);
namePassedEdit = (EditText) findViewById(R.id.inputNameEdit);
numPassedEdit = (EditText) findViewById(R.id.inputTelNoEdit);
emailPassedEdit = (EditText) findViewById(R.id.inputEmailEdit);
commentPassedEdit = (EditText) findViewById(R.id.inputCommentEdit);
bUpdate = (Button) findViewById (R.id.btnAddConEdit);
bDelete = (Button) findViewById (R.id.btnDeleteContact);
namePassedEdit.setText(returnedNameToEdit);
numPassedEdit.setText(returnedNumToEdit);
emailPassedEdit.setText(returnedEmailToEdit);
commentPassedEdit.setText(returnedCommentToEdit);
bUpdate.setOnClickListener(this);
bDelete.setOnClickListener(this);
}
String nameEdit = namePassedEdit.getText().toString();
String telEdit = numPassedEdit.getText().toString();
String emailEdit = emailPassedEdit.getText().toString();
String commentEdit = commentPassedEdit.getText().toString();
#Override
public void onClick(View updateOrDeleteClicked) {
boolean check = true;
switch(updateOrDeleteClicked.getId()){
case (R.id.btnAddConEdit):
try
{
DBHandler updateData = new DBHandler(this, null, null);
updateData.open();
updateData.updateData(passedID, nameEdit, telEdit, emailEdit, commentEdit);
}
catch (Exception e)
{
check = false;
Dialog d = new Dialog(this);
d.setTitle("Contact failed to be deleted.");
TextView txt = new TextView(this);
txt.setText("Fail");
d.setContentView(txt);
d.show();
}
finally
{
if(check = true);
{
Dialog e = new Dialog(this);
e.setTitle("Contact deleted.");
TextView txt = new TextView(this);
txt.setText("Success");
e.setContentView(txt);
e.show();
}
}
break;
case (R.id.btnDeleteContact):
try
{
DBHandler deleteContact = new DBHandler(this, null, null);
deleteContact.open();
deleteContact.deleteData(passedID);
}
catch (Exception e)
{
check = false;
Dialog d = new Dialog(this);
d.setTitle("Contact failed to be deleted.");
TextView txt = new TextView(this);
txt.setText("Fail");
d.setContentView(txt);
d.show();
}
finally
{
if(check = true);
{
Dialog e = new Dialog(this);
e.setTitle("Contact deleted.");
TextView txt = new TextView(this);
txt.setText("Success");
e.setContentView(txt);
e.show();
}
}
break;
}
}
}
String nameEdit = namePassedEdit.getText().toString();
String telEdit = numPassedEdit.getText().toString();
String emailEdit = emailPassedEdit.getText().toString();
String commentEdit = commentPassedEdit.getText().toString();
These lines aren't inside a method, and you can't use them like that. You're getting a null pointer on namePassedEdit because it's trying to initialize them when the class is created, and they aren't assigned anything yet.
One issue I see here is:
if(check = true); //This ends if statement here and here you are assigning true to check nothing more than that..
I guess what you need here is:
if(check){....}
The main problem I can find is that you close the braces for your onCreate on line 59. Leaving the following lines between functions.
String nameEdit = namePassedEdit.getText().toString();
String telEdit = numPassedEdit.getText().toString();
String emailEdit = emailPassedEdit.getText().toString();
String commentEdit = commentPassedEdit.getText().toString();
If you move these up into the onCreate it will probably fix your issue. Also as #Nambari said in their answer, in your if statements you are checking if check was set to true. You need to change this to:
if(check)