Implementing Getextra() and Putextra - java

I am trying to use putextra() and getextra() but my program is crashing after implementing it
Go through my code and let me know my mistake
If I am not using getextra() and putextra() the code is working flawlessly
This is 1st class from where I am getting the value
public class Assess extends ListActivity {
String itm;
ArrayAdapter<String> Adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getListView().setBackgroundResource(R.drawable.background);
Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, getResources()
.getStringArray(R.array.English));
setListAdapter(Adapter);
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
selectItem(pos);
itm = getListView().getItemAtPosition(pos).toString();
// Toast.makeText(getApplicationContext(), "CLicked",
// Toast.LENGTH_SHORT).show();
}
});
}
public void selectItem(int pos) {
switch (pos) {
case 0: {
Intent i;
List<Question> questions = getQuestionSetFromDb();
// Initialise Game with retrieved question set ///
GamePlay c = new GamePlay();
c.setQuestions(questions);
c.setNumRounds(getNumQuestions());
((ChuckApplication) getApplication()).setCurrentGame(c);
// Start Game Now.. //
i = new Intent(this, QuestionActivity.class);
**i.putExtra("itemname", itm);**
//startActivityForResult(i, Constants.PLAYBUTTON);
startActivity(i);
//this.finish();
break;
}
}
}
Now the Second class where I am trying to Pass the item name
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question);
topic1 = i.getStringExtra("itemname");
Log.i("sanket", topic1);
/**
* Configure current game and get question
*/
currentGame = ((ChuckApplication) getApplication()).getCurrentGame();
currentQ = currentGame.getNextQuestion();
RadioGroup rdgb = (RadioGroup) findViewById(R.id.group1);
rdgb.setOnCheckedChangeListener(this);
/**
* Update the question and answer options..
*/
setQuestions();
}
/**
* Method to set the text for the question and answers from the current
* games current question
*/
private void setQuestions() {
// set the question text from current question
String question = Utility.capitalise(currentQ.getQuestion()) + "?";
TextView qText = (TextView) findViewById(R.id.question);
qText.setText(question);
// set the available options
List<String> answers = currentQ.getQuestionOptions();
TextView option1 = (TextView) findViewById(R.id.answer1);
option1.setText(Utility.capitalise(answers.get(0)));
TextView option2 = (TextView) findViewById(R.id.answer2);
option2.setText(Utility.capitalise(answers.get(1)));
TextView option3 = (TextView) findViewById(R.id.answer3);
option3.setText(Utility.capitalise(answers.get(2)));
TextView option4 = (TextView) findViewById(R.id.answer4);
option4.setText(Utility.capitalise(answers.get(3)));
}
/*
* #Override public void onClick(View arg0) { //Log.d("Questions",
* "Moving to next question");
*//**
* validate a checkbox has been selected
*/
/*
* if (!checkAnswer()) return;
*//**
* check if end of game
*/
/*
* if (currentGame.isGameOver()){ //Log.d("Questions",
* "End of game! lets add up the scores.."); //Log.d("Questions",
* "Questions Correct: " + currentGame.getRight()); //Log.d("Questions",
* "Questions Wrong: " + currentGame.getWrong()); Intent i = new
* Intent(this, EndgameActivity.class); startActivity(i); finish(); } else{
* Intent i = new Intent(this, QuestionActivity.class); startActivity(i);
* finish(); } }
*/
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (a > 0) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
return true;
}
}
return super.onKeyDown(keyCode, event);
}
/**
* Check if a checkbox has been selected, and if it has then check if its
* correct and update gamescore
*/
private boolean checkAnswer() {
String answer = getSelectedAnswer();
if (answer == null) {
// Log.d("Questions", "No Checkbox selection made - returning");
return false;
} else {
// Log.d("Questions",
// "Valid Checkbox selection made - check if correct");
if (currentQ.getAnswer().equalsIgnoreCase(answer)) {
// Log.d("Questions", "Correct Answer!");
currentGame.incrementRightAnswers();
} else {
// Log.d("Questions", "Incorrect Answer!");
currentGame.incrementWrongAnswers();
}
return true;
}
}
/**
*
*/
public String getSelectedAnswer() {
RadioButton c1 = (RadioButton) findViewById(R.id.answer1);
RadioButton c2 = (RadioButton) findViewById(R.id.answer2);
RadioButton c3 = (RadioButton) findViewById(R.id.answer3);
RadioButton c4 = (RadioButton) findViewById(R.id.answer4);
if (c1.isChecked()) {
return c1.getText().toString();
}
if (c2.isChecked()) {
return c2.getText().toString();
}
if (c3.isChecked()) {
return c3.getText().toString();
}
if (c4.isChecked()) {
return c4.getText().toString();
}
return null;
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
// Log.d("Questions", "Moving to next question");
a++;
/**
* validate a checkbox has been selected
*/
if (!checkAnswer())
return;
/**
* check if end of game
*/
if (currentGame.isGameOver()) {
// db.open();
// db.insertOptions(topic1, currentGame.getRight(), month);
// Log.d("Questions", "End of game! lets add up the scores..");
// Log.d("Questions", "Questions Correct: " +
// currentGame.getRight());
// Log.d("Questions", "Questions Wrong: " + currentGame.getWrong());
Intent i = new Intent(this, EndgameActivity.class);
startActivity(i);
finish();
// db.close();
} else {
Intent i = new Intent(this, QuestionActivity.class);
startActivity(i);
finish();
}
}
}
Or is there any other way to carry data from one page to other page other than putextra() and getextra().
Here is my LOGCAT
02-04 10:33:35.697: E/AndroidRuntime(1776): FATAL EXCEPTION: main
02-04 10:33:35.697: E/AndroidRuntime(1776): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tmm.android.chuck/com.tmm.android.chuck.QuestionActivity}: java.lang.NullPointerException: println needs a message
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.os.Handler.dispatchMessage(Handler.java:99)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.os.Looper.loop(Looper.java:130)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-04 10:33:35.697: E/AndroidRuntime(1776): at java.lang.reflect.Method.invokeNative(Native Method)
02-04 10:33:35.697: E/AndroidRuntime(1776): at java.lang.reflect.Method.invoke(Method.java:507)
02-04 10:33:35.697: E/AndroidRuntime(1776): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-04 10:33:35.697: E/AndroidRuntime(1776): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-04 10:33:35.697: E/AndroidRuntime(1776): at dalvik.system.NativeStart.main(Native Method)
02-04 10:33:35.697: E/AndroidRuntime(1776): Caused by: java.lang.NullPointerException: println needs a message
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.util.Log.println_native(Native Method)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.util.Log.i(Log.java:158)
02-04 10:33:35.697: E/AndroidRuntime(1776): at com.tmm.android.chuck.QuestionActivity.onCreate(QuestionActivity.java:48)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
02-04 10:33:35.697: E/AndroidRuntime(1776): ... 11 more

Try out to get the string as below :
First change your onItemClickListener as below: You need to assign value to your itm variable and then call the selectItem() method so that your itm variable is not null.
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
itm = getListView().getItemAtPosition(pos).toString();
selectItem(pos);
}
});
Get the String in your another activity as below:
String topic1 =getIntent().getStringExtra("itemname");

first initialize the itm String in OnItemClickListener implementation of ListView, then call selectItem() method.
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
itm = getListView().getItemAtPosition(pos).toString(); // initialize it first.
selectItem(pos);
// Toast.makeText(getApplicationContext(), "CLicked",
// Toast.LENGTH_SHORT).show();
}
});
and in reeiving Activity, get this String as
topic1 = getIntent().getStringExtra("itemname");

You should read string from getIntent(). Read like below
topic1 = getIntent().getStringExtra("itemname");

It must be a NullPointerException because "itm" will always be null in that scope
Why don't you make it like this:
itm = getListView().getItemAtPosition(pos).toString();
selectItem(pos,itm);
And then pass it as extra in this method
Hope that helps :)

Related

Exception when trying to send a message to firebase server

Can you please find out what is wrong with this code?
public class NewMessageActivity extends AppCompatActivity {
private DatabaseReference mDatabaseReference;
String mDisplayName = "John";
EditText mNewMessageField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final EditText mNewMessageField = (EditText) findViewById(R.id.newMessageText);
setContentView(R.layout.activity_new_message);
ImageButton mSendButton = (ImageButton) findViewById(R.id.sendButton);
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
finish();
}
});
}
private void sendMessage(){
mDatabaseReference= FirebaseDatabase.getInstance().getReference();
String input = mNewMessageField.getText().toString();
SingleMessage singleMessage = new SingleMessage(input, mDisplayName);
mDatabaseReference.child("messages").push().setValue(singleMessage);
}
}
Immediately after I press the send button, the app stops working and I get this error message:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com..NewMessageActivity.sendMessage(NewMessageActivity.java:42)
at com..NewMessageActivity.access$000(NewMessageActivity.java:14)
at com.***.NewMessageActivity$1.onClick(NewMessageActivity.java:33)
at android.view.View.performClick(View.java:4209)
at android.view.View$PerformClick.run(View.java:17457)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5341)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:929)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
at dalvik.system.NativeStart.main(Native Method)
11-28 20:05:51.566 508-527/? E/AppErrorDialog: Failed to get ILowStorageHandle instance
You need to call setContentView() before you search for the EditText widget. You also must use the instance of mNewMessageField declared at package level. Don't declare a new instance in onCreate().
setContentView(R.layout.activity_new_message);
mNewMessageField = (EditText) findViewById(R.id.newMessageText); // <= CHANGED
if (mNewMessageField == null) {
System.out.println("mNewMessageField is NULL");
}
To get more clues, add this debug output:
private void sendMessage(){
mDatabaseReference= FirebaseDatabase.getInstance().getReference();
if (mNewMessageField == null) {
System.out.println("mNewMessageField is NULL");
}
Editable ed = mNewMessageField.getText();
if (ed == null) {
System.out.println("Editable is NULL");
}
String input = mNewMessageField.getText().toString();
System.out.println("input=" + input);
SingleMessage singleMessage = new SingleMessage(input, mDisplayName);
mDatabaseReference.child("messages").push().setValue(singleMessage);
}

FatalCrash when I click on a Button

I have this RemoteCar App which has the Buttons,
"LOCK" -> leads you to another Acitivity.
"LOCATION" -> leads you to another Activity.
"START ENGINE" -> Lets you click on it and it changes the txt into
"ENGINE RUNNING".
"REFUEL" -> lets you refuel and increments my ProgressBar(FuelBar).
So the problem I have is that I can't click on START ENGINE or REFUEL anymore since the App keeps crashing for reasons I can not resolve, yet. I can easily click on LOCATION and LOCK those work perfectly fine.
Here I have the ErrorMessage:
05-21 13:39:52.887 1869-1869/? W/gralloc_ranchu: Gralloc pipe failed 05-21 13:39:52.897 1869-1869/? D/OpenGLRenderer: Enabling debug mode 0 05-21 13:39:53.097 1402-1429/system_process I/ActivityManager: Displayed com.example.schwarzerritter.remotecv02/.MainActivity: +546ms 05-21 13:39:53.297 1402-1429/system_process D/gralloc_ranchu: gralloc_unregister_buffer: exiting HostConnection (is buffer-handling thread) 05-21 13:39:56.857 1402-1486/system_process E/ThrottleService: problem during onPollAlarm: java.lang.IllegalStateException: problem parsing stats: java.io.FileNotFoundException: /proc/net/xt_qtaguid/iface_stat_all: open failed: ENOENT (No such file or directory) 05-21 13:42:00.387 1869-1869/? D/AndroidRuntime: Shutting down VM 05-21 13:42:00.387 1869-1869/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa6661228) 05-21 13:42:00.387 1869-1869/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4084) 
at android.view.View$PerformClick.run(View.java:16966) 
at android.os.Handler.handleCallback(Handler.java:615) 
at android.os.Handler.dispatchMessage(Handler.java:92) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.NumberFormatException: Invalid int: "AC : 18"
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parse(Integer.java:375)
at java.lang.Integer.parseInt(Integer.java:366)
at java.lang.Integer.parseInt(Integer.java:332)
at com.example.schwarzerritter.remotecv02.MainActivity.onClick(MainActivity.java:41)
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:4084) 
at android.view.View$PerformClick.run(View.java:16966) 
at android.os.Handler.handleCallback(Handler.java:615) 
at android.os.Handler.dispatchMessage(Handler.java:92) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511)
MainActivity.Java:
public class MainActivity extends AppCompatActivity {
public ProgressBar fuelBar;
public Button lockButton;
public Button engButton;
public Button refuelButton;
public Button plusButton;
public Button minusButton;
public Button locationButton;
public SeekBar seekBarButton;
public TextView seekText;
int incFuel = 0;
int acNum = 0;
public void onClick(View v) {
engButton = (Button) findViewById(R.id.engB);
refuelButton = (Button) findViewById(R.id.refuelB);
fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
acNum = Integer.parseInt(seekText.getText().toString());
switch (v.getId()) {
case engB:
if (engButton.getText() == "ENGINE RUNNING") {
engButton.setText("START ENGINE");
} else {
if (fuelBar.getProgress() > 0) {
Toast.makeText(MainActivity.this,"Starting engine..",Toast.LENGTH_SHORT).show();
engButton.setText("ENGINE RUNNING");
if (fuelBar.getProgress() >= 10) {
incFuel = fuelBar.getProgress();
incFuel -= 10;
fuelBar.setProgress(incFuel);
if (fuelBar.getProgress() < 100)
refuelButton.setText("REFUEL");
}
} else
if(fuelBar.getProgress() == 0) {
Toast.makeText(MainActivity.this, "No fuel", Toast.LENGTH_SHORT).show();
engButton.setText("EMPTY GASTANK");
}else
engButton.setText("START ENGINE");
}
break;
case refuelB:
if (fuelBar.getProgress() == 0) {
engButton.setText("START ENGINE");
incFuel = fuelBar.getProgress();
incFuel += 10;
fuelBar.setProgress(incFuel);
} else if (fuelBar.getProgress() < 100) {
incFuel = fuelBar.getProgress();
incFuel += 10;
fuelBar.setProgress(incFuel);
} else {
Toast.makeText(MainActivity.this,"Tank is full",Toast.LENGTH_SHORT).show();
refuelButton.setText("FULL");
}
break;
}
}
public void seek_bar(){
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
seekText.setText("AC : " + (seekBarButton.getProgress() + 18));
seekText.setText("AC : " + (seekBarButton.getProgress() + 18));
seekBarButton.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressNum;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressNum = progress;
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
});
}
public void lockPage() {
lockButton = (Button) findViewById(R.id.lockB);
lockButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent lockPage = new Intent(MainActivity.this, lockDoor.class);
startActivity(lockPage);
}
});
}
public void locationPage() {
locationButton = (Button) findViewById(R.id.locationB);
locationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent locationPage = new Intent(MainActivity.this, location.class);
startActivity(locationPage);
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationButton = (Button) findViewById(R.id.locationB);
lockButton = (Button) findViewById(R.id.lockB);
engButton = (Button) findViewById(R.id.engB);
refuelButton = (Button) findViewById(R.id.refuelB);
fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
fuelBar.setMax(100);
fuelBar.setProgress(30);
refuelButton.setText(R.string.refuelB);
lockButton.setText(R.string.lockB);
locationButton.setText(R.string.locationB);
engButton.setText(R.string.engB);
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
int acNum;
seek_bar();
lockPage();
locationPage();
}
}
java.lang.NumberFormatException: Invalid int: "AC : 18"
at com.example.schwarzerritter.remotecv02.MainActivity.onClick(MainActivity.java:41)
You are trying to convert the string AC : 18 to an integer in MainActivity.java line 41.
(Reading error messages helps)

Why am I getting an java.lang.IllegalArgumentException: the bind value at index 1 is null in this case?

I know what an java.lang.IllegalArgumentException: the bind value at index 1 is null means and what causes the error. I my case I am still unable to find the reason for such an error in my case.
So, what do I intend to achieve?
I have 4 columns in my SQLite database table. I want to find the sum of each column and again find the sum of these four results. The row values for sum is filtered based on the product name chosen by the user from the autoCompleteTextView.
Where am I getting the error?
my stackTrace says I am getting the error in the line beginning with Cursor c = db.query... in the below code. The following code is part of my db file of my android project.
public int addPurchaseQuantity(String itemName) {
SQLiteDatabase db = helper.getReadableDatabase();
int result = 0;
String selection = VivzHelper.COLUMN_ADD_PURCHASE_ITEM_NAME + " =? ";
String[] selectionArgs = {itemName};
Cursor c = db.query(VivzHelper.ADD_PURCHASE_TABLE,
new String[]{"sum(" + VivzHelper.COLUMN_ADD_PURCHASE_ITEM_QUANTITY + ")"},
selection,
selectionArgs,
null,
null,
null);
if (c.moveToFirst()) {
result = c.getInt(0);
}
c.close();
return result;
}
The itemName is obtained from the autoCompleteTextView based on user selection.
String[] autoCompleteName = vivzHelper.getInventoryNameFilterBySupplierName(vivzHelper.getSupplierID(param1));
ArrayAdapter<String> NameAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, autoCompleteName);
addPurchaseItemName.setThreshold(1);// starts working from first char
addPurchaseItemName.setAdapter(NameAdapter);
addPurchaseItemName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
itemName = String.valueOf(arg0.getItemAtPosition(arg2));
}
});
My stackTrace is also pointing to the following code of the java activity file.
int purchaseQty = vivzHelper.addPurchaseQuantity(itemName);
Here is my stackTrace
04-21 00:09:58.274 21975-21975/com.example.bharathduraiswamy.comboedittext E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bharathduraiswamy.comboedittext/com.example.bharathduraiswamy.comboedittext.AddPurchase}: java.lang.IllegalArgumentException: the bind value at index 1 is null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2313)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
at android.app.ActivityThread.access$600(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5336)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: the bind value at index 1 is null
at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:164)
at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:200)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200)
at com.example.bharathduraiswamy.comboedittext.VivzDatabaseAdapter.addPurchaseQuantity(VivzDatabaseAdapter.java:2011)
at com.example.bharathduraiswamy.comboedittext.AddPurchase.aggregateQty(AddPurchase.java:531)
at com.example.bharathduraiswamy.comboedittext.AddPurchase.onCreate(AddPurchase.java:133)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2277)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
at android.app.ActivityThread.access$600(ActivityThread.java:156)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:153)
        at android.app.ActivityThread.main(ActivityThread.java:5336)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
        at dalvik.system.NativeStart.main(Native Method)
Can someone tell me where actually am I going wrong?
Update 01 : onCreate() from AddPurchase activity added
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_purchase);
// Set a toolbar to replace the action bar
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar_addPurchase);
setSupportActionBar(myToolbar);
myToolbar.setNavigationIcon(R.drawable.logo);
//Disable the Toolbar Title
getSupportActionBar().setDisplayShowTitleEnabled(false);
// Adding UP icon for Setting Activity
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
SharedPreferences myPreferences = getSharedPreferences("sharedSupplierData", Context.MODE_PRIVATE);
param1 = myPreferences.getString("sharedSupplierName", DEFAULT);
if (param1.equals(DEFAULT)) {
Message.message(this, "No data was found");
}
addPurchaseItemName = (AutoCompleteTextView) findViewById(R.id.addPurchaseProductName);
addPurchaseItemQty = (EditText) findViewById(R.id.addPurchaseProductQuantity);
addPurchaseCostPrice = (EditText) findViewById(R.id.addPurchaseCostPrice);
addPurchaseSalePrice = (EditText) findViewById(R.id.addPurchaseSalePrice);
myDate = (TextView) findViewById(R.id.addPurchaseDatum);
purchaseSum = (TextView) findViewById(R.id.addPurchaseSum);
primarySpinner = (Spinner) findViewById(R.id.toolbar_spinner);
vivzHelper = new VivzDatabaseAdapter(this);
showDialogOnButtonClick();
populateListView();
String[] autoCompleteName = vivzHelper.getInventoryNameFilterBySupplierName(vivzHelper.getSupplierID(param1));
ArrayAdapter<String> NameAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, autoCompleteName);
addPurchaseItemName.setThreshold(1);// starts working from first char
addPurchaseItemName.setAdapter(NameAdapter);
addPurchaseItemName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
itemName = String.valueOf(arg0.getItemAtPosition(arg2));
}
});
Message.message(this, ("Item Name = " + itemName));
aggregateQty();
//Initializing an Adapter
ArrayAdapter<String> toolbar_adapter = new ArrayAdapter<>(
this, android.R.layout.simple_spinner_dropdown_item, primarySpinner_array);
//Providing the Resource xml for Drop down Layout
toolbar_adapter.setDropDownViewResource(R.layout.custom_simple_spinner_dropdown_item);
primarySpinner.setAdapter(toolbar_adapter);
//Setting a default Spinner value before onItemClick
primarySpinner.setSelection(0);
//Initializing an OnItemClick Listener for Spinner Item
primarySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int position_toolbar = primarySpinner.getSelectedItemPosition();
//Changing Spinner TextSize and Text Color
((TextView) arg0.getChildAt(0)).setTextColor(Color.WHITE);
((TextView) arg0.getChildAt(0)).setTextSize(20);
//Changing Spinner Pointer Color - partially effective
primarySpinner.getBackground().setColorFilter(getResources().getColor(R.color.White), PorterDuff.Mode.SRC_ATOP);
//Using Switch to move to other Activities
Intent intent_spinner;
switch (arg2) {
case 1:
intent_spinner = new Intent(AddPurchase.this, SupplierDues.class);
AddPurchase.this.startActivity(intent_spinner);
break;
case 2:
intent_spinner = new Intent(AddPurchase.this, SupplierReturns.class);
AddPurchase.this.startActivity(intent_spinner);
break;
case 3:
intent_spinner = new Intent(AddPurchase.this, SupplierBalanceSheet.class);
AddPurchase.this.startActivity(intent_spinner);
break;
case 4:
intent_spinner = new Intent(AddPurchase.this, AddSupplier.class);
AddPurchase.this.startActivity(intent_spinner);
break;
default:
break;
}
//Changing Spinner Pointer Color - partially effective
primarySpinner.getBackground().setColorFilter(getResources().getColor(R.color.White), PorterDuff.Mode.SRC_ATOP);
//Setting a default Spinner value after onItemClick
primarySpinner.setSelection(0);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
Update 02 : aggregateQty() from when the addPurchaseQuantity() is called
public void aggregateQty() {
int purchaseQty = vivzHelper.addPurchaseQuantity(itemName);
int saleQty = vivzHelper.addSaleQuantity(itemName);
int supplierRtnQty = vivzHelper.returnedToSupplierQuantity(itemName, rtnPrice);
int supplierRtnScrapQty = vivzHelper.returnedToSupplierForScrapQuantity(itemName, rtnPrice);
int customerRtnQty = vivzHelper.returnedByCustomerQuantity(itemName, rtnPrice);
if (itemName.length() != 0) {
availableQuantity = String.valueOf(purchaseQty - saleQty - supplierRtnQty - supplierRtnScrapQty + customerRtnQty);
addPurchaseItemQty.setHint(availableQuantity);
Message.message(this, ("Item Name = " + itemName + "\n" +
"Purchase Quantity = " + purchaseQty + "\n" +
"Sale Quantity = " + saleQty + "\n" +
"Supplier Return Quantity = " + supplierRtnQty + "\n" +
"Customer Return Quantity = " + customerRtnQty));
} else {
Message.message(this, "Please Select an Item");
}
}
itemName is null in addPurchaseQuantity() invocation and thus why when SQLite tries to use it to replace the selection argument ('?') you receive this exception.
Try setting itemName to a known value and check the results.
EDIT
You should test every method independently so you can easily discover the errors or bugs. Learn to apply unit testing as described in Testing Fundamentals.
Then, you'll discover that the problem is reduced to get the text value from an AutoCompletTextView which you can find plenty of examples out there (i.e. How to get string text from AutoCompleteTextView?).
I would try removing the sum in : new String[]{"sum(" + VivzHelper.COLUMN_ADD_PURCHASE_ITEM_QUANTITY + ")"},
See if bind works.

MY android application is crashing when I click on the register btn

While running my application I go to click on the register button and the application is crashing. Please find Log-cat below (if anyone could explain the best way to use log-cat that would be great) I have also included the register Java. If there is any more information you need comment and I will update this message.
04-23 21:52:07.835: D/libEGL(28588): loaded /system/lib/egl/libEGL_mali.so
04-23 21:52:07.875: D/libEGL(28588): loaded /system/lib/egl/libGLESv1_CM_mali.so
04-23 21:52:07.885: D/libEGL(28588): loaded /system/lib/egl/libGLESv2_mali.so
04-23 21:52:07.895: E/(28588): Device driver API match
04-23 21:52:07.895: E/(28588): Device driver API version: 23
04-23 21:52:07.895: E/(28588): User space API version: 23
04-23 21:52:07.895: E/(28588): mali: REVISION=Linux-r3p2-01rel3 BUILD_DATE=Wed Oct 9 21:05:57 KST 2013
04-23 21:52:08.000: D/OpenGLRenderer(28588): Enabling debug mode 0
04-23 21:52:24.925: D/AndroidRuntime(28588): Shutting down VM
04-23 21:52:24.925: W/dalvikvm(28588): threadid=1: thread exiting with uncaught exception (group=0x41ba8700)
04-23 21:52:24.930: E/AndroidRuntime(28588): FATAL EXCEPTION: main
04-23 21:52:24.930: E/AndroidRuntime(28588): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.loggedin/com.loggedin.Register}: java.lang.NullPointerException
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.ActivityThread.access$700(ActivityThread.java:159)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.os.Handler.dispatchMessage(Handler.java:99)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.os.Looper.loop(Looper.java:176)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.ActivityThread.main(ActivityThread.java:5419)
04-23 21:52:24.930: E/AndroidRuntime(28588): at java.lang.reflect.Method.invokeNative(Native Method)
04-23 21:52:24.930: E/AndroidRuntime(28588): at java.lang.reflect.Method.invoke(Method.java:525)
04-23 21:52:24.930: E/AndroidRuntime(28588): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
04-23 21:52:24.930: E/AndroidRuntime(28588): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
04-23 21:52:24.930: E/AndroidRuntime(28588): at dalvik.system.NativeStart.main(Native Method)
04-23 21:52:24.930: E/AndroidRuntime(28588): Caused by: java.lang.NullPointerException
04-23 21:52:24.930: E/AndroidRuntime(28588): at com.loggedin.Register.onCreate(Register.java:83)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.Activity.performCreate(Activity.java:5372)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
the following code is the Register page
package com.loggedin;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.loggedin.internal.DatabaseHandler;
import com.loggedin.internal.UserFunctions;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Register extends Activity {
/**
* JSON Response node names.
**/
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "id";
private static String KEY_FIRSTNAME = "FirstName";
private static String KEY_LASTNAME = "LastName";
private static String KEY_USERNAME = "Username";
private static String KEY_EMAIL = "email";
private static String KEY_DOB = "DOB";
private static String KEY_CREATED_AT = "created_at";
private static String KEY_ERROR = "error";
/**
* Defining layout items.
**/
EditText inputFirstName;
EditText inputLastName;
EditText inputUsername;
EditText inputEmail;
EditText inputDOB;
EditText inputPassword;
Button btnRegister;
TextView registerErrorMsg;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
/**
* Defining all layout items
**/
inputFirstName = (EditText) findViewById(R.id.FirstName);
inputLastName = (EditText) findViewById(R.id.LastName);
inputUsername = (EditText) findViewById(R.id.Username);
inputEmail = (EditText) findViewById(R.id.email);
inputDOB = (EditText) findViewById(R.id.DOB);
inputPassword = (EditText) findViewById(R.id.Password);
btnRegister = (Button) findViewById(R.id.registerbtn1);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
/**
* Button which Switches back to the login screen on clicked
**/
Button login = (Button) findViewById(R.id.bktologinbtn);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Login.class);
startActivityForResult(myIntent, 0);
finish();
}
});
/**
* Register Button click event.
* A Toast is set to alert when the fields are empty.
* Another toast is set to alert Username must be 5 characters.
**/
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ( ( !inputUsername.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) && ( !inputFirstName.getText().toString().equals("")) && ( !inputLastName.getText().toString().equals("")) && ( !inputDOB.getText().toString().equals("")) && ( !inputEmail.getText().toString().equals("")) )
{
if ( inputUsername.getText().toString().length() > 4 ){
InternetAsync(view);
}
else
{
Toast.makeText(getApplicationContext(),
"Username should be minimum 5 characters", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(),
"One or more fields are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Async Task to check whether internet connection is working
**/
private class InternetCheck extends AsyncTask<String, Boolean, Boolean> {
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(Register.this);
nDialog.setMessage("Loading..");
nDialog.setTitle("Checking Network");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected Boolean doInBackground(String... args){
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessRegister().execute();
}
else{
nDialog.dismiss();
registerErrorMsg.setText("Error in Network Connection");
}
}
}
private class ProcessRegister extends AsyncTask <String, String, JSONObject>{
/**
* Defining Process dialog
**/
private ProgressDialog pDialog;
String email,Password,FirstName,LastName,DOB,Username;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputUsername = (EditText) findViewById(R.id.Username);
inputPassword = (EditText) findViewById(R.id.Password);
FirstName = inputFirstName.getText().toString();
LastName = inputLastName.getText().toString();
email = inputEmail.getText().toString();
DOB = inputDOB.getText().toString();
Username= inputUsername.getText().toString();
Password = inputPassword.getText().toString();
pDialog = new ProgressDialog(Register.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Registering ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(FirstName, LastName, DOB, email, Username, Password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
/**
* Checks for success message.
**/
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
String red = json.getString(KEY_ERROR);
if(Integer.parseInt(res) == 1){
pDialog.setTitle("Getting Data");
pDialog.setMessage("Loading Info");
registerErrorMsg.setText("Successfully Registered");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/**
* Removes all the previous data in the SQlite database
**/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/**
* Stores registered data in SQlite Database
* Launch Registered screen
**/
Intent registered = new Intent(getApplicationContext(),Registered.class);
/**
* Close all views before launching Registered screen
**/
registered.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(registered);
finish();
}
else if (Integer.parseInt(red) ==2){
pDialog.dismiss();
registerErrorMsg.setText("User already exists");
}
else if (Integer.parseInt(red) ==3){
pDialog.dismiss();
registerErrorMsg.setText("Invalid Email id");
}
}
else{
pDialog.dismiss();
registerErrorMsg.setText("Error occured in registration");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public void InternetAsync(View view){
new InternetCheck().execute();
}
}
Some advice when using logcat...
E/AndroidRuntime(28588): Caused by: java.lang.NullPointerException
E/AndroidRuntime(28588): at
com.loggedin.Register.onCreate(Register.java:83)
You can always do a quick text search checking out the caused By: you can find out where you went wrong.Logcat also shows where the error was thrown too in your case line #83.
I'd recommend looking into how to use the debugger properly too, it is pretty important:
http://forum.xda-developers.com/showthread.php?t=1726238
http://www.vogella.com/tutorials/AndroidLogging/article.html
As Mike already said, debugger can really help you find the issue.
In this case, the line is:
btnRegister.setOnClickListener(new View.OnClickListener() {
The problem is when you use findViewById:
public View findViewById (int id)
Added in API level 1
Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle).
Returns
The view if found or null otherwise.
This means that findViewById returns a null pointer :) so, check your id in the XML layout.
The error is obvious and ppl correctly said regarding using debugger and logcat..
Anyways following are my views :-
1. plz cross check your xml file activity_register.xml dat it has the id which you are using here.
since the error is happening in onclick of the button and then try to capture everything inside onlick in exception using try - catch also surrond the whole button click inside try-catch . add two Toast with different msgs as to identify where the exception is raised.
also u can simply add Log msg like this Log.e("IS_REGISTER_BUTTON_NULL","Value : " +btnRegister) in on create after getting the id if its not null it will write some character other then null. also remove everything inside the onlick and see for each string values u r taking like
String uName=inputUsername.getText().toString();
String pWd=inputPassword.getText().toString();
.
.
.
Log.e("CHECKING_IF_STRING_ARE_NULL",uName+" "+pWd+" "+eMail+.....);
thx

EditText.getText().toString() crashes

In my android application , I have 3 dialogue boxes in which the user puts info into 3 editTexts and it will display the one of the data onto another class/page after it randomly picks which data to choose.
This is my mainClass
public class MainActivity extends Activity {
//Variables are displayed in this area
String choices[] = new String[3];
//EditText editText;
//EditText editText2;
//EditText editText3;
Button mainButton ;
Random rand = new Random();
int finalChoice;
String displayChoice = "";
EditText editText ;
EditText editText2;
EditText editText3;
EditText editText4;
String test;
int count = 3;
//--------------------------- --------------------------------------------------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Makes Button
setContentView(R.layout.activity_main);
declareTextBox();
setButton();
String choice1 = editText.getText().toString();
String choice2 = editText2.getText().toString();
String choice3 = editText3.getText().toString();
choices[0] = choice1; //pass from click button to method.
choices[1] = choice2;
choices[2] = choice3;
finalChoice =rand.nextInt(2);
}
public void setButton()
{
final Button mainbutton = (Button) findViewById(R.id.mainButton);
mainbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
test = ((EditText) findViewById(R.id.editText4)).getText().toString();
// count++;
//retChoice();
// loadScreen();
Intent i = new Intent(MainActivity.this, resultScreen.class);
i.putExtra("display" , displayChoice);
Intent intent = new Intent(MainActivity.this,loadingScreen.class);
//start the second Activity
MainActivity.this.startActivity(intent);
}
});
}
public void declareTextBox()
{
editText = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
editText3 = (EditText) findViewById(R.id.editText3);
}
public void getString(String finalChoice)
{
finalChoice = displayChoice;
}
public String retChoice()
{
displayChoice = choices[finalChoice];
return displayChoice;
}
public void clearText()
{
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
editText.setText(" ");
}
});
editText2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
editText2.setText(" ");
}
});
editText3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
editText3.setText(" ");
}
});
}
public void getText2()
{
}
public void getText()
{
}
#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;
}
}
This is my Display class :
public class resultScreen extends Activity {
MainActivity ma = new MainActivity();
//Method supposedly retrieves the string data from MainActivity Class but somehow displayed null instead.
//Find a way to keep the string variable when transfering from one class to another class.
String finalResult = ma.retChoice();
public void onCreate(Bundle resultScreen){
super.onCreate(resultScreen);
setContentView(R.layout.resultscreen);
//ma.displayChoice.toString();
String str = finalResult;
TextView text = (TextView) findViewById(R.id.textView1);
text.setText(str);
final Button backbutton = (Button) findViewById(R.id.backButton);
backbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Intent intent = new Intent(resultScreen.this,MainActivity.class);
resultScreen.this.startActivity(intent);
}
});
}
}
And this is my loading screen class right after the main button is clicked
public class loadingScreen extends Activity{
protected void onCreate(Bundle loadingScreen) {
// TODO Auto-generated method stub
super.onCreate(loadingScreen);
setContentView(R.layout.loadingscreen);
//If sound clip 20 sec long we don't want to carryit outside next class
// A timer thread looking for "run" method
Thread timer = new Thread()
{
public void run() {
try {
//this is how many mil sec
sleep(8000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent intent = new Intent(loadingScreen.this, resultScreen.class);
loadingScreen.this.startActivity(intent);
loadingScreen.this.finish();
}
}
};
timer.start();
}
}
My app crashes a few seconds into the loading screen when the program attempts to display the data on the resultScreen.
Here's my logCat
05-17 22:32:54.446: D/AndroidRuntime(1181): Shutting down VM
05-17 22:32:54.446: W/dalvikvm(1181): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
05-17 22:32:54.636: E/AndroidRuntime(1181): FATAL EXCEPTION: main
05-17 22:32:54.636: E/AndroidRuntime(1181): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.choiceprototest/com.example.choiceprototest.resultScreen}: java.lang.NullPointerException
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.os.Handler.dispatchMessage(Handler.java:99)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.os.Looper.loop(Looper.java:137)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.ActivityThread.main(ActivityThread.java:5039)
05-17 22:32:54.636: E/AndroidRuntime(1181): at java.lang.reflect.Method.invokeNative(Native Method)
05-17 22:32:54.636: E/AndroidRuntime(1181): at java.lang.reflect.Method.invoke(Method.java:511)
05-17 22:32:54.636: E/AndroidRuntime(1181): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-17 22:32:54.636: E/AndroidRuntime(1181): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-17 22:32:54.636: E/AndroidRuntime(1181): at dalvik.system.NativeStart.main(Native Method)
05-17 22:32:54.636: E/AndroidRuntime(1181): Caused by: java.lang.NullPointerException
05-17 22:32:54.636: E/AndroidRuntime(1181): at com.example.choiceprototest.MainActivity.retChoice(MainActivity.java:101)
05-17 22:32:54.636: E/AndroidRuntime(1181): at com.example.choiceprototest.resultScreen.<init>(resultScreen.java:18)
05-17 22:32:54.636: E/AndroidRuntime(1181): at java.lang.Class.newInstanceImpl(Native Method)
05-17 22:32:54.636: E/AndroidRuntime(1181): at java.lang.Class.newInstance(Class.java:1319)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
05-17 22:32:54.636: E/AndroidRuntime(1181): ... 11 more
05-17 22:33:03.385: I/Process(1181): Sending signal. PID: 1181 SIG: 9
05-17 22:33:05.435: E/Trace(1204): error opening trace file: No such file or directory (2)
Thanks guys.
I believe I see the problem. You are trying to access your Array but it is an instance variable instead of static so it is being killed off when you exit your Activity. You can either put them in a static class and access them that way or pass a String variable through your Intent, depending on what you need.
If you have the value of the String you need when you leave MainActivity then I would probably just pass it through your Intent. If the value depended on something in one of your other Activities then I would consider putting it in a separate class but it doesn't look like that's what you need here
Edit
You are already doing it here, kind of
Intent i = new Intent(MainActivity.this, resultScreen.class);
i.putExtra("display" , displayChoice);
Intent intent = new Intent(MainActivity.this,loadingScreen.class);
But you aren't starting the Activity that would get the String
i.putExtra("display" , displayChoice);
that line would pass a String with key "displpay" and value of displayChoice, although I think that value is an empty String at that point, but you don't start that Activity. I'm lost on how your flow is suppose to work but basically you would do something like this
String displayChoice = "testValue"; // some arbitrary value--whatever you need to send
Intent i = new Intent(MainActivity.this, resultScreen.class); // create the Intent
i.putExtra("display" , displayChoice); // add the extra
startActivity(i); //start the Activity
then to get the value inside resultScreen in onCreate()
Intent recIntent = getIntent(); // get the Intent that started this Activity
String value = recIntent.getStringExtra("display"); // get the value using the key
// value now equals "testValue"
I think your app chash because you have an ANR: "Application Not Responding" because you are running a long procces inside the UIThread. (onCreate() method is form the UIThread)
Use rather as an Asyntack for your sleeping thread or one handler (with messages).
If you need more I can edit your code tomorrow.

Categories

Resources