I want to make a function in which if a button on a different activity is pressed, then another function which is outside of this one will be invoked. But in case that the button is not pressed the function must not take place.
Here I leave you the code of what I've done so far(java.file:
public class Comida2 extends AppCompatActivity implements Adaptador2.OnRecipeListener {
private RecyclerView recyclerView1;
List<Entidad2> listItems;
Adaptador2 adaptor;
private Entidad2 entidad1,entidad2,entidad3;
Button cambiarmenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_comida);
cambiarmenu = (Button) findViewById(R.id.boton_cambiarmenu);
recyclerView1 = findViewById(R.id.lv_1);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView1.setLayoutManager(layoutManager);
listItems = new ArrayList<>();
entidad1 = new Entidad2(R.drawable.calabacines_3, "Solomillo a la plancha", " 10 min.", 4, 20);
entidad2 = new Entidad2(R.drawable.patatas_deluxe_especiadas_70523_300_150, "Entrecot", " 15 min.", 2, 50);
entidad3 = new Entidad2(R.drawable.tomate, "Hamburguesa", " 2 min.", 5, 100);
listItems.add(entidad1);
listItems.add(entidad2);
listItems.add(entidad3);
adaptor = new Adaptador2(listItems, this);
recyclerView1.setAdapter(adaptor);
adaptor.notifyDataSetChanged();
//Clicado();
}
#Override
public void OnRecipe(int priority) {
if (priority == 20) {
Intent in = new Intent(this, Solomillo.class);
startActivity(in);
}
if (priority == 50) {
Intent in = new Intent(this, Entrecot.class);
startActivity(in);
}
if (priority == 100) {
Intent in = new Intent(this, Hamburguesa.class);
startActivity(in);
}
}
private void Clicado(){
final boolean[] numerillo = new boolean[1];
cambiarmenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
numerillo[0] = true;
}
});
if (numerillo[0]) {
pickEntidad();
}
}
private void pickEntidad(){
final int random = new Random().nextInt(101);
int priority1 = entidad1.getPriority();
int priority2 = entidad2.getPriority();
int priority3 = entidad3.getPriority();
listItems.clear();
if(random < priority1){
listItems.add(entidad1);
}else if(random < priority2){
listItems.add(entidad2);
}else if (random <= priority3){
listItems.add(entidad3);
}
adaptor.notifyDataSetChanged();
}
}
I want that if the button cambiarmenu is pressed, then the function pickEntidad is invoked, but that if its not, then nothing happens. I've had the problem that I had put the method in which if the button is pressed... inside the Oncreate, and then when it was not pressed the app crashed.
The method Clicado is not coded correctly as it is the method I tried to do myself in which I've included the if and the onClickListener.
Any idea of how to do it please?
Thanks.
I did see your another post and now I understand your problem.
"The button called cambaiarmenu is in another activity, not in Comida2" - what you said here Why can't I use a button which is not in the same activity as the java.file?
The moment you called
setContentView(R.layout.activity_comida);
you can only declare all widgets(button ,textview, etc) under that layout and which I believe R.id.boton_cambiarmenu(cambiarmenu button id) does not belong on that layout.
So you need to declare your cambiarmenu button on the activity where you declare its layout and call this inside its onclicklistener
new Comida2().pickEntidad(); //calling function pickEntidad from Comida2 class
Try this. change your pickEntidad like this
private void pickEntidad(){
final int random = new Random().nextInt(101);
List<Entidad2> newlistItems = new ArrayList<>();
Entidad2 entidad1 = new Entidad2(R.drawable.calabacines_3, "Solomillo a la plancha", " 10 min.", 4, 20);
Entidad2 entidad2 = new Entidad2(R.drawable.patatas_deluxe_especiadas_70523_300_150, "Entrecot", " 15 min.", 2, 50);
Entidad2 entidad3 = new Entidad2(R.drawable.tomate, "Hamburguesa", " 2 min.", 5, 100);
int priority1 = entidad1.getPriority();
int priority2 = entidad2.getPriority();
int priority3 = entidad3.getPriority();
if(random < priority1){
newlistItems.add(entidad1);
}else if(random < priority2){
newlistItems.add(entidad2);
}else if (random <= priority3){
newlistItems.add(entidad3);
}
adaptor.notifyDataSetChanged(); //this another activity listview adaptor so it useless to notify it when you are not this activity
}
Related
I want to get different variables for the editText which i coded with java (LOOP) not XML.
I am working on a project where user is asked how many courses did you offer?, if 10 the EditText will appear 10 times. But I want to get the variable name of each editText and its value. I am only getting the value of the last one.
public class CourseEnter extends AppCompatActivity {
private TextInputLayout noOfCourse, textInputLayout,
courseCreditLoadInputLayout, courseScoreInputLayout;
private TextInputLayout dropDown;
private int i;
private ProgressDialog dialog;
private LinearLayout linearLayout;
private TextInputEditText courseCode, courseTitle, courseCreditLoad, courseScore;
String[] update;
ArrayList<String> courseTitles= new ArrayList<String>();//not used for now
ArrayList<String> courseCodes= new ArrayList<String>();//not used for now
ArrayList<String> courseLoads= new ArrayList<String>();//not used for now
ArrayList<String> courseScores= new ArrayList<String>();//not used for now
String courseTitleId;
private Button buttonNext;
private Button button;
private TextInputLayout courseCodeInputLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_enter);
String[] SEMESTERS = new String[]{"First Semester", "Second Semester"};
String[] LEVELS = new String[] {"100 Level", "200 Level", "300 Level", "400 Level","500 Level", "600 Level"
,"700 Level"};
dropDown = findViewById(R.id.dropdownM);
courser = findViewById(R.id.coureser);
ArrayAdapter<String> adapter=new ArrayAdapter<>(getApplicationContext(),R.layout.item_list,LEVELS);
AutoCompleteTextView editTextFilledExposedDropdown =
findViewById(R.id.autoCompleteViewForLevel);
editTextFilledExposedDropdown.setAdapter(adapter);
ArrayAdapter<String> adapterSemester = new ArrayAdapter<>(getApplicationContext(), R.layout.item_list, SEMESTERS);
AutoCompleteTextView editSEMESTER =
findViewById(R.id.semester2);
editSEMESTER.setAdapter(adapterSemester);
buttonNext = findViewById(R.id.secondButton);
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
courseColumn();
}
});
}
void courseColumn() {
noOfCourse = findViewById(R.id.numberOfCourses);
if (!TextUtils.isEmpty(noOfCourse.getEditText().getText().toString())) {
String generateCourse = noOfCourse.getEditText().getText().toString();
int courseToInt = Integer.parseInt(generateCourse);
linearLayout = findViewById(R.id.linearLayout);
for (i = 1; i <= courseToInt; i++) {
textInputLayout = new TextInputLayout(this);
courseTitle = new TextInputEditText(this);
textInputLayout.setHelperText("Enter Course Title for Course " + i + ":");
textInputLayout.setHelperTextEnabled(true);
courseTitle.setId(i);
textInputLayout.setHintTextColor(android.content.res.ColorStateList.valueOf(Color.RED));
//courseTitle.setHintTextColor(Color.RED);
courseTitle.setTextColor(Color.RED);
String a = Integer.toString(i);
courseTitleId = "courseTitle" + a;
// update[i]=courseTitleId;
//For Course Code
courseCodeInputLayout = new TextInputLayout(this);
courseCode = new TextInputEditText(this);
courseCodeInputLayout.setHelperText("Enter Course Code for Course " + i + ":");
courseCodeInputLayout.setHelperTextEnabled(true);
courseCode.setAllCaps(true);
// lastly added
courseCode.setId(i);
//for Course Credit Load
courseCreditLoadInputLayout = new TextInputLayout(this);
courseCreditLoad = new TextInputEditText(this);
courseCreditLoadInputLayout.setHelperText("Enter Course Credit
or Unit for Course " + i + " only numbers" + ":");
courseCreditLoadInputLayout.setHelperTextEnabled(true);
courseCreditLoad.setAllCaps(true);
courseCreditLoad.setInputType(InputType.TYPE_CLASS_NUMBER);
courseCreditLoadInputLayout.setCounterEnabled(true);
courseCreditLoadInputLayout.setCounterMaxLength(1);
//for Score
courseScoreInputLayout = new TextInputLayout(this);
courseScore = new TextInputEditText(this);
courseScoreInputLayout.setHelperText("Enter Score for Course "
+ i + " only numbers" + ":");
courseScoreInputLayout.setHelperTextEnabled(true);
courseScore.setAllCaps(true);
courseScore.setInputType(InputType.TYPE_CLASS_NUMBER);
courseScoreInputLayout.setCounterEnabled(true);
courseScoreInputLayout.setCounterMaxLength(3);
Button btn = new Button(this);
for (int bt = 1; bt <= i; bt++) {
btn.setText("STEP " + bt);
btn.setVisibility(View.VISIBLE);
btn.setTextColor(Color.RED);
btn.setBackgroundColor(Color.YELLOW);
}
//toString methods of all the inputs
String courseT= courseTitle.getText().toString();
String courseC= courseCode.getText().toString();
String courseL= courseCreditLoad.getText().toString();
String courseS= courseScore.getText().toString();
courseTitle.setLayoutParams(new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.addView(btn);
linearLayout.addView(textInputLayout);
linearLayout.addView(courseTitle);
linearLayout.addView(courseCodeInputLayout);
linearLayout.addView(courseCode);
linearLayout.addView(courseCreditLoadInputLayout);
linearLayout.addView(courseCreditLoad);
linearLayout.addView(courseScoreInputLayout);
linearLayout.addView(courseScore);
//remeber to change the button id and name=
button = new Button(this);
button.setVisibility(View.VISIBLE);
button.setEnabled(true);
button.setBackgroundColor(Color.MAGENTA);
button.setText("Proceed");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog = new ProgressDialog(CourseEnter.this);
dialog.setTitle("GUIDE FROM VICTORHEZ!!!");
dialog.setMessage("For you to save your result, you
must fill all fields provided above");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setButton(DialogInterface.BUTTON_NEGATIVE,
"OKAY", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialoga, int
which) {
dialog.dismiss();
proceedMethod();
}
});
dialog.setButton(DialogInterface.BUTTON_POSITIVE, "GO
BACK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialoga, int
which) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
linearLayout.addView(button);
} else {
Toast.makeText(this, "Enter Field: ", Toast.LENGTH_LONG).show();
noOfCourse.setError("ENTER FIELD");
}
}
private void proceedMethod() {
if (TextUtils.isEmpty(courseTitle.getText()))
{
textInputLayout.setError("Error: Enter Field");
}
else if(TextUtils.isEmpty(courseCode.getText()))
{
courseCodeInputLayout.setError("Error: Enter Field");
}
else if(TextUtils.isEmpty(courseCreditLoad.getText()))
{
courseCreditLoadInputLayout.setError("Error: Enter Field");
}
else if(TextUtils.isEmpty(courseScore.getText()))
{
courseScoreInputLayout.setError("Error: Enter Field");
}
else
{
Toast.makeText(CourseEnter.this,"VICTORHEZ",Toast.LENGTH_LONG).show();
}
}
}
Either you store it in an array,map, or setTag.
You just created the elements but has no way of accessing them again.
It depends on how you're planning to use the elements.
If you can add more detail to the question, then maybe we can set the best answer.
Make your dynamically EditText on TableLayout, then access it by its row.
Idk, sth like this maybe
String[] value = new String[YOUR-COURSE-NUMBER];
for (int i = 0; i < YOUR-COURSE-NUMBER; i++) {
TableRow tableRow = (TableRow) yourTableLayout.getChildAt(i);
EditText yourET = (EditText) tableRow.getChildAt(0);
value[i]= yourET.getText().toString();
}
I'm currently working on developing an Android app, in which I have an Activity where the user can see all of their current streaks (which were created programmatically with data accessed from Android's SQLite database).
I'm trying to then pass this data when clicked into another activity which displays an individual streak from the list of all streaks. I would need to pass all 4 pieces of information (streak name, streak category, date started, and days kept), and I'm honestly not quite sure where to start. Below is what I have so far, and while I'm not getting errors - this is currently passing either null, 0 or simply nothing to EnlargedActivity.java.
I currently have most of my code in EnlargedActivity's onResume() method, since whenever a new button is clicked, new data has to be passed in - although I'm not sure if that's the best way to do this, I'm still pretty new to Android programming. Thanks!
AllStreaks.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_streaks);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
prefs = getSharedPreferences("carter.streakly", Context.MODE_PRIVATE);
editor = prefs.edit();
db = new DatabaseHelper(this);
mTableLayout = (TableLayout) findViewById(R.id.all_streak_table);
Cursor res = db.getAllData();
if(res.getCount() ==0) {
//show message
showMessage("Error", "Nothing found");
return;
}
idList = new ArrayList<>();
streakList = new ArrayList<>();
categoryList = new ArrayList<>();
dateStartedList = new ArrayList<>();
daysKeptList = new ArrayList<>();
buttonList = new ArrayList<>();
int counter = 0;
//StringBuffer buffer = new StringBuffer();
while (res.moveToNext()){
idList.add(res.getString(0));
//buffer.append("STREAKNAME :"+ res.getString(1)+"\n");
//buffer.append("STREAKCATEGORY :"+res.getString(2)+"\n");
//buffer.append("DATESTARTED :"+res.getString(3)+"\n");;
daysKeptList.add(res.getString(4));
streakList.add(res.getString(1));
counter++;
}
LinearLayout.LayoutParams btnParams = new LinearLayout.LayoutParams(200, 200);
btnParams.setMargins(200, 30, 80, 30);
LinearLayout.LayoutParams tvParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ActionBar.LayoutParams.WRAP_CONTENT);
tvParams.setMargins(100, 0, 0, 0);
i = 0;
while (i < counter){
if(i%2==0){
mTableRow = new TableRow(this);
mTableLayout.addView(mTableRow);
}
ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
mTableRow.addView(ll);
btn = new Button(this);
btn.setText(daysKeptList.get(i));
btn.setId(i);
btn.setBackground(getResources().getDrawable(R.drawable.round_button));
btn.setLayoutParams(btnParams);
buttonList.add(btn);
ll.addView(btn);
tv = new TextView(this);
tv.setText(streakList.get(i));
tv.setId(i);
tv.setGravity(Gravity.CENTER | Gravity.BOTTOM);
tv.setTextSize(20);
tv.setLayoutParams(tvParams);
ll.addView(tv);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(AllStreaks.this, EnlargedActivity.class);
intent.putExtra("enlargeName", streakList.get(i-1));
startActivity(intent);
}
});
i++;
}
}
public void showMessage(String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
EnlargedActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enlarged);
prefs = getSharedPreferences("carter.streakly", Context.MODE_PRIVATE);
editor = prefs.edit();
Toast.makeText(EnlargedActivity.this, streakIconName, Toast.LENGTH_LONG).show();
}
public void onResume(){
super.onResume();
db = new DatabaseHelper(this);
res = db.getAllData();
if(res.getCount() ==0) {
//show message
showMessage("Error", "Nothing found");
return;
}
idList = new ArrayList<>();
streakList = new ArrayList<>();
categoryList = new ArrayList<>();
dateStartedList = new ArrayList<>();
daysKeptList = new ArrayList<>();
streakIcon = (TextView)findViewById(R.id.activity_enlarge_icon);
streakIcon.setGravity(Gravity.CENTER);
streakIcon.setTextSize(30);
counter = 0;
while (res.moveToNext()){
idList.add(res.getString(0));
streakList.add(res.getString(1));
categoryList.add(res.getString(2));
dateStartedList.add(res.getString(3));
daysKeptList.add(res.getString(4));
if (streakList.get(counter) == getIntent().getStringExtra("enlargeName")){
streakIconName = streakList.get(counter);
daysKept = Integer.parseInt(daysKeptList.get(counter));
streakIcon.setText(streakIconName + "\n" + daysKept);
}
counter++;
}
}
public void onPause(){
super.onPause();
counter = 0;
idList.clear();
streakList.clear();
categoryList.clear();
dateStartedList.clear();
daysKeptList.clear();
}
public void showMessage(String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I have a lots of Views(about 30, may be it will be more), like cards.
I set onClickListener for each of them, but its does not working.
No reaction.
Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
final EditText searchProfile = (EditText) findViewById(R.id.search_profile);
final Button btnSearch = (Button) findViewById(R.id.btn_search);
final LinearLayout layoutProfileLeft = (LinearLayout) findViewById(R.id.layout_profiles_left);
searchProfile.setHint("UserName...");
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String profileName = searchProfile.getText().toString();
urlForProfile = "http://www.dotabuff.com/search?utf8=&q=" + searchProfile.getText().toString().replace(" ", "+") + "&commit=Search";
while (htmlSrc == "" || htmlSrc == null) {
setHtmlSrc(urlForProfile);
}
ArrayList<Integer> ids = new ArrayList<Integer>();
for (int i = 0; i < 30; i++) {
searchedHeroes.add(i, new SearchedHero(i));
RelativeLayout l = new RelativeLayout(StartActivity.this);
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(-1,-2);
rlp.setMargins(8, 0, 8, 8);
l.setLayoutParams(rlp);
l.setBackgroundColor(Color.rgb(69,90,100));
l.setPadding(8,0,8,8);
l.setId(i);
//l.setLayoutParams(LinearLayout.);
ImageView img = new ImageView(StartActivity.this);
new DownloadImageTask(img).execute(searchedHeroes.get(i).getImageSrc());
img.setOnClickListener(this);
img.setId(i + 40);
l.addView(img);
RelativeLayout innerL = new RelativeLayout(StartActivity.this);
RelativeLayout.LayoutParams paramsForInnerL = new RelativeLayout.LayoutParams
(-2, -2);
paramsForInnerL.addRule(RelativeLayout.RIGHT_OF, img.getId());
TextView txtProfileName = new TextView(StartActivity.this);
txtProfileName.setText(searchedHeroes.get(i).getName());
txtProfileName.setId(i + 80);
TextView txtLastMatch = new TextView(StartActivity.this);
txtLastMatch.setText(searchedHeroes.get(i).getLastMatch());
txtProfileName.setTextSize(14);
txtProfileName.setTextColor(Color.WHITE);
txtLastMatch.setId(i + 120);
RelativeLayout.LayoutParams paramsForNameLastMatch = new RelativeLayout.LayoutParams
(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
innerL.addView(txtProfileName, rlp);
paramsForNameLastMatch.addRule(RelativeLayout.BELOW, txtLastMatch.getId());
innerL.addView(txtLastMatch, paramsForNameLastMatch);
l.addView(innerL, paramsForInnerL);
l.setOnClickListener(this);
ids.add(i, l.getId());
layoutProfileLeft.addView(l, rlp);
//}
//m.find();
//passUrl = "http://www.dotabuff.com" + m.group(1);
//Intent pass = new Intent(StartActivity.this, MainActivity.class);
//pass.putExtra("EmpID", searchedHeroes.get(0).getProfileUrl());
//startActivity(pass);
//}
//}
}
}
});
}
#Override
public void onClick(View v) {
Intent pass = new Intent(StartActivity.this, MainActivity.class);
pass.putExtra("Link", searchedHeroes.get(v.getId()).getProfileUrl());
startActivity(pass);
}
Probably, each view must intent other activity.
Thanks.
It seems to me that you forgot to set your views clickable:
view.setClickable(true)
public class MainActivity extends Activity implements View.OnClickListener {
EditText searchProfile;
Button btnSearch;
LinearLayout layoutProfileLeft
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
searchProfile = (EditText) findViewById(R.id.search_profile);
btnSearch = (Button) findViewById(R.id.btn_search);
layoutProfileLeft = (LinearLayout) findViewById(R.id.layout_profiles_left);
searchProfile.setHint("UserName...");
btnSearch.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent pass = new Intent(StartActivity.this, MainActivity.class);
String profileName = searchProfile.getText().toString();
urlForProfile = "http://www.dotabuff.com/search?utf8=&q=" + searchProfile.getText().toString().replace(" ", "+") + "&commit=Search";
while (htmlSrc == "" || htmlSrc == null) {
setHtmlSrc(urlForProfile);
}
ArrayList<Integer> ids = new ArrayList<Integer>();
for (int i = 0; i < 30; i++) {
searchedHeroes.add(i, new SearchedHero(i));
RelativeLayout l = new RelativeLayout(StartActivity.this);
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(-1,-2);
rlp.setMargins(8, 0, 8, 8);
l.setLayoutParams(rlp);
l.setBackgroundColor(Color.rgb(69,90,100));
l.setPadding(8,0,8,8);
l.setId(i);
//l.setLayoutParams(LinearLayout.);
ImageView img = new ImageView(StartActivity.this);
new DownloadImageTask(img).execute(searchedHeroes.get(i).getImageSrc());
img.setOnClickListener(this);
img.setId(i + 40);
l.addView(img);
RelativeLayout innerL = new RelativeLayout(StartActivity.this);
RelativeLayout.LayoutParams paramsForInnerL = new RelativeLayout.LayoutParams
(-2, -2);
paramsForInnerL.addRule(RelativeLayout.RIGHT_OF, img.getId());
TextView txtProfileName = new TextView(StartActivity.this);
txtProfileName.setText(searchedHeroes.get(i).getName());
txtProfileName.setId(i + 80);
TextView txtLastMatch = new TextView(StartActivity.this);
txtLastMatch.setText(searchedHeroes.get(i).getLastMatch());
txtProfileName.setTextSize(14);
txtProfileName.setTextColor(Color.WHITE);
txtLastMatch.setId(i + 120);
RelativeLayout.LayoutParams paramsForNameLastMatch = new RelativeLayout.LayoutParams
(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
innerL.addView(txtProfileName, rlp);
paramsForNameLastMatch.addRule(RelativeLayout.BELOW, txtLastMatch.getId());
innerL.addView(txtLastMatch, paramsForNameLastMatch);
l.addView(innerL, paramsForInnerL);
l.setOnClickListener(this);
ids.add(i, l.getId());
layoutProfileLeft.addView(l, rlp);
}
pass.putExtra("Link", searchedHeroes.get(v.getId()).getProfileUrl());
startActivity(pass);
}
I made an app for my use for calculating a string of values appear in an another activity. My app has 3 editTexts and one button. If we press button calculate with the input in edit text and calculated values will displayed in a second activity. I made it successfully but my problem is if the user is leave any of the boxes empty and press the button, the system will Force Close. To avoid this I made editText in graphical layout pre entered with a hint. But if the user accidentally presses button after editing the editText again system shows a Force Close.
I tried many if else methods but it does not work. Some one show me a correct way to check all editText boxes.
public class Screen1 extends Activity {
public static StringBuilder EXTRA_MESSAGE=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen1);
Button bu1= (Button)findViewById(R.id.bu);
bu1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View message)
{ int f1,f3,f4;
String vis;
EditText t1=(EditText)findViewById(R.id.a);
EditText t3=(EditText)findViewById(R.id.c);
EditText t4=(EditText)findViewById(R.id.d);
String e1=t1.getText().toString();
String e3= t3.getText().toString();
String e4= t4.getText().toString();
f1 =Integer.parseInt(e1);
f4=Integer.parseInt(e4);
f3=Integer.parseInt(e3);
StringBuilder sb = new StringBuilder();
for( float i= (float)0.1;i<=5;i=i+(float) .1)
{
sb.append(String.format("%.1f", i)+" mcg = "+(f1*60*i*f4)/(f3*1000)+"\n");
}
vis=sb.toString();
Intent intent = new Intent(message.getContext(),Screen2.class);
intent.putExtra("EXTRA_MESSAGE",vis);
startActivity(intent);
}
});
}
}
Using [TextUtils][1] check isEmpty() text inside your onClick:
#Override
public void onCreate(Bundle savedInstanceState){
EditText t1=(EditText)findViewById(R.id.a);
EditText t3=(EditText)findViewById(R.id.c);
EditText t4=(EditText)findViewById(R.id.d);
Button bu1 = (Button) findViewById(R.id.bu);
bu1.setOnClickListener(this);
}
#Override
public void onClick(View message){
boolean foundEmpty = false;
if(TextUtils.isEmpty(t1.getText())) {
foundEmpty = true;
t1.setError("Please Enter a value");
}
if(TextUtils.isEmpty(t2.getText()){
foundEmpty = true;
t2.setError("Please Enter a value");
}
if(TextUtils.isEmpty(t3.getText()){
foundEmpty = true;
t3.setError("Please enter a value");
}
if(!foundEmpty){
/* none of your text fields are empty */
int f1, f3, f4;
f1 =Integer.parseInt(e1);
f4=Integer.parseInt(e4);
f3=Integer.parseInt(e3);
final StringBuilder sb = new StringBuilder();
for( float i= (float)0.1;i<=5;i=i+(float) .1) {
sb.append(String.format("%.1f", i)+
" mcg = "+
(f1*60*i*f4)/(f3*1000)+"\n");
}
final String vis = sb.toString();
Intent intent = new Intent(message.getContext(), Screen2.class);
intent.putExtra("EXTRA_MESSAGE", vis);
startActivity(intent);
}
}
From what I gather from your question, you're getting an error when bu1 is clicked, and at least one of the EditTexts is empty. This is because you're calling Integer.parseInt() on an empty String. The following code will check if the boxes are empty, and show a Toast if any are. It will also show a Toast if the user enters anything that's not a valid number:
public class Screen1 extends Activity
{
private static final String EXTRA_MESSAGE = "extra_msg";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.screen1);
final EditText t1 = (EditText)findViewById(R.id.a);
final EditText t3 = (EditText)findViewById(R.id.c);
final EditText t4 = (EditText)findViewById(R.id.d);
Button bu1 = (Button)findViewById(R.id.bu);
bu1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View message)
{
int f1,f3,f4;
String e1 = t1.getText().toString();
String e3 = t3.getText().toString();
String e4 = t4.getText().toString();
if (e1.equals("") || e3.equals("") || e4.equals(""))
{
Toast.makeText(Screen1.this, "Please enter all numbers.", Toast.LENGTH_SHORT).show();
return;
}
try
{
f1 = Integer.parseInt(e1);
f4 = Integer.parseInt(e4);
f3 = Integer.parseInt(e3);
StringBuilder sb = new StringBuilder();
for (float i = 0.1f; i <= 5; i = i + .1f)
{
sb.append(String.format("%.1f", i) + " mcg = " + (f1 * 60 * i * f4) / (f3 * 1000) + "\n");
}
Intent intent = new Intent(Screen1.this, Screen2.class);
intent.putExtra(EXTRA_MESSAGE, sb.toString());
startActivity(intent);
}
catch (NumberFormatException e)
{
Toast.makeText(Screen1.this, "Invalid numbers.", Toast.LENGTH_SHORT).show();
}
}
}
);
}
}
I have 36 imageButtons and with each one I call the same popup in which I set random question from sqlite database. When user answers question by clicking one of the 4 possible solutions it closes and goes back to my 36 buttons. Now here I have 2 problems:
I use this code to avoid repeating questions. In activity scope:
LinkedList mAnsweredQuestions = new LinkedList();
private String generateWhereClause(){
StringBuilder result = new StringBuilder();
for (Long l : mAnsweredQuestions){
result.append(" AND _ID <> " + l);
}
return result.toString();
}
and in my question method:
mAnsweredQuestions.add(c.getLong(0));
But this does not work when my activity resumes after popup question close. It's like it loads my activity from scratch. I use this in my other game and it works fine in "normal" activity, but for some reason after popup it does not.
2.I need for each imageButton press to launch this popup activity and after each correct answer to save different number of points. I used startActivityForResult in my other game to start activity and save result, but in that case I was starting different activities with each button. Now I have to start the same activity, and save back different results. How can I do that?
Here's my popup question class:
public class Pitanja_Cigle extends Activity{
public static String tacanOdg;
int counter = 0;
Button b1, b2, b3, b4;
TextView question;
LinkedList<Long> mAnsweredQuestions = new LinkedList<Long>();
private String generateWhereClause(){
StringBuilder result = new StringBuilder();
for (Long l : mAnsweredQuestions){
result.append(" AND _ID <> " + l);
}
return result.toString();
}
Runnable mLaunchTaskFinish = new Runnable() {
public void run() {
finish();
}
};
private class Answer {
public Answer(String opt, boolean correct) {
option = opt;
isCorrect = correct;
}
String option;
boolean isCorrect;
}
Handler mHandler = new Handler();
final OnClickListener clickListener = new OnClickListener() {
public void onClick(View v) {
Answer ans = (Answer) v.getTag();
if (ans.isCorrect) {
Intent i = new Intent("rs.androidaplikacije.toplo_hladno.TACANODGOVOR");
startActivity(i);
mHandler.postDelayed(mLaunchTaskFinish,1200);
}
else{
Intent i = new Intent(getApplicationContext(), PogresanOdgovor.class);
i.putExtra("tacanOdgovor", tacanOdg);
startActivity(i);
mHandler.postDelayed(mLaunchTaskFinish,2200);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.pitanja_cigle);
InicirajVariable();
nextQuestion();
}
private void nextQuestion() {
counter++;
TestAdapter mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
try{ //Pokusava da otvori db
mDbHelper.open(); //baza otvorena
Cursor c = mDbHelper.getPitanjaCigle(generateWhereClause());
mAnsweredQuestions.add(c.getLong(0));
List<Answer> labels = new ArrayList<Answer>();
labels.add(new Answer(c.getString(2), true));
labels.add(new Answer(c.getString(3), false));
labels.add(new Answer(c.getString(4), false));
labels.add(new Answer(c.getString(5), false));
tacanOdg = c.getString(2);
Collections.shuffle(labels);
question.setText(c.getString(1));
b1.setText(labels.get(0).option);
b1.setTag(labels.get(0));
b1.setOnClickListener(clickListener);
b2.setText(labels.get(1).option);
b2.setTag(labels.get(1));
b2.setOnClickListener(clickListener);
b3.setText(labels.get(2).option);
b3.setTag(labels.get(2));
b3.setOnClickListener(clickListener);
b4.setText(labels.get(3).option);
b4.setTag(labels.get(3));
b4.setOnClickListener(clickListener);
}
finally{ // kada zavrsi sa koriscenjem baze podataka, zatvara db
mDbHelper.close();
}
}
private void InicirajVariable() {
Typeface naslov = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
Typeface dugmad = Typeface.createFromAsset(getAssets(), "Bebas.ttf");
question = (TextView) findViewById(R.id.tvPitanjeCigle);
b1 = (Button) findViewById(R.id.bOdgCigle1);
b2 = (Button) findViewById(R.id.bOdgCigle2);
b3 = (Button) findViewById(R.id.bOdgCigle3);
b4 = (Button) findViewById(R.id.bOdgCigle4);
b1.setTypeface(dugmad);
b2.setTypeface(dugmad);
b3.setTypeface(dugmad);
b4.setTypeface(dugmad);
question.setTypeface(naslov);
}
}