I am trying to pass an array list to another activity but it seems that is not enough. I searched all day to pass the array list with "intent" but with no success. I wrote a code for learning purposes. How to pass the data and show the Arraylist in a second activity?
The action button is btn_save. If you want further details let me know.
The code is in
MainActivity (first activity):
public class MainActivity extends AppCompatActivity {
ArrayList<String> addArray = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editTextOne = (EditText) findViewById(R.id.editTextOne);
final EditText editTextTwo = (EditText) findViewById(R.id.editTextTwo);
Button btn_showText = (Button) findViewById(R.id.buttonShow);
final TextView textView = (TextView) findViewById(R.id.textResults);
Button btn_refresh = (Button) findViewById(R.id.btn_refresh);
Button btn_close = (Button) findViewById(R.id.btn_close);
Button btn_save = (Button) findViewById(R.id.btn_save);
final ListView showMe = (ListView) findViewById(R.id.list_items);
btn_showText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = editTextOne.getText().toString();
String textTwo = editTextTwo.getText().toString();
if (text.length() == 0 || textTwo.length() == 0){
textView.setText("You must enter Name & Surname");
}else {
textView.setText(Html.fromHtml(
"<font color=\"red\">"+ text + "</font> " +
"<font color=\"blue\"><b>" + textTwo + " </b></font>"));
}
}
});
btn_refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
startActivity(getIntent());
}
});
btn_close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
System.exit(0);
}
});
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Context context = getApplicationContext();
// CharSequence mytext = "Hahahaha";
// int duration = Toast.LENGTH_SHORT;
// Toast toast = Toast.makeText(context,mytext,duration);
// toast.show();
String text = editTextOne.getText().toString();
String textTwo = editTextTwo.getText().toString();
String getInput = text + textTwo;
if (addArray.contains(getInput)){
Toast.makeText(getBaseContext(), "Item already Added!", Toast.LENGTH_LONG).show();
}
else if (getInput == null || getInput.trim().equals("")){
Toast.makeText(getBaseContext(), "Input field is empty", Toast.LENGTH_LONG).show();
}
else{
addArray.add(getInput);
ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
showMe.setAdapter(adapter);
Intent intent = new Intent(MainActivity.this, ListOfNames.class);
((EditText)findViewById(R.id.editTextOne)).setText(" ");
((EditText)findViewById(R.id.editTextTwo)).setText(" ");
}
}
});
}
public void onButtonClick(View v){
if (v.getId() == R.id.btn_list){
Intent i = new Intent(MainActivity.this, ListOfNames.class);
startActivity(i);
}
}
}
ListOfNames second activity: (almost empty)
public class ListOfNames extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_screen);
}
}
If you are trying to pass a arraylist of string then it will be easy. Just pass arraylist with intent like this:
ArrayList<String> list = new ArrayList<String>();
Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);
intent.putStringArrayListExtra("key", list);
startActivity(intent);
And receive it in ActivityTwo like this:
ArrayList<String> list = getIntent().getStringArrayListExtra("key");
I found a temporary solution for this (The app is not broke). The only problem is the arraylist didn't increased. It contains and show only the last value.
Main Activity:
...
else{
// addArray.add(getInput);
// ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
// showMe.setAdapter(adapter);
Intent intent = new Intent(MainActivity.this, ListOfNames.class);
intent.putExtra("data", getInput);
startActivity(intent);
// ((EditText)findViewById(R.id.editTextOne)).setText(" ");
// ((EditText)findViewById(R.id.editTextTwo)).setText(" ");
}
...
ListOfNames (Second Activity):
public class ListOfNames extends Activity {
ArrayList<String> addArrayT = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_screen);
Bundle bundle = getIntent().getExtras();
String data = bundle.getString("data");
Button btn_more = (Button) findViewById(R.id.btn_more);
ListView showMe = (ListView) findViewById(R.id.list_items);
addArrayT.add(data);
ArrayAdapter<String> adapterT = new ArrayAdapter<>(ListOfNames.this, android.R.layout.simple_list_item_1, addArrayT);
showMe.setAdapter(adapterT);
}
public void onClickMore(View v){
if (v.getId() == R.id.btn_more){
Intent i = new Intent(ListOfNames.this, MainActivity.class);
startActivity(i);
}
}
}
Related
Hey I was wondering if this is possible. I'm working on a app that takes user input and creates flashcards. When I click the red button I want it to open a new activity displaying the input as a list. I'm not sure how to get the second activity to read the Edittext and put it into a list display.
When you press the green button, a prompt takes user input and post it to the page. When you click the red button it will take you to a list view of what the user entered. I'm a bit stumped on how to pass the information to the next page to display a list.
enter code here package Main Code ;
TextView QuestionTV;
TextView AnswerTV;
//Buttons of Main Flashcard xml
Button addcardbtn;
Button Answerbtn;
Button nextbtn;
//Input and Buttons from dialog_Flashcard xml
EditText QuestionET;
EditText AnswerET;
Button Submitcardbtn;
Button cancelbtn;
Button deletecard;
//counter for array
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flash_cards);
addcardbtn = findViewById(R.id.addcardbtn);
Answerbtn = findViewById(R.id.Answerbtn);
nextbtn = findViewById(R.id.nextbtn);
deletecard = findViewById(R.id.deletecard);
//new array
QuestionArray = new ArrayList<>();
adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, QuestionArray);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, QuestionArray);
AnswerArray = new ArrayList<>();
adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, AnswerArray);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, AnswerArray);
//Text views
QuestionTV = findViewById(R.id.QuestionTV);
AnswerTV = findViewById(R.id.answerTV);
deletecard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplication(), FlashCard_ListView.class));
}
});
addcardbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder flashbuilder = new AlertDialog.Builder(FlashCards.this);
//get layout for the alert box
View fView = getLayoutInflater().inflate(R.layout.dialog_flashcard, null);
//get EditText from the alertbox layout
QuestionET = fView.findViewById(R.id.QuestionET);
AnswerET = fView.findViewById(R.id.AnswerET);
//get buttons from the alertbox layout
Submitcardbtn = (Button) fView.findViewById(R.id.Submitcardbtn);
cancelbtn = fView.findViewById(R.id.cancelbtn);
//make dialog box pop up
flashbuilder.setView(fView);
final AlertDialog dialog = flashbuilder.create();
dialog.show();
//code for the submit button
Submitcardbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!QuestionET.getText().toString().isEmpty() && !AnswerET.getText().toString().isEmpty()){
QuestionArray.add(QuestionET.getText().toString());
AnswerArray.add(AnswerET.getText().toString());
Toast.makeText(FlashCards.this, "Card Created", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
});
//code for cancel button
cancelbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
nextbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
QuestionTV.setText(QuestionArray.get(count));
AnswerTV.setText(AnswerArray.get(count));
if (count<QuestionArray.size()-1 || count<AnswerArray.size()-1){
count++;
AnswerTV.setVisibility(View.INVISIBLE);
}else if(count == QuestionArray.size()-1){
count = 0;
AnswerTV.setVisibility(View.INVISIBLE);
}
}
});
Answerbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AnswerTV.setVisibility(View.VISIBLE);
}
});
}
});
}
}
First Activity code
ArrayList<String> QuestionArray = new ArrayList<>();
QuestionArray.add(QuestionET.getText().toString());
ArrayList<String> AnswerArray = new ArrayList<>();
AnswerArray.add(AnswerET.getText().toString());
Intent i = new Intent(FlashCards.this, FlashCard_ListView.class);
i.putExtra("Questions", QuestionArray);
i.putExtra("Answers", AnswerArray);
startActivity(i);
Second Activity Code
Intent i = getIntent();
ArrayList<String> QuestionArray = i.getStringArrayListExtra("Questions");
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, QuestionArray);
QuestionListView.setAdapter(adapter);
ArrayList<String> AnswerArray = i.getStringArrayListExtra("Answers");
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, AnswerArray);
AnswersListView.setAdapter(adapter);
I Figured It out thanks!
Excuse my noobness. I just don't understand how to implement it to work with my code. What I'm doing is editing a name that's in a list view. When editing the name in "EditDeleteList" and get back to the previous activity (ListView) to see the name updated within the list view, nothing happens. I have to go out of the activity completely to see the change reflected. How do I get this to update? I implement an onActivityReult() method but then get this error message "java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference" so I removed it completely. How I could get the list view to update without getting that error message?
ListView.Java
public class ListView extends AppCompatActivity {
private static final String TAG = "ListView";
DatabaseHelper mDatabaseHelper;
Button btnAdd;
private EditText editText;
private android.widget.ListView listView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
mDatabaseHelper = new DatabaseHelper(this);
btnAdd = (Button) findViewById(R.id.btnAdd);
editText = (EditText) findViewById(R.id.editText);
listView = (android.widget.ListView) findViewById(R.id.lv);
ArrayList<String> list = getIntent().getStringArrayListExtra("myList");
android.widget.ListView lv = (android.widget.ListView) findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
//Takes user back to the main activity
ImageView ivBack = (ImageView) findViewById(R.id.ivBackArrow);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: pressed back arrow");
Intent intent = new Intent(ListView.this, MainActivity.class);
startActivity(intent);
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
if (editText.length() != 0) {
addData(newEntry);
editText.setText("");
} else {
toastMessage("you must put something in the text field");
}
}
});
populateListView();
}
public void addData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Successfully inserted");
recreate();
} else {
toastMessage("Whoops, something went wrong");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
private void populateListView() {
Log.d(TAG, "populateListView: displaying data in the listview");
//get data and append to list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()) {
//get the value from the database in column 1
//set it to the arraylist
listData.add(data.getString(1));
}
//create arraylist and set it to the adapter
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
listView.setAdapter(adapter);
//set onclick listen to edit activity
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String name = adapterView.getItemAtPosition(position).toString();
Log.d(TAG, "onItemClick: you clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while (data.moveToNext()) {
itemID = data.getInt(0);
}
if (itemID > -1) {
Log.d(TAG, "onItemID: the ID is: " + itemID);
Intent editScreenIntent = new Intent(ListView.this, EditDeleteList.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
} else {
toastMessage("No ID found");
}
}
});
}
}
EditDeleteList.java
public class EditDeleteList extends AppCompatActivity {
private static final String TAG = "EditDeleteList";
DatabaseHelper mDatabaseHelper;
private ImageView ivDelete;
private ImageView ivApprove;
private EditText editHashtag;
private String selectedName;
private int selectedID;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_delete);
mDatabaseHelper = new DatabaseHelper(this);
editHashtag = (EditText) findViewById(R.id.editHashtag);
ivDelete = (ImageView) findViewById(R.id.ivDelete);
ivApprove = (ImageView) findViewById(R.id.ivApprove);
//get the intent extra from the ListView activity
final Intent receivedIntent = getIntent();
//get item ID passed as an extra
selectedID = receivedIntent.getIntExtra("id", -1);
//get name passed as an extra
selectedName = receivedIntent.getStringExtra("name");
//set text field to selected item text
editHashtag.setText(selectedName);
ivApprove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = editHashtag.getText().toString();
if (!item.equals(null)) {
mDatabaseHelper.updateName(item, selectedID, selectedName);
} else {
toastMessage("you must enter a #hashtag");
}
finish();
}
});
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
In the EditDeleteList.java I have an onClickListener that saves the changes and goes back to the previous activity by using finish();
ivApprove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = editHashtag.getText().toString();
if (!item.equals(null)) {
mDatabaseHelper.updateName(item, selectedID, selectedName);
} else {
toastMessage("you must enter a #hashtag");
}
finish();
}
});
Notify the adapter in some part of the activity lifecycle.
OnCreate() should not run when you go back (this is the reason you have to completely recreate the activity to see the list updated) so you should use OnRestart/OnStart/OnResume to notify the adapter to check for new items.
Check this image
I am trying to bring all the items from the ArrayList getting saved in EditActivity to the MainActivity using SharedPreferences. But only the last entered data gets displayed in the ListView on the first MainActivity. How can I make all the text entered into the EditText get displayed as a different item in the ListView and not replace the earlier item.
Here is my Code:
MainActivity
public class MainActivity extends AppCompatActivity {
private ListView list;
private Button nextButton;
ArrayList<String> arrayList = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
nextButton = (Button) findViewById(R.id.nextButton);
loadData();
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList);
list.setAdapter(adapter);
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
nextActivity();
}
});
}
public void nextActivity(){
Intent intent = new Intent(this, EditActivity.class);
startActivity(intent);
}
public void loadData(){
SharedPreferences sp = getSharedPreferences("Data", Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = sp.getString("list", null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
arrayList = gson.fromJson(json, type);
if(arrayList == null){
arrayList = new ArrayList<String>();
}
}}
EditActivity
public class EditActivity extends AppCompatActivity {
private EditText input;
private Button addButton;
public ArrayList<String> list = new ArrayList<String>();
public ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
input = (EditText) findViewById(R.id.input);
addButton = (Button) findViewById(R.id.addButton);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String getInput = input.getText().toString();
adapter.addAll(getInput);
saveData();
input.setText(""); //clear the value in the edit text
}
});
}
public void saveData(){
SharedPreferences sp = getSharedPreferences("Data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString("list", json);
editor.apply();
}}
I think you forget to add item to list before save and thus the result is you are saving only the last item.
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String getInput = input.getText().toString();
list.add(getInput); //add this line
adapter.addAll(getInput);
saveData();
input.setText(""); //clear the value in the edit text
}
});
I have an app, where a user can enter a number and save to listView. The app is split into 3 activities.
The first activity is the MainActivity, which does something else. The second activity is where I enter a number and save it. The code Is below
public class HomeTeamScored extends Activity {
protected static EditText display;
protected static ArrayAdapter<String> adapter;
Button addButton;
CheckBox checkBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rect_activity_home_goal_player);
display = (EditText) findViewById(R.id.editText);
addButton = (Button) findViewById(R.id.btn);
checkBox = (CheckBox) findViewById(R.id.checkBox);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String task = display.getText().toString();
adapter.add(task);
adapter.notifyDataSetChanged();
SavePreferences();
Intent i = new Intent(HomeTeamScored.this, MainActivity.class);
startActivity(i);
finish();
}
});
}
protected void SavePreferences() {
// TODO Auto-generated method stub
SharedPreferences data = getApplicationContext().getSharedPreferences("saveNumber", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
for (int i = 0; i < adapter.getCount(); ++i){
// This assumes you only have the list items in the SharedPreferences.
editor.putString(String.valueOf(i), adapter.getItem(i));
}
editor.commit();
}
}
In my third activity, I retrieve the saved number.
public class ScoreBoardOverview extends Activity {
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rect_activity_score_board_overview);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
lv = (ListView) findViewById(R.id.listView);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
loadPreferences();
}
protected void loadPreferences(){
SharedPreferences data = getApplicationContext().getSharedPreferences("saveNumber", Context.MODE_PRIVATE);
for (int i = 0;; ++i){
final String str = data.getString(String.valueOf(i), "");
if (!str.equals("")){
adapter.add(str);
} else {
break; // Empty String means the default value was returned.
}
}
}
}
All this is working fine, and it adds a number to listView, but the problem is that it overrides the old value, were instead it should add a second row.
Anyone who can help??
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String task = display.getText().toString();
adapter.add(task);
adapter.notifyDataSetChanged();
SavePreferences();
Intent i = new Intent(HomeTeamScored.this, MainActivity.class);
startActivity(i);
finish();
}
});
}
here your adapter item size will be 0 when you call second activity each time. if you want to add second or third item you should write your
protected void loadPreferences(){
SharedPreferences data = getApplicationContext().getSharedPreferences("saveNumber", Context.MODE_PRIVATE);
for (int i = 0;; ++i){
final String str = data.getString(String.valueOf(i), "");
if (!str.equals("")){
adapter.add(str);
} else {
break; // Empty String means the default value was returned.
}
}
}
method in second activity too. and call loadPreferences() after this line
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
your adapter data size will be changed.
I have made this code :
public class MainActivity extends AppCompatActivity {
private ImageButton ourButton;
private EditText operand1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find Views by IDs :
ourButton = (ImageButton) findViewById(R.id.gobutton);
operand1 = (EditText) findViewById(R.id.edit_Name);
String ed_text = operand1.getText().toString().trim();
if(ed_text.isEmpty() || ed_text.length() == 0 || ed_text.equals("") || ed_text == null)
{
ourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "You did not enter a username", Toast.LENGTH_LONG).show();
}
});
}
else
{
ourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this, ScreenName.class);
MainActivity.this.startActivity(myIntent);
}
});
}
}
The problem is that if I pressed the button with or without entering anything in the field, it will say :
You did not enter a username
And the next activity will not work neither.
How do I make the button to move the user into the next activity while making sure he inputed a name?
Use this, I have modified your code..
public class MainActivity extends AppCompatActivity {
private ImageButton ourButton;
private EditText operand1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find Views by IDs :
ourButton = (ImageButton) findViewById(R.id.gobutton);
operand1 = (EditText) findViewById(R.id.edit_Name);
ourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String ed_text = operand1.getText().toString().trim();
if(ed_text.equals(""))
{
Toast.makeText(MainActivity.this, "You did not enter a username", Toast.LENGTH_LONG).show();
}
else
{
Intent myIntent = new Intent(MainActivity.this, ScreenName.class);
MainActivity.this.startActivity(myIntent);
}
}
});
}
You need to do the check when the button is pressed, here is an example:
public class MainActivity extends AppCompatActivity {
private ImageButton ourButton;
private EditText operand1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find Views by IDs :
ourButton = (ImageButton) findViewById(R.id.gobutton);
operand1 = (EditText) findViewById(R.id.edit_Name);
ourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(operand1.getText().length() == 0){
Toast.makeText(MainActivity.this, "You did not enter a username", Toast.LENGTH_LONG).show();
}else{
Intent myIntent = new Intent(MainActivity.this, ScreenName.class);
MainActivity.this.startActivity(myIntent);
}
}
});
}
}
The problem is that you are not checking the value in the listener. Change it to this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find Views by IDs :
ourButton = (ImageButton) findViewById(R.id.gobutton);
operand1 = (EditText) findViewById(R.id.edit_Name);
ourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (operand1.getText().toString().trim().length() > 0) {
Intent myIntent = new Intent(MainActivity.this, ScreenName.class);
MainActivity.this.startActivity(myIntent);
} else {
Toast.makeText(MainActivity.this, "You did not enter a username", Toast.LENGTH_LONG).show();
}
}
});
}
Also onCreate gets called when the Activity is created so you can't check the name field's value in there. That's why you need to move that check in your button's click listener. Then it will always check if the name field is empty when you click your button.
You can try this code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private ImageButton ourButton;
private EditText operand1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find Views by IDs :
ourButton = (ImageButton) findViewById(R.id.gobutton);
operand1 = (EditText) findViewById(R.id.edit_Name);
ourButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.gobutton) {
if(operand1.getText().toString().trim().equals("")){
Toast.makeText(MainActivity.this, "You did not enter a username", Toast.LENGTH_LONG).show()
}else{
Intent myIntent = new Intent(this,ScreenName.class);
startActivity(myIntent);
}
}
}
Try this instead...
public class MainActivity extends AppCompatActivity {
private ImageButton ourButton;
private EditText operand1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find Views by IDs :
ourButton = (ImageButton) findViewById(R.id.gobutton);
operand1 = (EditText) findViewById(R.id.edit_Name);
String ed_text = operand1.getText().toString().trim();
ourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ed_text.isEmpty() || ed_text.length() == 0 || ed_text.equals("") || ed_text == null) {
Toast.makeText(MainActivity.this, "You did not enter a username", Toast.LENGTH_LONG).show();
} else {
Intent myIntent = new Intent(MainActivity.this, ScreenName.class);
MainActivity.this.startActivity(myIntent);
}
});
}
}
you can use this
public class MainActivity extends AppCompatActivity {
private ImageButton ourButton;
private EditText operand1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find Views by IDs :
ourButton = (ImageButton) findViewById(R.id.gobutton);
operand1 = (EditText) findViewById(R.id.edit_Name);
String ed_text = operand1.getText().toString();
ourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ed_text.equalsignorcase("")
{
Toast.makeText(MainActivity.this, "You did not enter a username", Toast.LENGTH_LONG).show();
}
else
{
Intent myIntent = new Intent(MainActivity.this, ScreenName.class);
MainActivity.this.startActivity(myIntent);
}
});
}
cahnge your code like that
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private ImageButton ourButton;
private EditText operand1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find Views by IDs :
ourButton = (ImageButton) findViewById(R.id.gobutton);
operand1 = (EditText) findViewById(R.id.edit_Name);
ourButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
String ed_text = operand1.getText().toString().trim();
if(ed_text.equals("")){
Toast.makeText(MainActivity.this, "You did not enter a username", Toast.LENGTH_LONG).show()
}else{
Intent myIntent = new Intent(MainActivity.this, ScreenName.class);
MainActivity.this.startActivity(myIntent);
}
}
}
Don't set two OnClickListeners for one button
Try following code -
String ed_text = operand1.getText().toString().trim();
ourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!TextUtils.isEmpty(ed_text)){
Toast.makeText(MainActivity.this, "Not Empty", Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(MainActivity.this, ScreenName.class);
startActivity(myIntent);
finish(); //If you want to kill current Activity.
}else{
Toast.makeText(MainActivity.this, "Empty", Toast.LENGTH_SHORT).show();
}
}
});
Hope it will help :)