The code worked back when I still used an EditText, but I changed it to an AutoCompleteTextView to make things easier for the user, and now I have a problem. Here is the bulk of the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
AutoCompleteTextView edit = (AutoCompleteTextView) findViewById(R.id.et_item);
String[] items = getResources().getStringArray(R.array.items_array);
java.util.Arrays.sort(items);
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
edit.setAdapter(adapter);
public void find(View view) {
String name = edit.getText().toString();
if(name.equalsIgnoreCase("Brown Turkey Fig")){
Intent intent = new Intent(this, BrownTurkeyFig.class);
startActivity(intent);
}
else if(name.equalsIgnoreCase("Emerald Green Arborvitae")){
Intent intent = new Intent(this, EmeraldGreenArborvitae.class);
startActivity(intent);
}
else if(name.equalsIgnoreCase("Delaware Valley White Azalea")){
Intent intent = new Intent(this, DelawareValleyWhiteAzalea.class);
startActivity(intent);
}
Ive included the parts that are related to the question. Basically, the user types the name of a plant in the AutoCompleteTextView, and then clicks a button to be brought to a new activity based on whatever plant they typed in (I included three as examples at the end). Before I added the autofill part, the code worked fine the way it was.
The problem is that when the button is clicked, the next activity is not brought up. It crashes the app.
I do not know what is wrong with it now. Perhaps I am not properly taking the actual text from the AutoCompleteTextView to be compared in my if statements? Any help is appreciated!
You are declaring a local variable "edit" in your oncreate method but also you are using a global variable in your "find" method.
I'm sorry , I can't understand what's your meaning. Maybe you can try to use AutoCompleteTextView.setOnItemClickListener. For example:
edit.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = items.get(position);
if(item.equalsIgnoreCase("Brown Turkey Fig")){
Intent intent = new Intent(this, BrownTurkeyFig.class);
startActivity(intent);
} else if(item.equalsIgnoreCase("Emerald GreenArborvitae"){
Intent intent = new
Intent(this,EmeraldGreenArborvitae.class);
startActivity(intent);
} else if(item.equalsIgnoreCase("Delaware Valley White Azalea")){
Intent intent = new Intent(this, DelawareValleyWhiteAzalea.class);
startActivity(intent);
}
}
})
Hope to help you.
Related
I am new to Android development and I am trying to start another activity when the user clicks on an item in a ListView. However, I am stuck trying to create an Intent to do it. I am trying to follow this guide, where they use the this keyword. However, it doesn't work in this case because this refers to the AdapterView.onItemClickListener.
My current code is this:
list.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter,
View item, int pos, long id) {
Intent intent = new Intent(this, OtherActivity.class);
// use the Intent to start another activity...
}
});
What should I be replacing this with?
use your activity name before this, example:
Intent intent = new Intent(MainActivity.this, OtherActivity.class);
I am making an app for a local card game for three players, where there are two activities. One, which is kind of a calculator which calculates the results, and second, where the mentioned results are (to be) displayed. However, as I am not expert with java and programming in general, it is not working.
What now happens in my app is that the result of player one (Tom in my case), is taken from the calculator activity and displayed in the first textView und Player One's name. But when I repeat this operation, with the intent of displaying the second result in the second textView, it just overwrites the first textView. I have already tried the following:
using startActivity
using startActivityForResult
finishing the calculator activity (called MainActivity) with finish()
using Bundle instead of Intent, but
none of these did work though.
In the calculator activity (called MainActivity):
final Button zapsat = (Button)findViewById(R.id.button3);
zapsat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final TextView tomVysledek = (TextView)findViewById(R.id.textView_tom2);
//final TextView tataVysledek = (TextView)findViewById(R.id.textView_tom3);
//final TextView kubaVysledek = (TextView)findViewById(R.id.textView_tom4);
Intent intent = new Intent(MainActivity.this, Results.class);
intent.putExtra("tomVysledek", tomVysledek.getText().toString());
startActivity(intent);
}
});
In onCreate of the Results activity (where I want to display the results):
TextView textView_tomV1 = (TextView) findViewById(R.id.textView_tomV1);
TextView textView_tomV2 = (TextView) findViewById(R.id.textView_tomV2);
.
.
.
TextView textView_tomV5 = (TextView) findViewById(R.id.textView_tomV5);
int tomZapis = 0;
Intent intent = getIntent();
try {
tomZapis = Integer.parseInt(intent.getStringExtra("tomVysledek"));
} catch (Exception e){}
String tomZapis_tv = Integer.toString(tomZapis);
if (textView_tomV1.getText().equals("0")) {
textView_tomV1.setText(tomZapis_tv);
} else if (textView_tomV2.getText().equals("0")){
textView_tomV2.setText(tomZapis_tv);
} else if (textView_tomV3.getText().equals("0")){
textView_tomV3.setText(tomZapis_tv);
} else if (textView_tomV4.getText().equals("0")) {
textView_tomV4.setText(tomZapis_tv);
} else if (textView_tomV5.getText().equals("0")) {
textView_tomV5.setText(tomZapis_tv);
} else {
Toast.makeText(Results.this, "Už není místo :(", Toast.LENGTH_LONG).show();
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intentres = new Intent(Results.this, MainActivity.class);
startActivityForResult(intentres, 1);
}
});
As I said, it always displays the result in the first textView (textView_tomV1), instead of finding the first empty textView and filling it with the variable. I believe that is because the startActivity actually restarts the activity, but I am not sure about that, and even if it was the case, I wouldn't know what to do with it, either.
I am not sure if it will solve your problem but when you write this
else if (textView_tomV2.getText().equals("0"))
you compare "Editable" with a String...
You should add toString() like so
textView_tomV2.getText().toString().equals("0")
and it will compare Strings
I've got two different activities Menu and Exercise.
I need to pass some data from Menu to Exercise when I start the latter activity via the click of a button.
Here is the code in Menu activity:
Button b = (Button) findViewById(R.id.temp);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
Intent i = new Intent(context, ExerciseActivity.class);
Bundle b = new Bundle();
b.putString("colors","Blue");
b.putIntArray("workoutlist",new int[] {0,1});
i.putExtras(b);
//i.putExtra("workoutlist",MyApp.workoutList.get(0));
//i.putExtra("colors","Blue");
startActivity(i);
}
});
Using debugging tools I've checked that all the data are inside the bundle of the intent properly.
And here is the code that should retrieve data from the intent in Exercise Activity:
Intent in = getIntent();
Bundle b = in.getExtras();
String[] colorSets = (String[]) b.get("colors");
int[] l = (int[]) b.get("workoutlist");
The fact is when I get the bundle it is empty, and obviously I cannot proceed.
Moreover I already used almost the same code between to other activities and everything is working fine.
Why is this happening? Is it there something I'm missing which generates this error? Maybe some incompatibility between the two activities?
Thank you for your help!
you add String using putString() and get it using getString(). the same goes for other types.
Intent in = getIntent();
Bundle b = in.getExtras();
String colorSets = b.getString("colors");
int[] l = b.getIntArray("workoutlist");
I'm quite a beginner as far as java and android studio is concerned. So, I'm building a simple riddle game. Each activity consists of a question and a Text Field to place your answer - right answers get you to the next one etc.
The main activity has two buttons: a New Game one (which works fine) and a Continue one - the one that troubles me. Obviously, what I want is that, when pressed, it takes you to the last question you reached. I'm aware that SharedPreferences must be used in order to get this done, my problem is that I fail to think of a piece of code that works (every tutorial I've seen and read was about keeping names - high scores etc).
Here's my code: it may need some polishing, but I'm still learning.
Main Activity java
public class MainMenu extends AppCompatActivity {
private Button mStartInterrogationButton;
private VideoView mLogoprwto;
private Button mContinueButton; //This one is the one I'm asking about
#Override
public void onResume() {
super.onResume();
setContentView(R.layout.activity_main_menu);
mLogoprwto = (VideoView) findViewById(R.id.logoprwto);
mLogoprwto.setVideoPath("android.resource://my.path/"+R.raw.teloslogo);
mLogoprwto.start();
mLogoprwto.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mLogoprwto.start();
}
});
mStartInterrogationButton = (Button)findViewById(R.id.StartInterrogationButton);
mStartInterrogationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startGame();
}
});
}
private void startGame () {
Intent intent = new Intent(this, Question01.class);
startActivity(intent);
finish();
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
Question One activity java (next ones are the same)
public class FirstQuestion extends AppCompatActivity {
private Button mSayAnswer;
private EditText mAnswerbox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_question);
mAnswerbox = (EditText)findViewById(R.id.Answerbox);
mSayAnswer = (Button)findViewById(R.id.SayAnswer);
mSayAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String answer = mAnswerbox.getText().toString().trim();
if (answer.equalsIgnoreCase("nothing")){
Intent i = new Intent(getApplicationContext(), QuestionTwo.class);
startActivity(i);
}else if (answer.equalsIgnoreCase("black")) {
Intent i = new Intent(getApplicationContext(), QuestionTwo.class);
startActivity(i);
}else {
}
}
});
}
#Override
public void onBackPressed()
{
startActivity(new Intent(getApplicationContext(), MainMenu.class));
finish();
}
};
Thanks in advance, I've been looking for a solution for this for quite a few days.
One way of doing this is to save whether or not the user has answered each question correctly in the SharedPreferences. Then in your MainActivity, send them to the right question depending on how many they've answered correctly. For example:
SharedPreferences.Editor editor = getSharedPreferences("FILENAME", MODE_PRIVATE).edit();
editor.putBoolean("Question01", true);
editor.apply();
Here, FILENAME is the name of the file to write your SharedPreferences to and 'Question01' would be the tag you would save the boolean under for the first question.
SharedPreferences prefs = getSharedPreferences("FILENAME", MODE_PRIVATE);
boolean question01Answered = prefs.getBoolean("Question01", false);
Then you'd call the above to check if Question01 has been answered or not. In your continue button's onClick() method you could do a series of checks to see how far the user has reached and send them to the appropriate Question Activity.
if (!(question01Answered)) {
// question01Answered is false and has not been answered. Send them to the first question.
Intent intent = new Intent(this, Question01.class);
startActivity(intent);
finish();
} else if (!(question02Ansered)) {
// question02Answered is false and has not been answered. Send them to the second question.
Intent intent = new Intent(this, Question02.class);
startActivity(intent);
finish();
} else if (!(question03Answered)) {
// and so on...
}
EDIT: The first section of code can be called anytime you want to save data for a certain question. For example if your user answers the 5th question right then inside the Question05's activity class, you would run the first piece of code right after you confirm that the user answered correctly. Something like:
public class Question05 extends AppCompatActivity {
...
private void checkIfQuestion05IsCorrect() {
if (correct) {
// They answered right, move to the next question.
// But before we do that, let's save the fact that they answered right.
SharedPreferences.Editor editor = getSharedPreferences("FILENAME", MODE_PRIVATE).edit();
editor.putBoolean("Question05", true);
editor.apply();
} else {
// they got it wrong
}
}
}
As for the second piece of code, call it in the MainActivity right before doing all the checks in your continue button's onClick() method, or whenever else you want to know which questions they've answered and which ones they haven't.
SharedPreferences prefs = getSharedPreferences("FILENAME", MODE_PRIVATE);
boolean question01Answered = prefs.getBoolean("Question01", false);
boolean question02Answered = prefs.getBoolean("Question02", false);
boolean question03Answered = prefs.getBoolean("Question03", false);
// and so on ...
if (!(question01Answered)) {
// question01Answered is false and has not been answered. Send them to the first question.
Intent intent = new Intent(this, Question01.class);
startActivity(intent);
finish();
} else if (!(question02Ansered)) {
// question02Answered is false and has not been answered. Send them to the second question.
Intent intent = new Intent(this, Question02.class);
startActivity(intent);
finish();
} else if (!(question03Answered)) {
// and so on...
}
I have the following code:
chart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final String aux= (String) lt.getItemAtPosition(position);
Intent myIntent = new Intent(infoList.this, tabList.class);
startActivity(myIntent);
}
});
I also have a ListView. When I click on an item from that ListView I navigate to another activity that shows me the info for that activity. How do I do that? I want that info to correspond to the item I clicked.
Here is what I did in this situation, if you don't want to just pass an id back:
I call the other activity with this:
Intent intent = new Intent(myapp, CreateExerciseActivity.class);
intent.putExtra("selected_id", workout.getId());
startActivityForResult(intent, CREATE_ACTIVITY);
I then do
Intent returnIntent = new Intent();
returnIntent.putExtra("name", m.getName());
returnIntent.putExtra("unit", m.getUnit());
returnIntent.putExtra("quantity", m.getQuantity());
if (getParent() == null) {
setResult(Activity.RESULT_OK, returnIntent);
} else {
getParent().setResult(Activity.RESULT_OK, returnIntent);
}
finish();
So, in this case I was passing in an id in order to get more details from the user, and then I pass those back to the calling activity, in order to add it, as I didn't want to save this until the user chooses to later.
So, you need to do startActivityForResult in order to have it able to return the data.
You can add some data to the Intent with the methods putExtra(), and then retrieve the data in the new Activity with getExtras().getSomething().
i guess you have to use OnItemClickListener instead of the click event and you need intent to call the next activity.
private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id)
{
Intent intent = new Intent(this, MyInfoActivity.class);
intent.putExtra("selected_id", getIdFor(position));
startActivity(intent);
}
};
mHistoryView = (ListView)findViewById(R.id.history);
mHistoryView.setOnItemClickListener(mMessageClickedHandler);
Possible answer: How do I pass data between Activities in Android application?
http://thedevelopersinfo.wordpress.com/2009/10/15/passing-data-between-activities-in-android/
It really depends on what the data is in your listview. For example, if you're displaying a list of contacts in the listview, you could just pass the ID of the contact over to the other activity, and let that activity access the content provider for contacts to retrieve the data you want it to work with. You'd pass an ID within a URI in the data field of the intent, as opposed to in the extras bundle.