I'm trying to take an RGB value (not hexadecimal, the actual constant value, such as -16711936) from a textfield and display it in a new activity (to use it as an integer). I attempted to do this by converting the string to an integer, but it still ends up crashing the program. Here's the code:
FULL SOURCE:issue occurs in testvalue function
package com.example.seniordesign;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity { //1
//public final static String RGB_VALUE = "com.example.seniordesign.RGB_VALUE_USE";
TextView pixelcord, rgbvals, rgbnumvals, red, green, blue, RGB;
ImageView iv;
Button btn;
#Override
public void onCreate(Bundle savedInstanceState) { //2
/* GATHER THE INFORMATION FROM THE LAYOUT TO ORGANIZE APP*/
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* SET ON CLICK LISTENER TO GET CLICK REPSONSE -- LAUNCH CAMERA AND TAKE PHOTO */
/* SET VARIABLES FOR USE FROM EACH VIEW */
iv = (ImageView) findViewById(R.id.imageView); /* USE IMAGE VIEW FIELD*/
pixelcord = (TextView)findViewById(R.id.pixelcord); /* USE TEXT FIELD FOR PIXEL */
rgbvals = (TextView)findViewById(R.id.rgbvals); /* USE TEXT FIELD FOR RGB VALUES*/
btn = (Button) findViewById(R.id.takePhoto);
/* SET INFORMATION OF WHAT TO DO UPON EACH CLIK*/
iv.setOnTouchListener(imgSourceOnTouchListener);
red = (TextView)findViewById(R.id.red);
blue = (TextView)findViewById(R.id.blue);
green = (TextView)findViewById(R.id.green);
RGB = (TextView)findViewById(R.id.RGB);
/* =====================================CAMERA BUTTON=====================================*/
btn.setOnClickListener(new OnClickListener() { //3
#Override
public void onClick(View v) { //4
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
} //*4
}); //*3
/* =======================================================================================*/
} /* END OF ON CREATE*/ //*2
/* DECLARATION OF IMG TOUCH FUNCTION*/
OnTouchListener imgSourceOnTouchListener = new OnTouchListener() { //5
#Override
public boolean onTouch(View view, MotionEvent event) { //6
float eventX = event.getX();
float eventY = event.getY();
float[] eventXY = new float[] { eventX, eventY};
Matrix invertMatrix = new Matrix();
((ImageView)view).getImageMatrix().invert(invertMatrix);
invertMatrix.mapPoints(eventXY);
int x = Integer.valueOf((int)eventXY[0]); /* POTENTIALLY REDUNDANT*/
int y = Integer.valueOf((int)eventXY[1]);
/* CHECK TO MAKE SURE VALUES ARE WITHIN BITMAP RANGE*/
/* SET TEXT FUNCTION TO THE FIELD USING SET TEXT METHOD*/
pixelcord.setText("X:" + String.valueOf(eventX) + "/ Y:" + String.valueOf(eventY) );
Bitmap bitmap = ((BitmapDrawable)iv.getDrawable()).getBitmap();
int touchedRGB = bitmap.getPixel(x,y);
rgbvals.setText("Color Value" + "#" + Integer.toHexString(touchedRGB));
rgbvals.setTextColor(touchedRGB);
int rval = Color.red(touchedRGB);
int bval = Color.blue(touchedRGB);
int gval = Color.green(touchedRGB);
red.setText(String.valueOf(rval));
blue.setText(String.valueOf(bval));
green.setText(String.valueOf(gval));
RGB.setText(String.valueOf(touchedRGB));
return true;
} //*6
}; //*5
public void testvalue(View view) {
Intent intent = new Intent(this, TestValue.class);
TextView RGBval = (TextView) findViewById(R.id.RGB);
int rgb_val_use = Integer.parseInt((String) RGBval.getText().toString());
intent.putExtra("RGB_VALUE", (int)rgb_val_use);
startActivity(intent);
}
#Override
public void onActivityResult( int requestCode, int resultCode, Intent data)
{ //7
if(requestCode == 0)
{ //8
Bitmap theImage = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(theImage);
} //*8
} //*7
} //*1
and here is my logCat:
10-31 07:27:44.334: E/AndroidRuntime(9915): FATAL EXCEPTION: main
10-31 07:27:44.334: E/AndroidRuntime(9915): java.lang.IllegalStateException: Could not execute method of the activity
10-31 07:27:44.334: E/AndroidRuntime(9915): at android.view.View$1.onClick(View.java:2144)
10-31 07:27:44.334: E/AndroidRuntime(9915): at android.view.View.performClick(View.java:2485)
10-31 07:27:44.334: E/AndroidRuntime(9915): at android.view.View$PerformClick.run(View.java:9089)
10-31 07:27:44.334: E/AndroidRuntime(9915): at android.os.Handler.handleCallback(Handler.java:587)
10-31 07:27:44.334: E/AndroidRuntime(9915): at android.os.Handler.dispatchMessage(Handler.java:92)
10-31 07:27:44.334: E/AndroidRuntime(9915): at android.os.Looper.loop(Looper.java:123)
10-31 07:27:44.334: E/AndroidRuntime(9915): at android.app.ActivityThread.main(ActivityThread.java:3806)
10-31 07:27:44.334: E/AndroidRuntime(9915): at java.lang.reflect.Method.invokeNative(Native Method)
10-31 07:27:44.334: E/AndroidRuntime(9915): at java.lang.reflect.Method.invoke(Method.java:507)
10-31 07:27:44.334: E/AndroidRuntime(9915): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-31 07:27:44.334: E/AndroidRuntime(9915): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-31 07:27:44.334: E/AndroidRuntime(9915): at dalvik.system.NativeStart.main(Native Method)
10-31 07:27:44.334: E/AndroidRuntime(9915): Caused by: java.lang.reflect.InvocationTargetException
10-31 07:27:44.334: E/AndroidRuntime(9915): at java.lang.reflect.Method.invokeNative(Native Method)
10-31 07:27:44.334: E/AndroidRuntime(9915): at java.lang.reflect.Method.invoke(Method.java:507)
10-31 07:27:44.334: E/AndroidRuntime(9915): at android.view.View$1.onClick(View.java:2139)
10-31 07:27:44.334: E/AndroidRuntime(9915): ... 11 more
10-31 07:27:44.334: E/AndroidRuntime(9915): Caused by: java.lang.NumberFormatException: unable to parse 'RGB' as integer
10-31 07:27:44.334: E/AndroidRuntime(9915): at java.lang.Integer.parse(Integer.java:383)
10-31 07:27:44.334: E/AndroidRuntime(9915): at java.lang.Integer.parseInt(Integer.java:372)
10-31 07:27:44.334: E/AndroidRuntime(9915): at java.lang.Integer.parseInt(Integer.java:332)
10-31 07:27:44.334: E/AndroidRuntime(9915): at com.example.seniordesign.MainActivity.testvalue(MainActivity.java:125)
10-31 07:27:44.334: E/AndroidRuntime(9915): ... 14 more
Is it just a syntax error or am I going about this incorrectly? I appreciate the help
NOTE: The value in the textfield is techinically a string I guess, this is the code I used to place it in the field (touchedRGB is an integer value).
RGB.setText(String.valueOf(touchedRGB));
If it makes a difference, this is the XML from this particular section
<TextView
android:id="#+id/RGB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/green"
android:layout_alignBottom="#+id/green"
android:layout_marginLeft="40dp"
android:layout_toRightOf="#+id/green"
android:text="RGB" />
The problem is, you have a string("RGB") in your textView. So you got a NumberFormatException.
Set an integet value in your textView and try again.
java.lang.NumberFormatException: unable to parse 'RGB' as integer
Edit: Could you try code below?
public void testvalue(View view) {
try{
TextView RGBval = (TextView) findViewById(R.id.RGB);
String valueStoredInRGBvalTextView = RGBval.getText().toString();
int rgb_val_use = Integer.parseInt(valueStoredInRGBvalTextView);
Intent intent = new Intent(this, TestValue.class);
intent.putExtra("RGB_VALUE", (int)rgb_val_use);
startActivity(intent);
} catch (Exception e) {
// Not touched yet
}
}
Edit2:
You are setting the integer touch value to RGB textView after first touch occurs. If you invoke your testvalue method before touching anywhere, you'll get this exception. Change your testvalue method as I wrote above. Your problem will be solved.
try this you cannot cast the int value to String like this -> (int)(rgb_val_use)
change it into new Integer.toString(rgb_val_use);
intent.putExtra("RGB_VALUE",new Integer.toString(rgb_val_use));
Integer rgb = Integer.getInteger((String) RGBval.getText(), null);
if (rgb == null) {
// input string is not integer
} else {
// use rgb to start new activity
}
Related
I created a button and assigned it 1 by doing
remove.setId(0 + count);
Then I tried to put that button in my onCreate bundle to use it
Button remove = (Button)findViewById(1);
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
When I create the button remove in my oncreate it runs but as soon as I add my onclick listener I dont get any errors but when I run it it force closes
Log
12-12 13:42:06.172: D/AndroidRuntime(19502): Shutting down VM
12-12 13:42:06.172: W/dalvikvm(19502): threadid=1: thread exiting with uncaught exception (group=0x416bbd40)
12-12 13:42:06.178: E/AndroidRuntime(19502): FATAL EXCEPTION: main
12-12 13:42:06.178: E/AndroidRuntime(19502): Process: com.th3ramr0d.armytrooptotask, PID: 19502
12-12 13:42:06.178: E/AndroidRuntime(19502): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.th3ramr0d.armytrooptotask/com.th3ramr0d.armytrooptotask.MainActivity}: java.lang.NullPointerException
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.access$800(ActivityThread.java:139)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.os.Handler.dispatchMessage(Handler.java:102)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.os.Looper.loop(Looper.java:136)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.main(ActivityThread.java:5102)
12-12 13:42:06.178: E/AndroidRuntime(19502): at java.lang.reflect.Method.invokeNative(Native Method)
12-12 13:42:06.178: E/AndroidRuntime(19502): at java.lang.reflect.Method.invoke(Method.java:515)
12-12 13:42:06.178: E/AndroidRuntime(19502): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
12-12 13:42:06.178: E/AndroidRuntime(19502): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
12-12 13:42:06.178: E/AndroidRuntime(19502): at dalvik.system.NativeStart.main(Native Method)
12-12 13:42:06.178: E/AndroidRuntime(19502): Caused by: java.lang.NullPointerException
12-12 13:42:06.178: E/AndroidRuntime(19502): at com.th3ramr0d.armytrooptotask.MainActivity.onCreate(MainActivity.java:45)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.Activity.performCreate(Activity.java:5248)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)
12-12 13:42:06.178: E/AndroidRuntime(19502): ... 11 more
Here is my full file
package com.th3ramr0d.armytrooptotask;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
public int count = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addTroopBtn = (Button) findViewById(R.id.addTroop);
addTroopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(count <= 5)
{
inputName(v);
}
else
{
}
}
});
Button remove = (Button)findViewById(1);
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
public void inputName(final View v){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
//alert.setTitle("Enter Name and Rank");
alert.setMessage("Please Enter A Name");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable name = input.getText();
addTroop(name);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
public void addTroop(Editable name){
LinearLayout mainPage = (LinearLayout) findViewById(R.id.manageTroopsMain);
if (count <= 5)
{
//CREATE NEW LINEAR LAYOUT
LinearLayout addTroopLayout = new LinearLayout(this);
//CREATE LAYOUT PARAMS FOR LAYOUT
LinearLayout.LayoutParams newLayout = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
newLayout.bottomMargin = 10;
//STYLE NEW LINEAR LAYOUT
addTroopLayout.setTag("addTroopLayout" + count);
addTroopLayout.setLayoutParams(newLayout);
addTroopLayout.setOrientation(LinearLayout.HORIZONTAL);
//CREATE NEW BUTTONS
Button newTroop = new Button(this);
Button remove = new Button(this);
Button change = new Button(this);
//CREATE LAYOUT PARAMS FOR BUTTONS
LinearLayout.LayoutParams newTroopParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 20f);
LinearLayout.LayoutParams rmvBtnParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, .5f);
LinearLayout.LayoutParams chngNameParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, .5f);
//STYLE NEW BUTTONS
newTroop.setText(name);
newTroop.setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL);
newTroop.setLayoutParams(newTroopParam);
remove.setId(0 + count);
remove.setText("-");
remove.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
remove.setLayoutParams(rmvBtnParam);
change.setText("...");
change.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
change.setLayoutParams(chngNameParam);
//ADD VIEWS TO NEW LAYOUT
addTroopLayout.addView(newTroop);
addTroopLayout.addView(remove);
addTroopLayout.addView(change);
//ADD NEW LAYOUT TO mainPage LAYOUT
mainPage.addView(addTroopLayout);
//Increment Counter
count++;
}
}
}
This is your problem:
Button remove = (Button)findViewById(1);
This should be something like this:
Button remove = (Button)findViewById(R.id.buttonRemove); // that should be a long int
The crash is likely happening from this line:
Button remove = (Button)findViewById(1);
You'll need to provide a valid ID for a Button within your inflated layout. A value of 1 is not meaningful.
Good morning,
I'm trying to send two arrays (returned from getValuesGraph(doc) and getValuesFooter(doc) respectively) to the same function (OnPostExecute), I'm newbie at Java and Android and I don't now if the app code structure It's correct. So my apologies for the "disaster".
LogCat says:
02-21 00:07:25.852: W/dalvikvm(3282): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
02-21 00:07:25.862: E/AndroidRuntime(3282): FATAL EXCEPTION: main
02-21 00:07:25.862: E/AndroidRuntime(3282): java.lang.NullPointerException
02-21 00:07:25.862: E/AndroidRuntime(3282): at com.example.kwhora1.MainActivity$BackGroundTask.onPostExecute(MainActivity.java:159)
02-21 00:07:25.862: E/AndroidRuntime(3282): at com.example.kwhora1.MainActivity$BackGroundTask.onPostExecute(MainActivity.java:1)
02-21 00:07:25.862: E/AndroidRuntime(3282): at android.os.AsyncTask.finish(AsyncTask.java:631)
02-21 00:07:25.862: E/AndroidRuntime(3282): at android.os.AsyncTask.access$600(AsyncTask.java:177)
02-21 00:07:25.862: E/AndroidRuntime(3282): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
02-21 00:07:25.862: E/AndroidRuntime(3282): at android.os.Handler.dispatchMessage(Handler.java:99)
02-21 00:07:25.862: E/AndroidRuntime(3282): at android.os.Looper.loop(Looper.java:137)
02-21 00:07:25.862: E/AndroidRuntime(3282): at android.app.ActivityThread.main(ActivityThread.java:5041)
02-21 00:07:25.862: E/AndroidRuntime(3282): at java.lang.reflect.Method.invokeNative(Native Method)
02-21 00:07:25.862: E/AndroidRuntime(3282): at java.lang.reflect.Method.invoke(Method.java:511)
02-21 00:07:25.862: E/AndroidRuntime(3282): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-21 00:07:25.862: E/AndroidRuntime(3282): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-21 00:07:25.862: E/AndroidRuntime(3282): at dalvik.system.NativeStart.main(Native Method)
Here's the code:
package com.example.kwhora1;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView tvmax, tvmid, tvmin, tvactualval;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvmax=(TextView)findViewById(R.id.tvmaximo);
tvmid=(TextView)findViewById(R.id.tvmedio);
tvmin=(TextView)findViewById(R.id.tvminimo);
new BackGroundTask().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class BackGroundTask extends AsyncTask<Void, Void, String[]> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public String[] getValuesGraph(Document doc) {
int cont=24,var=7;
String bar[] = new String[cont];
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
for (cont=0; cont < 24; cont++){
String onMouseOver = doc.select("a").get(var+cont).attr("onMouseOver");
bar[cont] = onMouseOver.split("'")[9];
}
return bar;
}
public String[] getValuesFooter(Document doc) {
String values[] = new String[7];
/*
* Getting elements from the graphic footer
*/
Elements elements = doc.select("td.cabeceraRutaTexto");
elements.size(); // 6
/* Getting text from table */
values[0] = elements.get(0).text(); // TITLE
values[1] = elements.get(1).text(); // TEXT MAX VALUE
values[2] = elements.get(2).text(); // TEXT MIDDLE VALUE
values[3] = elements.get(3).text(); // TEXTO MIN VALUE
/* Getting numbers from table */
values[4] = elements.get(4).text(); // NUMBER MAX VALUE
values[5] = elements.get(5).text(); // NUMBER MIDDLE VALUE
values[6] = elements.get(6).text(); // NUMBER MIN VALUE
return values;
}
#Override
public String[] doInBackground(Void... params) {
try {
URL url= new URL("http://www.mywebtoextractdata.com");
Document doc = Jsoup.connect(url.toString()).get();
getValuesGraph(doc);
getValuesFooter(doc);
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] values) {
/*tvactualval.setText();*/
tvmax.setText(values[4]);
tvmid.setText(values[5]);
tvmin.setText(values[6]);
/*System.out.println(val[4]);*/
super.onPostExecute(values);
}
}
}
Thank you in advance for your help and time.
In String[] doInBackground(Void... params) { you are supposed to return a String array. So create one
String arr [] = new String [2];
and then add the result of getValuesGraph() to it.
arr[0] = getValuesGraph(doc);
arr[1] = getValuesFooter(doc);
then return then arr
This is doing my head in, and it's probably something simple that's causing it - so I think I need a new set of eyes looking at it.
All activities are defined in the manifest. I've made sure all attributes are initialised in onCreate/constructor.
The 'Circle' object is just a generic object with gets and sets for x, y, radius and colour.
Any help greatly appreciated.
10-01 16:06:28.338: E/AndroidRuntime(18306): FATAL EXCEPTION: main
10-01 16:06:28.338: E/AndroidRuntime(18306): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dbk.parallelreaction/com.dbk.parallelreaction.GameActivity}: java.lang.NullPointerException
10-01 16:06:28.338: E/AndroidRuntime(18306): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308)
10-01 16:06:28.338: E/AndroidRuntime(18306): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
10-01 16:06:28.338: E/AndroidRuntime(18306): at android.app.ActivityThread.access$600(ActivityThread.java:153)
10-01 16:06:28.338: E/AndroidRuntime(18306): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
10-01 16:06:28.338: E/AndroidRuntime(18306): at android.os.Handler.dispatchMessage(Handler.java:99)
10-01 16:06:28.338: E/AndroidRuntime(18306): at android.os.Looper.loop(Looper.java:137)
10-01 16:06:28.338: E/AndroidRuntime(18306): at android.app.ActivityThread.main(ActivityThread.java:5227)
10-01 16:06:28.338: E/AndroidRuntime(18306): at java.lang.reflect.Method.invokeNative(Native Method)
10-01 16:06:28.338: E/AndroidRuntime(18306): at java.lang.reflect.Method.invoke(Method.java:511)
10-01 16:06:28.338: E/AndroidRuntime(18306): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
10-01 16:06:28.338: E/AndroidRuntime(18306): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
10-01 16:06:28.338: E/AndroidRuntime(18306): at dalvik.system.NativeStart.main(Native Method)
10-01 16:06:28.338: E/AndroidRuntime(18306): Caused by: java.lang.NullPointerException
10-01 16:06:28.338: E/AndroidRuntime(18306): at com.dbk.parallelreaction.util.GameView.<init>(GameView.java:51)
10-01 16:06:28.338: E/AndroidRuntime(18306): at com.dbk.parallelreaction.GameActivity.onCreate(GameActivity.java:64)
10-01 16:06:28.338: E/AndroidRuntime(18306): at android.app.Activity.performCreate(Activity.java:5104)
10-01 16:06:28.338: E/AndroidRuntime(18306): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-01 16:06:28.338: E/AndroidRuntime(18306): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2262)
The two files in question:
GameActivity.java
package com.dbk.parallelreaction;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.dbk.parallelreaction.util.GameView;
public class GameActivity extends Activity {
// GameView object to hold current level
private GameView game;
// level/score persistance
private int currentLevel;
private int currentScore;
// game countdown timer
private CountDownTimer timer;
private int timerTime; // in milliseconds
private int timerPeriod; // in ms also
private int timerIndex;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
// initialise
timerTime = 10000;
timerPeriod = 50;
timerIndex = (int) timerTime / timerPeriod;
// aesthetic stuff
TextView ins = (TextView) findViewById(R.id.GameInstructions);
Typeface tf = Typeface.createFromAsset(getAssets(), "Economica-Regular.ttf");
ins.setTypeface(tf);
ins.setTextColor(Color.WHITE);
ins.setTextSize(18);
// get extras
Bundle extras = getIntent().getExtras();
currentLevel = extras.getInt("LEVEL");
currentScore = extras.getInt("SCORE");
// check if starting new game, or going to next level
switch(currentLevel) {
case 1:
// new level
break;
case 2:
// etc
break;
}
// add the game view to the layout
FrameLayout frame = (FrameLayout) findViewById(R.id.GameContainer);
game = new GameView(this, 2);
frame.addView(game);
// timer bar
final ProgressBar pb = (ProgressBar) findViewById(R.id.GameTimerBar);
pb.setMax(timerIndex);
pb.setProgress(timerIndex);
timer = new CountDownTimer(timerTime, timerPeriod) {
#Override
public void onFinish() {
pb.setProgress(timerIndex);
Bundle extras = new Bundle();
extras.putInt("SCORE", 16); // placeholder score
Intent i = new Intent(getApplicationContext(), GameOverActivity.class);
i.putExtras(extras);
// GAME OVER if timer bar empties
finish();
startActivity(i);
}
#Override
public void onTick(long msLeft) {
timerIndex--;
pb.setProgress(timerIndex);
}
}.start();
}
// cancel timer if user exits game
public void onBackPressed() {
super.onBackPressed();
timer.cancel();
}
}
GameView.java updated
package com.dbk.parallelreaction.util;
import java.util.ArrayList;
import java.util.Random;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.dbk.parallelreaction.R;
public class GameView extends SurfaceView {
// Temp ArrayList containing Circle objects
private ArrayList<Circle> circles;
// Paint object for colour info
private Paint paint;
// number of circles to draw depending on level
private int numCircles;
// Current score in the current level
private int levelScore;
public GameView(Context context, int numberCircles) {
super(context);
LayoutInflater inflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// replace custom_layout with the name of the .xml file that contains the `FrameLayout` with id R.id.GameContainer
View v = inflater.inflate(R.layout.activity_game, (ViewGroup) GameView.this.getParent(), true);
FrameLayout frame = (FrameLayout) v.findViewById(R.id.GameContainer);
// initialise
circles = new ArrayList<Circle>();
paint = new Paint();
levelScore = 0;
numCircles = numberCircles;
// Get the game container FrameView
int frameW = frame.getWidth();
int frameH = frame.getHeight();
int frameL = frame.getLeft();
int frameT = frame.getTop();
// fill arraylist with random circles
Random random = new Random();
for(int i=0; i<numCircles; i++) {
// generate coords within the frame
int x = random.nextInt((frameL+frameW)-frameL) + frameL;
int y = random.nextInt((frameT+frameH)-frameT) + frameT;
// random radius between 50 and 10
int r = random.nextInt(50-10) + 10;
// add them to the ArrayList
circles.add(new Circle(x, y, r, Color.WHITE));
}
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for(int i=0; i<numCircles; i++) {
Circle c = circles.get(i);
// set colour
paint.setColor(c.getColor());
// draw circle to canvas
canvas.drawCircle(c.getX(), c.getY(), c.getRadius(), paint);
}
}
}
If your custom SurfaceView will have a layout you need to inflate it. On your constructor you have
FrameLayout frame = (FrameLayout) findViewById(R.id.GameContainer);
You are trying to reference a FrameLayout that has not been inflated yet. To inflate the corresponding .xml you need to use a LayoutInflator. You can get a reference to the LayoutInflated via the Context passed in to your SurfaceView. For example like this:
public GameView(Context context, AttributeSet attrs, int numberCircles){
super(context,attrs);
LayoutInflater inflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//replace custom_layout with the name of the .xml file that contains the `FrameLayout` with id R.id.GameContainer
View v = inflater.inflate(R.layout.custom_layout, (ViewGroup) GameView.this.getParent(), true);
FrameLayout frame = (FrameLayout)v.findViewById(R.id.GameContainer);
//The rest of your code...
}
Also, If you are going to add your GameView to an .xml file you need to use the SurfaceView(Context context, AttributeSet attrs) constructor.
Please check your XML that whether you have supplied correct ID for Frame Layout in GameView.java
package com.example.first666;
import com.example.first666.util.SystemUiHider;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* #see SystemUiHider
*/
public class FullscreenActivity extends Activity {
int counter;
Button add, sub;
TextView display;
/**
* Whether or not the system UI should be auto-hidden after
* {#link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;
/**
* If {#link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* If set, will toggle the system UI visibility upon interaction. Otherwise,
* will show the system UI visibility upon interaction.
*/
private static final boolean TOGGLE_ON_CLICK = true;
/**
* The flags to pass to {#link SystemUiHider#getInstance}.
*/
private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
/**
* The instance of the {#link SystemUiHider} for this activity.
*/
private SystemUiHider mSystemUiHider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
counter = 0;
add = (Button) findViewById(R.id.bAdd);
sub = (Button) findViewById(R.id.bSub);
display = (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Your total is " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
display.setText("Your total is " + counter);
}
});
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, contentView,
HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider
.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView
.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE
: View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
// Set up the user interaction to manually show or hide the system UI.
contentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.dummy_button).setOnTouchListener(
mDelayHideTouchListener);
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
Handler mHideHandler = new Handler();
Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
mSystemUiHider.hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
public void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
}
nullpointerexception occurs when processing display = (TextView) findViewById(R.id.tvDisplay); which crashes the app saying 'unfortunately the app has stopped'. How do I fix NullPointerException?
Here's the XML file as requested. Any help appreciated.
<?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:orientation="vertical" >
<TextView
android:id="#+id/tvDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello"
android:textSize="200sp"
android:layout_gravity="center"
android:gravity="center"/>
<Button
android:layout_width="500sp"
android:layout_height="200sp"
android:text="#string/Add"
android:layout_gravity="center"
android:gravity="center"
android:textSize="75sp"
android:id="#+id/bAdd"/>
<Button
android:layout_width="500sp"
android:layout_height="200sp"
android:text="#string/Sub"
android:layout_gravity="center"
android:textSize="75sp"
android:id="#+id/bSub"/>
</LinearLayout>
Here's the LogCat as requested
06-05 14:52:46.269: E/Trace(466): error opening trace file: No such file or directory (2)
06-05 14:52:48.300: D/AndroidRuntime(466): Shutting down VM
06-05 14:52:48.309: W/dalvikvm(466): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
06-05 14:52:48.360: E/AndroidRuntime(466): FATAL EXCEPTION: main
06-05 14:52:48.360: E/AndroidRuntime(466): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.first666/com.example.first666.FullscreenActivity}: java.lang.NullPointerException
06-05 14:52:48.360: E/AndroidRuntime(466): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
06-05 14:52:48.360: E/AndroidRuntime(466): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-05 14:52:48.360: E/AndroidRuntime(466): at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-05 14:52:48.360: E/AndroidRuntime(466): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-05 14:52:48.360: E/AndroidRuntime(466): at android.os.Handler.dispatchMessage(Handler.java:99)
06-05 14:52:48.360: E/AndroidRuntime(466): at android.os.Looper.loop(Looper.java:137)
06-05 14:52:48.360: E/AndroidRuntime(466): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-05 14:52:48.360: E/AndroidRuntime(466): at java.lang.reflect.Method.invokeNative(Native Method)
06-05 14:52:48.360: E/AndroidRuntime(466): at java.lang.reflect.Method.invoke(Method.java:511)
06-05 14:52:48.360: E/AndroidRuntime(466): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-05 14:52:48.360: E/AndroidRuntime(466): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-05 14:52:48.360: E/AndroidRuntime(466): at dalvik.system.NativeStart.main(Native Method)
06-05 14:52:48.360: E/AndroidRuntime(466): Caused by: java.lang.NullPointerException
06-05 14:52:48.360: E/AndroidRuntime(466): at com.example.first666.FullscreenActivity.onCreate(FullscreenActivity.java:62)
06-05 14:52:48.360: E/AndroidRuntime(466): at android.app.Activity.performCreate(Activity.java:5104)
06-05 14:52:48.360: E/AndroidRuntime(466): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-05 14:52:48.360: E/AndroidRuntime(466): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
06-05 14:52:48.360: E/AndroidRuntime(466): ... 11 more
06-05 14:53:28.219: I/Process(466): Sending signal. PID: 466 SIG: 9
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);
does not belongs to the current view hierarchy
If line 62 is add.setOnClickListener(new View.OnClickListener() ...
Then check if this line is returning null:
add = (Button) findViewById(R.id.bAdd);
I am doing an android app and i was thinking of creating a theme option. Well all I was thinking of doing was to allow the user to click on a image button which represented a theme. And when he clicks on it I start a new activity i.e i direct him to the home page. Also i have created a few integer variables which are set to 1 when the user clicks on a button.
Then in the other classes all i do is check if the variables are 1 or not and depending on that i apply the theme. By theme i mean i just change the background wallpaper. But this is not working. I mean the code works but if use an if loop to check the variable values and then apply the effects it causes an error.
Here's the complete code:
package com.example.themetest;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
public class MainActivity extends Activity implements OnClickListener{
ImageButton ib1;
ImageButton ib2;
int water=0;
int fire=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ib1 = (ImageButton) findViewById(R.id.imageButton1);
ib2 = (ImageButton) findViewById(R.id.imageButton2);
ib1.setOnClickListener(this);
ib2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.imageButton1:
water = 1;
Intent wi = new Intent("com.example.themetest.THEME");
startActivity(wi);
break;
case R.id.imageButton2:
fire = 1;
Intent fi = new Intent("com.example.themetest.THEME");
startActivity(fi);
break;
}
}
}
Here's the other class where i check which variable is set to 1 and apply the effect.
package com.example.themetest;
import java.io.InputStream;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.LinearLayout;
public class Theme extends Activity{
MainActivity main;
Resources res;
Drawable drawable;
LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.theme);
if(main.water==1){
res = getResources();
drawable = res.getDrawable(R.drawable.water_theme);
linearLayout = (LinearLayout)findViewById(R.id.ll);
linearLayout.setBackgroundDrawable(drawable);
}
else if(main.fire==1){
res = getResources();
drawable = res.getDrawable(R.drawable.fire_theme);
linearLayout = (LinearLayout)findViewById(R.id.ll);
linearLayout.setBackgroundDrawable(drawable);
}
else{
res = getResources();
drawable = res.getDrawable(R.drawable.ic_launcher);
linearLayout = (LinearLayout)findViewById(R.id.ll);
linearLayout.setBackgroundDrawable(drawable);
}
}
}
I can change the wallpaper without using the if loop, but i want to do it this way which is not working. Can anyone please tell me why?
Log cat:
01-15 12:08:23.339: D/dalvikvm(273): GC_EXTERNAL_ALLOC freed 767 objects / 55936 bytes in 235ms
01-15 12:08:25.539: D/AndroidRuntime(273): Shutting down VM
01-15 12:08:25.539: W/dalvikvm(273): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-15 12:08:25.559: E/AndroidRuntime(273): FATAL EXCEPTION: main
01-15 12:08:25.559: E/AndroidRuntime(273): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.themetest/com.example.themetest.Theme}: java.lang.NullPointerException
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.os.Handler.dispatchMessage(Handler.java:99)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.os.Looper.loop(Looper.java:123)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-15 12:08:25.559: E/AndroidRuntime(273): at java.lang.reflect.Method.invokeNative(Native Method)
01-15 12:08:25.559: E/AndroidRuntime(273): at java.lang.reflect.Method.invoke(Method.java:521)
01-15 12:08:25.559: E/AndroidRuntime(273): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-15 12:08:25.559: E/AndroidRuntime(273): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-15 12:08:25.559: E/AndroidRuntime(273): at dalvik.system.NativeStart.main(Native Method)
01-15 12:08:25.559: E/AndroidRuntime(273): Caused by: java.lang.NullPointerException
01-15 12:08:25.559: E/AndroidRuntime(273): at com.example.themetest.Theme.onCreate(Theme.java:29)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-15 12:08:25.559: E/AndroidRuntime(273): ... 11 more
01-15 12:08:31.089: I/Process(273): Sending signal. PID: 273 SIG: 9
I think the better way to do this is pass the name or code of the theme user selected along with the intent.
This might help: Passing data through Intent and receiving it
You cannot access other activities variables this way, a better way (for example) is to use a constant class..
public class Constants {
public static int water=0;
public staticint fire=0;
}
MainActivity:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.imageButton1:
Constants.water = 1;
Intent wi = new Intent("com.example.themetest.THEME");
startActivity(wi);
break;
case R.id.imageButton2:
Constants.fire = 1;
Intent fi = new Intent("com.example.themetest.THEME");
startActivity(fi);
break;
}
}
Theme:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.theme);
if(Constants.water==1){
res = getResources();
drawable = res.getDrawable(R.drawable.water_theme);
linearLayout = (LinearLayout)findViewById(R.id.ll);
linearLayout.setBackgroundDrawable(drawable);
}
else if(Constants.fire==1){
res = getResources();
drawable = res.getDrawable(R.drawable.fire_theme);
linearLayout = (LinearLayout)findViewById(R.id.ll);
linearLayout.setBackgroundDrawable(drawable);
}
else{
res = getResources();
drawable = res.getDrawable(R.drawable.ic_launcher);
linearLayout = (LinearLayout)findViewById(R.id.ll);
linearLayout.setBackgroundDrawable(drawable);
}
}