I'm trying to launch an activity using intents and setting values in TextViews in the launched activity, but when I try to do that my app crashes. Heres the activity I'm trying to launch. It crashes when i try to set the text in the last two code lines
public class GameOver extends Activity {
TextView correctTxt;
TextView incorrectTxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
int correct = intent.getIntExtra("correct", 0);
int incorrect = intent.getIntExtra("incorrect", 0);
correctTxt = (TextView)findViewById(R.id.correct_txt);
incorrectTxt = (TextView)findViewById(R.id.incorrect_txt);
correctTxt.setText("" + correct);
incorrectTxt.setText("" + incorrect);
}
}
And the activity that's launching. I make use of the intent in the trueButton onClickListener method:
package com.example.beithia.geotest;
import android.app.Activity;
import java.util.*;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;
public class TestActivity extends Activity {
private Button trueButton;
private Button falseButton;
private TextView questionTextView;
private TextView correctNum;
private TextView incorrectNum;
private TextView avgScore;
int numOfCorrect = 0;
int numOfIncorrect = 0;
double num = 1;
private TrueFalse[] questionBank = new TrueFalse[] {
new TrueFalse(R.string.question_oceans, true),
new TrueFalse(R.string.question_mideast, false),
new TrueFalse(R.string.question_americas, true),
new TrueFalse(R.string.question_asia,true),
new TrueFalse(R.string.question_channel_islands,true),
new TrueFalse(R.string.question_china,false),
new TrueFalse(R.string.question_mexico,true),
new TrueFalse(R.string.question_turkey,false),
new TrueFalse(R.string.question_everest,false),
new TrueFalse(R.string.question_colombia,false),
new TrueFalse(R.string.question_vatican,true),
new TrueFalse(R.string.question_nile,true),
};
private int currentIndex = 0;
private void updateQuestion() {
int question = questionBank[currentIndex].getQuestion();
questionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = questionBank[currentIndex].isTrueQuestion();
int msgId = 0;
if (userPressedTrue == answerIsTrue) {
msgId = R.string.correct_toast;
numOfCorrect++;
}
else {
msgId = R.string.incorrect_toast;
numOfIncorrect++;
}
Toast.makeText(this,msgId,Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
questionTextView = (TextView)findViewById(R.id.question_text_view);
correctNum = (TextView)findViewById(R.id.correct_num);
incorrectNum = (TextView)findViewById(R.id.incorrect_num);
avgScore = (TextView)findViewById(R.id.average_score);
trueButton = (Button) findViewById(R.id.true_button);
trueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
double score = (numOfCorrect / num) * 100;
currentIndex = (currentIndex + 1) % questionBank.length;
correctNum.setText("Correct: " + numOfCorrect);
incorrectNum.setText("Incorrect: " + numOfIncorrect);
avgScore.setText("Score: " + String.format("%.2f", score) + "%");
updateQuestion();
num++;
if(num > 10) {
Intent intent = new Intent(TestActivity.this, GameOver.class);
intent.putExtra("correct", numOfCorrect);
intent.putExtra("incorrect", numOfIncorrect);
startActivity(intent);
}
}
});
falseButton = (Button) findViewById(R.id.false_button);
falseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
double score = (numOfCorrect / num) * 100;
currentIndex = (currentIndex + 1) % questionBank.length;
correctNum.setText("Correct: " + numOfCorrect);
incorrectNum.setText("Incorrect: " + numOfIncorrect);
avgScore.setText("Score: " + String.format("%.2f", score) + "%");
updateQuestion();
num++;
}
});
updateQuestion();
}
}
Here's the layout for activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/correct_num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff00ff12" />
<TextView
android:id="#+id/incorrect_num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffff5440" />
<TextView
android:id="#+id/average_score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffff8c1a" />
<TextView
android:id="#+id/question_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/true_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/true_button"/>
<Button
android:id="#+id/false_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/false_button"/>
</LinearLayout>
</LinearLayout>
And the layout for the activity_game_over.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/correct_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/incorrect_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
I can get it to work if I use the setContentView(R.layout.activity_game_over);
however when I try to launch the main activity again it starts the GameOver Activity, but it should start the GeoQuiz activity instead.
In the GameOver activity you don't set any content view setContentView(), hence you textViews cannot be found, findViewById returns null, hence you get NullPointerException when invoking setText().
I can get it to work if I use the setContentView(R.layout.activity_game_over); however when I try to launch the main activity again it starts the GameOver Activity, but it should start the GeoQuiz activity instead. Please help!
The activity that runs at start up is defined in the android manifest xml file of your project.
look for
action android:name="android.intent.action.MAIN"
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hello this is my first question so please forgive me if its in bad format, I have my main activity with three buttons,Button 1 and 2 lead to numberpickers that allow user to pick from numbers to set a background image. My problem is once they pick the color (rgb) i need it sent back to the main activity but then i want the button to immediately change to the background color they chose then they can go to button two and do the same thing, at the end of the process both button1 and 2 should be the colors they have chosen. Which i will then mix in button 3(which i havent at all started on) My main problem is i pick one then it set but then i pick the other one and it onCreates() and sets the other back to a default , So i somehow need to change the colors immedietly after the activity returns to the main activity my code is a bit ugly but ive just been trying to get it working then i was gonna go back and make it more efficient so my apologize
//MAIN CONTENT
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="50dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.bignerdranch.android.colormixer.MainActivity"
tools:showIn="#layout/activity_main">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/mixButton"
android:id="#+id/screen1MixerButton"
android:layout_below="#+id/screen1Button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="103dp" />
<Button
android:text="#string/Color1Text"
android:layout_width="162dp"
android:layout_height="188dp"
android:id="#+id/screen1Button1"
android:src="#ffffff"
android:background="#ffffff"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
/>
<Button
android:text="#string/Color2Text"
android:layout_width="162dp"
android:layout_height="188dp"
android:id="#+id/screen1Button2"
android:background="#ffffff"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignBottom="#+id/screen1Button1" />
</RelativeLayout>
//COLORRPICKER1 ACTIVITY
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.bignerdranch.android.colormixer.ColorPicker1"
tools:showIn="#layout/activity_color_picker1">
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/numberPicker1"></NumberPicker>
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="#+id/numberPicker2"
android:orientation="horizontal"></NumberPicker>
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/numberPicker2"
android:layout_alignParentEnd="true"
android:orientation="horizontal"
android:id="#+id/numberPicker3"></NumberPicker>
<SurfaceView
android:layout_width="fill_parent"
android:layout_height="71dp"
android:id="#+id/surfaceView1"
android:layout_gravity="center_vertical"
android:background="#000000"
android:layout_below="#+id/numberPicker1"
android:layout_alignParentStart="true"
android:layout_marginTop="99dp"></SurfaceView>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick Color"
android:id="#+id/PickColor1"
android:layout_below="#+id/surfaceView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp" />
//COLORPICKER2 activity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.bignerdranch.android.colormixer.ColorPicker2"
tools:showIn="#layout/activity_color_picker2">
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/numberPicker1"></NumberPicker>
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="#+id/numberPicker2"
android:orientation="horizontal"></NumberPicker>
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/numberPicker2"
android:layout_alignParentEnd="true"
android:orientation="horizontal"
android:id="#+id/numberPicker3"></NumberPicker>
<SurfaceView
android:layout_width="fill_parent"
android:layout_height="71dp"
android:id="#+id/surfaceView2"
android:layout_gravity="center_vertical"
android:background="#000000"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"></SurfaceView>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick Color"
android:id="#+id/PickColor2"
android:layout_below="#+id/surfaceView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="84dp" />
</RelativeLayout>
//MAIN ACTIVITY
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;'
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MYTAG";
public static Button colorButton1;
private Button colorButton2;
private Button mixerButton;
int red1, green1, blue1,red2, green2, blue2 =255;
public static final int REQUEST_CODE= 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "in onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//START SETTING UP BUTTONS
colorButton1 = (Button) findViewById(R.id.screen1Button1);
colorButton2 = (Button) findViewById(R.id.screen1Button2);
mixerButton = (Button) findViewById(R.id.screen1MixerButton);
//ONCLICKLISTENER FOR MULTIPLE BUTTONS
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.screen1Button1:
Log.i(TAG, "screen1Button1 TAPPED");
Toast.makeText(MainActivity.this, "screen1Button1 TAPPED", Toast.LENGTH_LONG).show();
Intent i1 = new Intent(MainActivity.this,ColorPicker1.class);
startActivityForResult(i1,REQUEST_CODE);
break;
case R.id.screen1Button2:
Log.i(TAG, "screen1Button2 TAPPED");
Toast.makeText(MainActivity.this, "screen1Button2 TAPPED", Toast.LENGTH_LONG).show();
Intent i2 = new Intent(MainActivity.this,ColorPicker2.class);
startActivity(i2);
Log.i(TAG, "BACKFROM1");
break;
case R.id.screen1MixerButton:
Log.i(TAG, "screen1MixerButton TAPPED");
Toast.makeText(MainActivity.this, "screen1MixerButton TAPPED", Toast.LENGTH_LONG).show();
Intent i3 = new Intent(MainActivity.this,MixedColorScreen.class);
startActivity(i3);
Log.i(TAG, "test value recieved" + red1);
Log.i(TAG, "test value recieved" + green1);
Log.i(TAG, "test value recieved" + blue1);
Log.i(TAG, "test value recieved" + red2);
Log.i(TAG, "test value recieved" + green2);
Log.i(TAG, "test value recieved" + blue2);
red1 = getIntent().getIntExtra("ColorPicker1_red",0);
green1 = getIntent().getIntExtra("ColorPicker1_green",0);
blue1 = getIntent().getIntExtra("ColorPicker1_blue",0);
red2 = getIntent().getIntExtra("ColorPicker2_red",0);
green2 = getIntent().getIntExtra("ColorPicker2_green",0);
blue2 = getIntent().getIntExtra("ColorPicker2_blue",0);
colorButton1.setBackgroundColor(Color.rgb(red1, green1, blue1));
colorButton2.setBackgroundColor(Color.rgb(red2, green2, blue2));
break;
}
}
};
colorButton1.setOnClickListener(onClickListener);
colorButton2.setOnClickListener(onClickListener);
mixerButton.setOnClickListener(onClickListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i(TAG, "in onCreateOptionsMenu");
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.i(TAG, "in onOptionsItemsSelected");
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
//colorpicker1 activity
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.Toast;
public class ColorPicker1 extends AppCompatActivity {
private static final String TAG = "MYTAG";
NumberPicker np, np2, np3;
SurfaceView img;
int red, green, blue ;
private Button pickColorButton1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_picker1);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
pickColorButton1 = (Button) findViewById(R.id.PickColor1);
pickColorButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {;
Intent colorPick1 = new Intent(ColorPicker1.this,MainActivity.class);
colorPick1.putExtra("ColorPicker1_red",red);
colorPick1.putExtra("ColorPicker1_green", green);
colorPick1.putExtra("ColorPicker1_blue", blue);
//TRY
//MainActivity.colorButton1 = (Button) findViewById(R.id.screen1Button1);
//colorPick1.setBackgroundColor(Color.rgb(red, green, blue));
//END TRY
Log.i(TAG, "PUTING IN PUTEXTRAS VALUES RED BLUE GREEN =" + red +green + blue);
startActivity(colorPick1);
}
});
//STARTING LOGS ----------------------------------------------------------------------------
Log.i(TAG,"IN COLORPICKER1");
Toast.makeText(ColorPicker1.this, "IN COLORPICKER1", Toast.LENGTH_LONG).show();
//SETUP NUMBERPICKERS-----------------------------------------------------------------------
np = (NumberPicker) findViewById(R.id.numberPicker1);
np.setMinValue(0);
np.setMaxValue(255);
np.setWrapSelectorWheel(true);
np2 = (NumberPicker) findViewById(R.id.numberPicker2);
np2.setMinValue(0);
np2.setMaxValue(255);
np2.setWrapSelectorWheel(true);
np3 = (NumberPicker) findViewById(R.id.numberPicker3);
np3.setMinValue(0);
np3.setMaxValue(255);
np3.setWrapSelectorWheel(true);
//VALUE CHANGED LISTENERS-------------------------------------------------------------------
np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
red = np.getValue();
img = (SurfaceView) findViewById(R.id.surfaceView1);
img.setBackgroundColor(Color.rgb(red, green, blue));
}
});
np2.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
green = np2.getValue();
img = (SurfaceView) findViewById(R.id.surfaceView1);
img.setBackgroundColor(Color.rgb(red, green, blue));
}
});
np3.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
blue = newVal;
img = (SurfaceView) findViewById(R.id.surfaceView1);
img.setBackgroundColor(Color.rgb(red, green, blue));
}
});
//CLOSE-------------------------------------------------------------------------------------
}
}
//colorpicker2 activity
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.Toast;
public class ColorPicker2 extends AppCompatActivity {
private static final String TAG = "MYTAG";
NumberPicker np, np2, np3;
SurfaceView img;
int red, green, blue ;//might not need
private Button pickColorButton2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_picker2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
pickColorButton2 = (Button) findViewById(R.id.PickColor2);
pickColorButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ColorPicker2.this, "COlorPick2", Toast.LENGTH_LONG).show();
Intent colorPick2 = new Intent(ColorPicker2.this,MainActivity.class);
colorPick2.putExtra("ColorPicker2_red",red);
colorPick2.putExtra("ColorPicker2_green", green);
colorPick2.putExtra("ColorPicker2_blue", blue);
Log.i(TAG, "PUTING IN PUTEXTRAS VALUES RED BLUE GREEN =" + red + green + blue);
startActivity(colorPick2);
}
});
//STARTING log -----------------------------------------------------------------------------
Log.i(TAG, "IN COLORPICKER2");
Toast.makeText(ColorPicker2.this, "IN COLOPICKER2", Toast.LENGTH_LONG).show();
//SETTING UP NUMBER PICKERS ----------------------------------------------------------------
np = (NumberPicker) findViewById(R.id.numberPicker1);
np.setMinValue(0);
np.setMaxValue(255);
np.setWrapSelectorWheel(true);
np2 = (NumberPicker) findViewById(R.id.numberPicker2);
np2.setMinValue(0);
np2.setMaxValue(255);
np2.setWrapSelectorWheel(true);
np3 = (NumberPicker) findViewById(R.id.numberPicker3);
np3.setMinValue(0);
np3.setMaxValue(255);
np3.setWrapSelectorWheel(true);
//SETTING UP LISTENERS ---------------------------------------------------------------------
np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
red = np.getValue();
img = (SurfaceView) findViewById(R.id.surfaceView2);
img.setBackgroundColor(Color.rgb(red, green, blue));
}
});
np2.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
green = np2.getValue();
img = (SurfaceView) findViewById(R.id.surfaceView2);
img.setBackgroundColor(Color.rgb(red, green, blue));
}
});
np3.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
blue = newVal;
img = (SurfaceView) findViewById(R.id.surfaceView2);
img.setBackgroundColor(Color.rgb(red, green, blue));
}
});
//end --------------------------------------------------------------------------------------
}
}
For this you have to call startActivityForResult every time when you open ColorPicker1/2/3
Like this
Intent i1 = new Intent(MainActivity.this,ColorPicker1.class);
startActivityForResult(i1,REQUEST_CODE_COlLOR1);
//REQUEST_CODE must be greater than`0` so keep it `101` for example
and for ColorPicker2 keep REQUEST_CODE_COlLOR2 as 102 and for ColorPicker3 REQUEST_CODE_COlLOR2 as 103
and in your ColorActivity1/2/3 Call intent like this with respective request codes
Intent i = new Intent();
i.putExtra("color1", yourColor);
setResult(REQUEST_CODE_COlLOR1, i);
finish();
for in Second color activity
Intent i = new Intent();
i.putExtra("color2", yourColor);
setResult(REQUEST_CODE_COlLOR2, i);
finish();
In your mixed
Intent i = new Intent();
i.putExtra("color3", yourColor);
setResult(REQUEST_CODE_COlLOR3, i);
finish();
and then write OnActivityResult Override method in MainActivity to get the result from ColorPicker1/2/3
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == REQUEST_CODE_COlLOR1) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
//Set your color on your first button
yourColor = data.getExtras().get("color1");
}
}
if (requestCode == REQUEST_CODE_COlLOR2) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
//Set your color on your second button
yourColor2 = data.getExtras().get("color2");
}
}
if (requestCode == REQUEST_CODE_COlLOR3) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
//Set your color on your mixed color button
yourColor3 = data.getExtras().get("color3");
}
}
}
My app shuts down when clicking a button, anyone knows why? And if you fins any errors please tell me ;)This activity is about two buttons that when pressed show a TimePickerDialog and save the time.
Here's my code:
package app.alexdickson.com.workout1;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TimePicker;
import android.widget.Toast;
public class Main2Activity extends AppCompatActivity implements View.OnClickListener{
ImageButton botoFlexio;
ImageButton botoAbdominals;
static final int DIALOG_ID = 0;
int hour_x;
int minute_x;
int hourDefinitivaFlexio;
int minuteDefinitvaFlexio;
int hourDefinitivaAbs;
int minuteDefinitivaAbs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
botoFlexio = (ImageButton) findViewById(R.id.botoFlexio);
botoAbdominals = (ImageButton) findViewById(R.id.botoAbdominals);
botoFlexio.setOnClickListener(this);
botoAbdominals.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.botoFlexio:
botoFlexio.setBackgroundResource(R.drawable.flexioclicat);
showDialog(DIALOG_ID);
hourDefinitivaFlexio = hour_x;
minuteDefinitvaFlexio = minute_x;
break;
case R.id.botoAbdominals:
botoFlexio.setBackgroundResource(R.drawable.abdominalsclicat);
showDialog(DIALOG_ID);
hourDefinitivaAbs = hour_x;
minuteDefinitivaAbs = minute_x;
break;
}
}
#Override
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_ID)
return new TimePickerDialog(Main2Activity.this, kTimePickerListener, hour_x, minute_x, true);
return null;
}
protected TimePickerDialog.OnTimeSetListener kTimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour_x = hourOfDay;
minute_x = minute;
Toast.makeText(Main2Activity.this, hour_x + ": " + minute_x, Toast.LENGTH_LONG).show();
}
};
And here's my xml:
<?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="wrap_content"
android:weightSum="2"
android:orientation="horizontal"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen" >
<ImageButton
android:layout_width="0dp"
android:layout_height="400dp"
android:layout_weight="1"
android:id="#+id/botoAbdominals"
android:background="#drawable/abdominals"
android:contentDescription="ImatgeAbdominals"
android:layout_marginTop="50dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
/>
<ImageButton
android:layout_width="0dp"
android:layout_height="400dp"
android:layout_weight="1"
android:id="#+id/botoFlexio"
android:layout_gravity="top"
android:layout_marginTop="50dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/flexio"
android:contentDescription="ImatgeFlexio"
/>
Thanks for your help !!!!
Register listener with your Button after initialize it.
botoFlexio.setOnClickListener(this);
botoAbdominals.setOnClickListener(this);
You need to set listeners to the ImageButtons.
For example:
#Override
protected void onCreate(Bundle savedInstanceState) {
....
botoFlexio.setOnClickListener(this);
botoAbdominals.setOnClickListener(this);
}
I just started studying Androdid programming and have come up with some problems. I was trying to implement an app with a textview and three buttons(true_button, false_button, next_question). This project runs well on AVD. Later I added a prev_button and its listener for linking to the previous question. I also added a listener for the textview question_text_view. The Eclipse Indigo reported no error, but when running on an AVD, this program stops immediately after it is launched. Where is the problem? Or, how can I find the problems in programs when using such an IDE? Thank you.
Below are some of the programs for this project. (MainActivity.java, activity_main.xml, TrueFalse.java, strings.xml)
MainActivity.java
package com.example1.geoquiz;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private TextView mQuestionTextView;
private Button mNextButton2;
private Button mPrevButton;
private TrueFalse[] mQuestionBank = new TrueFalse[] {
new TrueFalse(R.string.question2, true),
new TrueFalse(R.string.question3, false),
new TrueFalse(R.string.question4, false),
new TrueFalse(R.string.question5, true),
new TrueFalse(R.string.question6, true),
};
private int mCurrentIndex = 0;
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
int messageResId = 0;
if(userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mQuestionTextView = (TextView)findViewById(R.id.question_text_view);
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
}
});
mNextButton = (Button)findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
}
});
/*Click the textview to get to next question.*/
mNextButton2 = (Button)findViewById(R.id.question_text_view);
mNextButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
}
});
mPrevButton = (Button)findViewById(R.id.prev_button);
mPrevButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
updateQuestion();
}
});
updateQuestion();
}
}
TrueFalse.java
package com.example1.geoquiz;
public class TrueFalse {
private int mQuestion;
private boolean mTrueQuestion;
public TrueFalse(int question, boolean trueQuestion) {
mQuestion = question;
mTrueQuestion = trueQuestion;
}
public int getQuestion() {
return mQuestion;
}
public void setQuestion(int question) {
mQuestion = question;
}
public boolean isTrueQuestion() {
return mTrueQuestion;
}
public void setTrueQuestion(boolean trueQuestion) {
mTrueQuestion = trueQuestion;
}
}
MainActivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="#+id/question_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="#+id/true_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="180dp"
android:text="#string/true_button" />
<Button
android:id="#+id/false_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/true_button"
android:layout_alignLeft="#+id/true_button"
android:layout_marginLeft="130dp"
android:text="#string/false_button" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/next_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/prev_button"
android:layout_alignBottom="#+id/prev_button"
android:layout_alignParentRight="true"
android:layout_marginRight="45dp"
android:text="#string/next_button" />
<Button
android:id="#+id/prev_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="44dp"
android:text="#string/prev_button" />
</RelativeLayout>
</RelativeLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">GeoQuiz</string>
<string name="question1">Shenzhen is near Hong Kong.</string>
<string name="question2">The Pacific Ocean is larger than the Atlantic Ocean.</string>
<string name="question3">The Suez Canal connects the Red Sea and the Indian Ocean.</string>
<string name="question4">The source of the Nile River is in Egypt.</string>
<string name="question5">The Amazon River is the longest river in the Americas.</string>
<string name="question6">Lake Bakal is the world\'s oldest and deepest freshwater lake.</string>
<string name="true_button">true</string>
<string name="false_button">false</string>
<string name="next_button">Next</string>
<string name="prev_button">Prev</string>
<string name="correct_toast">correct</string>
<string name="incorrect_toast">incorrect</string>
</resources>
/*Click the textview to get to next question.*/
mNextButton2 = (Button)findViewById(R.id.question_text_view);
What did I just see?
TextView is not a button. If you're using TextView, you should cast to TextView in your code, not to Button; and set android:clickable="true" in your layout xml resource file
I created one mini App for learning,
When any user give any number in EditText and click on submit, then TextView & EditText created dynamically based on given Digit.
and After created new EditText, user fill Data in EditText and click on submit button...
When user click on submit data must pass in new intent and Display that data in it.
My Problem is that when I click on submit button,
only Last EditText Value is display...
What Can I Do?
Thanks In Advance...!!!
Here is my Code...
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:hint="Enter Digit Here" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ADD" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<Button
android:id="#+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DELETE" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<Button
android:id="#+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SUBMIT" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/LinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
MainAvtivity.java
package com.example.textviewdemo;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private TextView addTv;
private EditText edt, edtAdd, edArray;
private Button add, delete, submit;
LinearLayout layout;
List<EditText> allEds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt = (EditText) findViewById(R.id.editText1);
add = (Button) findViewById(R.id.button1);
delete = (Button) findViewById(R.id.button2);
submit = (Button) findViewById(R.id.button3);
layout = (LinearLayout) findViewById(R.id.LinearLayout);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int no = Integer.parseInt(edt.getText().toString());
allEds = new ArrayList<EditText>();
for (int i = 0; i < no; i++) {
addTv = new TextView(MainActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(params);
addTv.setText("TextView " + i);
addTv.setId(i);
layout.addView(addTv);
edtAdd = new EditText(MainActivity.this);
layout.setLayoutParams(params);
allEds.add(edtAdd);
edtAdd.setText("Test" + i);
edtAdd.setId(i);
layout.addView(edtAdd);
}
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent(MainActivity.this, Display.class);
String[] items = new String[allEds.size()];
String str = String.valueOf(allEds.size());
for (int j = 0; j < allEds.size(); j++) {
items[j] = allEds.get(j).getText().toString();
data.putExtra("edData", items[j]);
data.putExtra("size", str);
/*
* Toast.makeText(getApplicationContext(), items[j],
* Toast.LENGTH_SHORT).show();
*/
}
startActivity(data);
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout.removeAllViews();
}
});
}
}
Display.xml
<?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" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/LinearLayout_1" >
</LinearLayout>
</LinearLayout>
Display.java
package com.example.textviewdemo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Display extends ActionBarActivity {
TextView getText;
LinearLayout linear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
Intent get = getIntent();
linear = (LinearLayout) findViewById(R.id.LinearLayout_1);
int size = Integer.parseInt((get.getExtras().getString("size")));
for (int i = 0; i < size; i++) {
getText = new TextView(Display.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
getText.setText(get.getExtras().getString("edData"));
linear.setLayoutParams(params);
getText.setId(i);
linear.addView(getText);
}
}
}
My Problem is that when I click on submit button,
only Last EditText Value is display...
Because, you are overwriting the data in your for loop using this key:
for (int j = 0; j < allEds.size(); j++) {
items[j] = allEds.get(j).getText().toString();
data.putExtra("edData", items[j]);
data.putExtra("size", str);
}
And later, retrieve using index id till j = size.
You can either use index in key or pass String array itself:
Approach 1:
data.putExtra("size", str); //you don't need to keep this in loop as its same.
for (int j = 0; j < allEds.size(); j++) {
items[j] = allEds.get(j).getText().toString();
data.putExtra("edData"+j, items[j]);
}
and
int size = Integer.parseInt(getIntent().getStringExtra("size"));
for (int j = 0; j < size; j++) {
Intent intent = getIntent();
String str = intent.getStringExtra("edData"+j);
}
Approach 2:
Pass String array in intent, and later, retrieve it in second activity:
intent.putExtra("strings", myStringArray);
and
Intent intent = getIntent();
String[] myStrings = intent.getStringArrayExtra("strings");
Hope this helps.
Please check below you are updating the value every time that's why it is only showing last digit.
package com.example.textviewdemo;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private TextView addTv;
private EditText edt, edtAdd, edArray;
private Button add, delete, submit;
LinearLayout layout;
List<EditText> allEds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt = (EditText) findViewById(R.id.editText1);
add = (Button) findViewById(R.id.button1);
delete = (Button) findViewById(R.id.button2);
submit = (Button) findViewById(R.id.button3);
layout = (LinearLayout) findViewById(R.id.LinearLayout);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int no = Integer.parseInt(edt.getText().toString());
allEds = new ArrayList<EditText>();
for (int i = 0; i < no; i++) {
addTv = new TextView(MainActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(params);
addTv.setText("TextView " + i);
addTv.setId(i);
layout.addView(addTv);
edtAdd = new EditText(MainActivity.this);
layout.setLayoutParams(params);
allEds.add(edtAdd);
edtAdd.setText("Test" + i);
edtAdd.setId(i);
layout.addView(edtAdd);
}
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent(MainActivity.this, Display.class);
String[] items = new String[allEds.size()];
String str = String.valueOf(allEds.size());
for (int j = 0; j < allEds.size(); j++) {
items[j] = allEds.get(j).getText().toString();
/*
* Toast.makeText(getApplicationContext(), items[j],
* Toast.LENGTH_SHORT).show();
*/
}
//changes made here
data.putExtra("edData", items);
data.putExtra("size", str);
startActivity(data);
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout.removeAllViews();
}
});
}
}
package com.example.textviewdemo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Display extends ActionBarActivity {
TextView getText;
LinearLayout linear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
Intent get = getIntent();
linear = (LinearLayout) findViewById(R.id.LinearLayout_1);
int size = Integer.parseInt((get.getExtras().getString("size")));
for (int i = 0; i < size; i++) {
getText = new TextView(Display.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
String[] data = get.getExtras().getString("edData");
String textOnRequest = ";
for(int i=0 ; i < data.length ; i++){
textOnResponse += data[i];
}
getText.setText(textOnResponse);
linear.setLayoutParams(params);
getText.setId(i);
linear.addView(getText);
}
}
}
You can use Shared Preferences to store values,
And later on you can retrieve from shared preferences.
Write to Shared Preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Read from Shared Preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
Check in Google API Shared - Preferences
Move data.putExtra for both size and edData keys outside for loop data.putExtra work like a Map which have a unique keys
// Prepare items Array
for (int j = 0; j < allEds.size(); j++) {
items[j] = allEds.get(j).getText().toString();
}
data.putExtra("edData", items);
data.putExtra("size", str);
Now get edData as String Array instead of String from Bundle.
I have tried many other questions on this site today but none of them have been helpful, i seem to have identical syntax that works for other people but every time i hit send (when i want my text fields to update) my app just crashes, I have tried a bunch of different syntax for the setText() method but nothing has worked.
Thanks for any help in advance
this is my main class
package com.example.myapp;
import android.app.Activity;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class TestprojectsActivity extends Activity {
private int index;
private int QsClicked = 0;
private ArrayList<String> categories = new ArrayList<String>();
private ArrayList<Button> buttons = new ArrayList<Button>();
Button b1;
Button b2;
Button b3;
Button b4;
Button changer;
private int Qselected;
TextView txt;
EditText edit;
private ArrayList<String> questions = new ArrayList<String>();
private int qnum = 0;
// updates all the buttons so we can see more categories
public void updateButtons(View v){
for(int i = 0; i < 4; i++){
if(index >= categories.size()){
index = 0;
}
buttons.get(i).setText(categories.get(index));
index++;
}
}
public void Q1(View v){
setContentView(R.layout.sub);
Qselected = index;
//send(null);
}
public void Q2(View v){
setContentView(R.layout.sub);
Qselected = (index+1);
//send(null);
}
public void Q3(View v){
setContentView(R.layout.sub);
Qselected = (index+2);
//send(null);
}
public void Q4(View v){
setContentView(R.layout.sub);
Qselected = (index+3);
//send(null);
}
public void send(View v){
edit.setText("WHY ISNT THIS WORKING?");
if(qnum < questions.size()){
txt.setText("i work!");
qnum++;
}
else{
qnum = 0;
System.exit(0);
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
index = 0;
b1 = (Button) findViewById(R.id.B1);
buttons.add(b1);
b2 = (Button) findViewById(R.id.B2);
buttons.add(b2);
b3 = (Button) findViewById(R.id.B3);
buttons.add(b3);
b4 = (Button) findViewById(R.id.B4);
buttons.add(b4);
txt = (TextView) findViewById(R.id.textView1);
edit = (EditText) findViewById(R.id.editText2);
categories.add("dumb questions");
categories.add("smart questions");
questions.add("hi there, what is your name?");
questions.add("what did you have for breakfast today?");
questions.add("how old are you?");
questions.add("what color is your hair?");
updateButtons(null);
}
}
this is my main xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layoutrowtop"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/B4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="B4"
android:onClick="Q4" />
<Button
android:id="#+id/B3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="B3"
android:onClick="Q3" />
<Button
android:id="#+id/B2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="B2"
android:onClick="Q2" />
<Button
android:id="#+id/B1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="B1"
android:onClick="Q1" />
<Button
android:id="#+id/Button05"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="More Categories"
android:onClick="updateButtons" />
</LinearLayout>
this is my sub xml (i use it so i can have another layout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.22"
android:text="Question"
/>
<EditText
android:id="#+id/editText2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.51"
android:ems="10"
android:inputType="text" />
<Button
android:id="#+id/send"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.08"
android:text="Send"
android:onClick="send" />
</LinearLayout>
Your activity is using main.xml as its layout, and that does not have a TextView with id editText2. Just putting such a view in sub.xml doesn't create the view; the layout file needs to be inflated and set as the content view for the activity. Call findViewById after you change layouts and all should be well.
AS in when Oncreate get call main.xml was you layout xml and it has not R.id.editText2 so at that time edit would be null..........
Put this line
edit = (EditText) findViewById(R.id.editText2);
in
public void Q1(View v){
setContentView(R.layout.sub);
Qselected = index;
edit = (EditText) findViewById(R.id.editText2); <-----------------here in Q1 Q2 Q3 Q4
//send(null);
}
In the activity's onCreate method you set the content view to R.layout.main and you search for the TextView that you want to set the text. Because the TextView is not in that layout(is in the R.layout.sub and not in the R.layout.main) it will be null and you'll get a NullPointerException when you set the text, although you set the content view as the new layout that contains that TextView(you already search for it in the onCreate method so the reference is initialized with null).
The solution is to search for the TextView after you set the new content view(R.layout.sub), for example:
public void send(View v){
txt = (TextView) findViewById(R.id.textView1);
edit = (EditText) findViewById(R.id.editText2);
edit.setText("WHY ISNT THIS WORKING?");
if(qnum < questions.size()){
txt.setText("i work!");
qnum++;
}
else{
qnum = 0;
System.exit(0);
}
}
Ans the same thing goes for that Edittext.