Android - I am using intent to communicate between two activities. I used putExtra() in the calling activity and i am using getExtras in the called activity. But the problem is iam not able to set the edit text with the number i retrieved in the intent. below is my program`
// Calling activity
package com.example.androidtutorial2;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.text.InputType;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//EDIT TEXT
final EditText sharedata = (EditText) findViewById ( R.id.editText1 ) ;
sharedata.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
//BUTTON
Button sendbutton = (Button) findViewById (R.id.button2) ;
sendbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int edittext_data = Integer.valueOf(sharedata.getText().toString());
Intent sendintent = new Intent(MainActivity.this,second_activity.class);
sendintent.putExtra("somedata", edittext_data);
startActivity(sendintent);
}
});
// Button button_to_call_activity = (Button) findViewById(R.id.button1);
// button_to_call_activity.setOnClickListener(new OnClickListener() {
//
// #Override
// public void onClick(View v) {
//
//
// }
// });
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
//CALLED ACTIVITY
package com.example.androidtutorial2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.widget.EditText;
public class second_activity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
EditText displaymessage = (EditText) findViewById ( R.id.editText1 );
Intent intent1 = getIntent();
Bundle bundle1 = intent1.getExtras();
int integer1 = bundle1.getInt("somedata");
Integer string1 = integer1;
displaymessage.setText(integer1); // HERE IS A RUNTIME ERROR
}
}
use
displaymessage.setText("" +integer1);
Or
displaymessage.setText(String.valueOf(integer1));
1. First of all if you are using Java 1.5 and above dont useInteger.valueOf() but instead use Integer.parseInt().
eg:
int edittext_data = Integer.parseInt(sharedata.getText().toString());
2. Your problem with the output is here.
Dont do this ... Integer string1 = integer1;
Use it like this...
String string1 = getIntent().getExtras().getString("somedata");
displaymessage.setText(string1);
Since you don't seem to be doing anything with the variable as an integer, you could also simply keep it as a string.
sendintent.putExtra("somedata", sharedata.getText().toString());
String integer1 = bundle1.getString("somedata");
Related
I am beginner. I have made a simple log in form in android studio. I face a fault in if condition. Please solve this.
If username box is empty then control should go in if(...) but it goes to else part and open next intent
code is here:
package com.android.dumbseraaz;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private EditText uname;
private EditText pwd;
private Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname = (EditText)findViewById(R.id.txt_userName);
pwd = (EditText)findViewById(R.id.txt_Password);
login = (Button)findViewById(R.id.button);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(uname.getText().toString(),pwd.getText().toString());
}
});
}
private void validate(String myuname, String Pswd) {
if(myuname == "")
{
uname.setText("user");
}
else if(Pswd == "")
{
pwd.setText("PasswordMe");
}
else {
Intent intent = new Intent(MainActivity.this, app_home.class);
startActivity(intent);
}
}
}
I am trying to get a submit button to take me to the next page when the input is milk. Here's what I've tried so far
package com.example.ephraimcohen.prestwichlanguageschool;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class activitytwomilk2 extends AppCompatActivity {
private EditText Word;
private TextView TryAgain;
private Button Submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activitytwomilk2);
Word = (EditText)findViewById(R.id.etword);
TryAgain = (TextView)findViewById(R.id.tvtryagian);
Submit = (Button) findViewById(R.id.btnsubmit);
TryAgain.setText(" ");
Submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
validate(Word.getText().toString());
}
});
}
private void validate(String userWord){
if((userWord.equals ("milk"))){
Intent intent = new Intent(activitytwomilk2.this, activitytwomilkcorrect.class);
startActivity(intent);
}else{
TryAgain.setText(" " + "Try again");
}
}`
Under that, there is another button which just goes to the home screen. That button is working properly and taking me to the homepage.
Try to use == instead of equals in your condition
if(userWord=="milk"){
Intent intent = new Intent(activitytwomilk2.this, activitytwomilkcorrect.class);
startActivity(intent);
}else{
TryAgain.setText(" " + "Try again");
}
}`
I am making an app in android Studio and if you open the app on your phone you see the Launcer activity. I have a button that sends you to a new activity where te game is located. Once i click the Start button, The app closes and doesn't goes to the other activity. Why is that?
This is my code of the Launcher activity:
package joenio.sirname;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class SirName_launcher extends AppCompatActivity {
public static Button button_start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sir_name_launcher);
StartButton();
}
public void StartButton(){
button_start = (Button) findViewById(R.id.button_start);
button_start.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent("joenio.sirname.Game");
startActivity(intent1);
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_sir_name_launcher, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// 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);
}
}
And this is the code of the second activity:
package joenio.sirname;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import android.widget.Toast;
public class Game extends AppCompatActivity {
public static EditText editText_surname;
public static TextView textView_name;
public static Button button_check;
int x =0; //to keep track of qustions
//Context editText_this = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Displayquestions();
}
public void Displayquestions(){
final ArrayList<String> mQuestionList = new ArrayList<>();
mQuestionList.add("1+2");
mQuestionList.add("6+8");
mQuestionList.add("5 * 6");
mQuestionList.add("8*5");
mQuestionList.add("6+16");
mQuestionList.add("18-5");
textView_displayquestion.setText((mQuestionList.get(x)));//displayquestion is textview
final ArrayList<String> mAnswerList=new ArrayList<>();
mAnswerList.add("3");
mAnswerList.add("14");
mAnswerList.add("30");
mAnswerList.add("40");
mAnswerList.add("22");
mAnswerList.add("13");
//button_check is the button when user click it will first check answer and than move to next question if answer is correct
button_check.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//editText_this;
String answer = editText_ans.getText().toString();
if (answer.equals(mAnswerList.get(x))) {
x = x + 1;
textView_displayquestion.setText(mQuestionList.get(x)); //answer is correct display next quesion
Toast.makeText(getApplication().getBaseContext(),
(R.string.Nice), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(),
(R.string.tryagain), Toast.LENGTH_SHORT).show();
}
}
});
}
}
You are no where initializing your TextView and Button which must be causing NullPointerException.
Change your Game activity like this
TextView textView_displayquestion;
Button button_check;
EditText editText_ans;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
textView_displayquestion = (TextView)findViewById(R.id.displayquestion); //change as per your id
button_check = (Button)findViewById(R.id.buttoncheck); //change as per your id
editText_ans = (EditText)findViewById(R.id.answer); //change as per your id
Displayquestions();
}
In your button click , change the code as below.
Intent intent1 = new Intent(SirName_launcher.this, Game.class);
startActivity(intent1);
And also add the new Game Activity in your Manifest file too.
I have this problem accessing an extra from an intent.
The value i'm parsing is a long type, and I need this value to be stored in a database.
So this is what I have so far:
MainActivity:
package com.example.calendar;
import java.sql.Date;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CalendarView;
import static android.provider.BaseColumns._ID;
import static com.example.calendar.Constants.TABLE_NAME;
import static com.example.calendar.Constants.TIME;
import static com.example.calendar.Constants.TITLE;
import static com.example.calendar.Constants.DETAILS;
import static com.example.calendar.Constants.DATE;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class MainActivity extends Activity implements OnClickListener {
private AppointmentsData appointments;
CalendarView calendar;
Date date = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View createButton = findViewById(R.id.btn_create);
View editButton = findViewById(R.id.btn_viewEdit);
View deleteButton = findViewById(R.id.btn_delete);
View moveButton = findViewById(R.id.btn_move);
View searchButton = findViewById(R.id.btn_search);
View translateButton = findViewById(R.id.btn_translate);
View exitButton = findViewById(R.id.exit);
createButton.setOnClickListener(this);
editButton.setOnClickListener(this);
deleteButton.setOnClickListener(this);
moveButton.setOnClickListener(this);
searchButton.setOnClickListener(this);
translateButton.setOnClickListener(this);
exitButton.setOnClickListener(this);
appointments = new AppointmentsData(this);
calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
date = new Date(year, month, dayOfMonth);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i;
switch (v.getId()) {
case R.id.btn_create:
i = new Intent(this, CreateAppointment.class);
i.putExtra(DATE, date.getTime());
startActivity(i);
break;
case R.id.btn_viewEdit:
i = new Intent(this, EditViewAppointment.class);
i.putExtra(DATE, date.getTime());
startActivity(i);
break;
case R.id.btn_move:
i = new Intent(this, MoveAppointment.class);
i.putExtra(DATE, date.getTime());
startActivity(i);
break;
case R.id.btn_delete:
i = new Intent(this, DeleteAppointment.class);
i.putExtra(DATE, date.getTime());
startActivity(i);
break;
case R.id.btn_search:
i = new Intent(this, SearchAppointment.class);
startActivity(i);
break;
case R.id.btn_translate:
i = new Intent(this, TranslateAppointment.class);
i.putExtra(DATE, date.getTime());
startActivity(i);
break;
case R.id.exit:
finish();
break;
}
}
}
And the other Activity to use the value:
package com.example.calendar;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.EditText;
import android.app.Activity;
import android.content.Intent;
import static android.provider.BaseColumns._ID;
import static com.example.calendar.Constants.TABLE_NAME;
import static com.example.calendar.Constants.TIME;
import static com.example.calendar.Constants.TITLE;
import static com.example.calendar.Constants.DETAILS;
import static com.example.calendar.Constants.DATE;
import static com.example.calendar.Constants.CONTENT_URI;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class CreateAppointment extends Activity implements OnClickListener{
private static String[] FROM = { _ID, DATE, TIME, TITLE, DETAILS};
private static String ORDER_BY = TIME + " ASC";
AppointmentsData appointments;
CalendarView calendar;
String string;
EditText nameTextBox;
EditText timeTextBox;
EditText detailsTextBox;
Button createButton;
SQLiteDatabase db;
Intent fetchDate = getIntent();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
createButton = (Button) findViewById(R.id.apptSave);
nameTextBox = (EditText)findViewById(R.id.apptName);//Assign the global name box
timeTextBox = (EditText)findViewById(R.id.apptTime);//Assign the global time box
detailsTextBox = (EditText)findViewById(R.id.apptDetails);//Assign the global details box
calendar = (CalendarView)findViewById(R.id.calendar);
createButton.setOnClickListener(this);
appointments = new AppointmentsData(this);
string = "row";
long dateFecth = fetchDate.getLongExtra(DATE, defaultValue);
}
private void addAppointment(String string) {
/* Insert a new record into the Events data
source. You would do something similar
for delete and update. */
String getTitle = nameTextBox.getText().toString();
String getTime = timeTextBox.getText().toString();
String getDetails = detailsTextBox.getText().toString();
db = appointments.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DATE, calendar.getDate());
values.put(TIME, getTime);
values.put(TITLE, getTitle);
values.put(DETAILS, getDetails);
getContentResolver().insert(CONTENT_URI, values);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.apptSave:
addAppointment(string);
finish();
break;
}
}
}
The error is on the long dateFecth = fetchDate.getLongExtra(DATE, defaultValue); line and I don't know what to use for the second argument, since everything I think of gives me an error.
Can someone please help me with this?
Move fetchDate = getIntent(); inside onCreate method of Activity as:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
//.your code here..
fetchDate = getIntent(); // get intent here from previous Activity
long dateFecth = fetchDate.getLongExtra(DATE, defaultValue);
}
First check - Value is associated with the given name.
if you don't want to use defaultValue try with bundle as follow
if (getchDate.hasExtra("Date")) {
Bundle bundle = new Bundle();
bundle = getchDate.getExtras();
Object object = bunlde.get(Date);
Now parse this object in your desire type.
}
You should check if result of getIntent() is not empty at first (an of course the call should be inside onCreate, not constructor). If it's not empty, then get long variable from it. defaultValue stands for a value returned from a method if a value for specified key is not found.
Am new to Android so just practising on small stuff, what am trying to do is a button(B1) in the (mainactivity) layout and when I click it , it changes to another layout(main) which has another button (B2)which changes back to mainactivity layout out on-click , B1 is working okey , but B2 not working any ideas?
package com.example.android;
import java.util.Random;
import java.awt.*;
import com.example.android.R;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Button btn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.clickme);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.main);
/*Random rand = new Random();
btn.setBackgroundColor(Color.argb(255, rand.nextInt(255),
rand.nextInt(255), rand.nextInt(255)));*/
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
this is (main) layout
package com.example.android;
import com.example.android.R;
import java.util.Random;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity {
Button btn;
TextView text;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.ChangeColor);
text = (TextView) findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.activity_main);
/*Random rand = new Random();
btn.setBackgroundColor(Color.argb(255, rand.nextInt(255),
rand.nextInt(255), rand.nextInt(255)));
text.setTextColor(Color.argb(255, rand.nextInt(255),
rand.nextInt(255), rand.nextInt(255)));*/
}
});
}
}
setContentView(R.layout.activity_main); is not doing what you think.
To naviguate to activities you have to use intents like the others sugested in the comments
First decalre your context:
final Context context = this;
then pass it to your intent:
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
}
});