i want to send integer value through intents , and access it on another activity ... i tried using the following code .. but its not working..!!
mCheatButton = (Button)findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mCheatButton.setVisibility(View.INVISIBLE);
mIsCheater = false;
int mCurrentIndex=2;
Intent i = new Intent(quizactivity.this, CheatActivity.class);
i.putExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, mCurrentIndex);
startActivityForResult(i, 0);
}
catch (Exception e)
{
}
}
});
SECOND ACTIVITY:
mShowAnswer = (Button)findViewById(R.id.showAnswerButton);
mShowAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(extras == null)
{ mAnswerIsTrue= 0;
updateanswer(mAnswerIsTrue);
}
else
{
mAnswerIsTrue= extras.getInt(EXTRA_ANSWER_IS_TRUE);
updateanswer(mAnswerIsTrue);
}
updateanswer(mAnswerIsTrue);
}
});
public void updateanswer(int q){
mAnswerTextView.setText(solution[q].getA());
setAnswerShownResult(true);
}
please help me solve it out..!!
i want to send integer value through intents , and access it on another activity ... i tried using the following code .. but its not working..!!
what is the error in above code.. i cant really understand...!!
Your problem is on your second activity, I guess.
Intent extras = getIntent();
int yourInt = extras.getIntExtra(EXTRA_ANSWER_IS_TRUE, -1);
In you second activity you need to do
int i = getIntent().getExtras().getInt(CheatActivity.EXTRA_ANSWER_IS_TRUE)
Related
This code can open a built-in contacts directory on a mobile device. However, when I select a contact, the app reports "done", but doesn't retrieve the contact number -- the user can't send a message.
How do I retrieve the contact number? List View is not a solution: I need to return just the one number, not extra information.
Here's my code:
public EditText no;
public EditText msg;
public Button cancel;
public Button snd;
public String Number,name,Message;
public int run=0;
public static final int PICK_CONTACT=1;
public void callContacts(View v)
{
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent,PICK_CONTACT);
}
#Override
public void onActivityResult(int reqCode,int resultCode,Intent data)
{
super.onActivityResult(reqCode,resultCode,data);
if(reqCode==PICK_CONTACT)
{
if(resultCode== ActionBarActivity.RESULT_OK)
{
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData,null,null,null,null);
if(c.moveToFirst())
{
name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.CONTENT_URI.toString()));
Toast.makeText(this,"done",Toast.LENGTH_SHORT).show();
}
}
}
}
and here is the onCreate method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
no = (EditText)findViewById(R.id.num);
msg = (EditText)findViewById(R.id.sms);
cancel = (Button)findViewById(R.id.cancel);
snd = (Button)findViewById(R.id.snd);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
msg.setText("");
no.setText("");
callContacts(null);
}
});
snd.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Number = no.toString();
Message = msg.getText().toString();
SmsManager manager = SmsManager.getDefault();
ArrayList<String>long_sms = manager.divideMessage(Message);
manager.sendMultipartTextMessage(Number,null,long_sms,null,null);
Toast.makeText(getApplicationContext(),"Sent Successfully",Toast.LENGTH_SHORT).show();
}
});
}
Here is the code just for selecting one phone number from contact list. i found this code simplest. let me know if there is any problem.
start activity with pick intent on phone data type:
findViewById(R.id.choose_contact_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pickContact = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(pickContact, PICK_CONTACT_REQUEST);
}
});
Now set onAcitivityResult();
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
switch (requestCode){
case PICK_CONTACT_REQUEST:
if (resultCode == RESULT_OK){
Uri contactUri = intent.getData();
Cursor nameCursor = getContentResolver().query(contactUri, null, null, null, null);
if (nameCursor.moveToFirst()){
String name = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
((EditText)findViewById(R.id.person_name)).setText(name);
((EditText)findViewById(R.id.enter_mobile)).setText(number);
nameCursor.close();
}
}
break;
}
}
After trying lot of things found here, nothing worked.
To make it simple :
I have a main activity with a button.
I have a "child" activity with 2 text fields and a button.
When I click the main activity button, the child activity opens (it works). Then I put some text to the two text fields and when I click the button I want the data from the text fields to be transfered to the main activity, and I can't get this working.
Here is my main activity code
public class MainMenu extends AppCompatActivity {
Button btnAddBib;
public final static int REQUEST_CODE_B = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
btnAddBib = (Button)findViewById(R.id.btnAddBib);
btnAddBib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(), MainActivity.class);
startActivityForResult(myIntent,REQUEST_CODE_B);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case REQUEST_CODE_B:
String Qte = data.getStringExtra("qte");
String Time = data.getStringExtra("time");
if (Qte != null && !Qte.isEmpty() && Time != null && !Time.isEmpty()) {
final SQLiteDatabase dbBib;
dbBib = openOrCreateDatabase("bibi", Context.MODE_PRIVATE, null);
dbBib.execSQL("CREATE TABLE IF NOT EXISTS bibi(time VARCHAR, qte VARCHAR);");
dbBib.execSQL("INSERT INTO bibi VALUES ('" + Time + "','" +
Qte + "')");
Toast.makeText(getApplicationContext(), "Bibi bien enregistré",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Fail get extraData",
Toast.LENGTH_LONG).show();
}
break;
}
}
And the child activity code :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ajouter_bibi);
btnValideBib = (Button)findViewById(R.id.btnValideBib);
btnValideBib.setBackgroundResource(R.drawable.logo_biberon);
txtTime = (EditText)findViewById(R.id.txtTime);
txtQte = (EditText)findViewById(R.id.txtQte);
Calendar c = Calendar.getInstance();
int hh = c.get(Calendar.HOUR_OF_DAY);
int mm = c.get(Calendar.MINUTE);
txtTime.setText(hh + ":" + mm);
btnValideBib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent backIntent = new Intent();
backIntent.putExtra("qte", txtQte.getText());
backIntent.putExtra("time", txtTime.getText());
setResult(RESULT_OK, backIntent);
finish();
}
});
The problem :
In the main activity, when I want to get back my Extra Strings I have null fields.
String Qte = data.getStringExtra("qte");
String Time = data.getStringExtra("time");
What is wrong with it ?
Thanks!
Change the code :
backIntent.putExtra("qte", txtQte.getText());
backIntent.putExtra("time", txtTime.getText());
to below code:
backIntent.putExtra("qte", txtQte.getText().toString()); //append .toString() method
backIntent.putExtra("time", txtTime.getText().toString());
I'm Developing an android app in which there is a Login activity and a Questionnaire activity contains Questions.So now I wanted to make the user to access the app only by entering the unique id which will help in blocking unauthorized users. I tried with the code but when i press the login button it pops the alert dialogue even if the password is matching the password I've given. And the password i wanted to keep is 'VISTEON'. If the password entered is rite then it should intent to the next activity.
check my java code and help me to modify it.efforts will be really appreciated.
Thanks in Advance.
Here is my java code
public class Klogin extends Activity {
EditText editText1;
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_login);
addButtonListener();
}
public void addButtonListener()
{
Button login=(Button)findViewById(R.id.button1);
login.setOnClickListener(new OnClickListener(){
public void onClick(View v){
if(validationSuccess()){
Intent intent = new Intent(Klogin.this, Login.class);
startActivity(intent);
}
}
});
}
private Boolean validationSuccess()
{
EditText visteon = null;
if(editText1==visteon)
{
alertDialog();
return false;
}
return true;
}
private void alertDialog()
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Klogin.this);
alertDialogBuilder.setMessage("Please ENTER the Correct password").setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
Try this way first initialized EditText edit_password like
EditText edit_password = (EditText)findViewById(R.id.edit_password);
Now, create validationSuccess(......) like
private Boolean validationSuccess(String str)
{
if(!str.equals("yourcorrectpassword"))
{
alertDialog();
return false;
}
return true;
}
Now called this function like
login.setOnClickListener(new OnClickListener(){
public void onClick(View v){
if(validationSuccess(edit_password.getText.toString())){
Intent intent = new Intent(Klogin.this, Login.class);
startActivity(intent);
}
}
});
And make sure you have EditText with id edit_password in your activity_main_login.xml layout file.
Try this..
public void addButtonListener()
{
Button login=(Button)findViewById(R.id.button1);
editText1=(EditText)findViewById(R.id.editText1);
login.setOnClickListener(new OnClickListener(){
public void onClick(View v){
if(validationSuccess(editText1.getText().toString().trim())){
Intent intent = new Intent(Klogin.this, Login.class);
startActivity(intent);
}
}
});
}
and
private Boolean validationSuccess(String value)
{
if(!value.equals("VISTEON"))
{
alertDialog();
return false;
}
return true;
}
For start you are not setting the visteon variable. This only needs to be a String.
Then when you user enters the value, you need to get the String from the editText1 and then check using equals as to whether it is correct or not. The == operator will check for equality of objects, not their values.
What you want is if(editText1.getText().toString().equals("VISTEON")).
I'm new to Android, and trying to create authentication function that will use startActivityForResult and onActivityResult and return result (in my case array of two strings - username and password from login screen).
Here's my code (returning null for username and password)
In main activity (calling authenticate() function):
public String user;
public String pass;
public void startAuth(Intent i)
{
startActivityForResult(i, 1);
}
public String[] authenticate()
{
String[] ret = new String[2];
Intent i = new Intent(getApplicationContext(), LoginActivity.class);
startAuth(i);
ret[0] = i.getStringExtra("iUsername");
ret[1] = i.getStringExtra("iPassword");
return ret;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data.getExtras().containsKey("iUsername"))
{
user = data.getStringExtra("iUsername");
pass = data.getStringExtra("iPassword");
}
}
In loginActivity:
public class LoginActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Button loginButton = (Button) findViewById(R.id.btnLogin);
final EditText username = (EditText) findViewById(R.id.username_fill);
final EditText password = (EditText) findViewById(R.id.password_fill);
// Listening to Login Button
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = getIntent();
i.putExtra("iUsername", username.getText().toString());
i.putExtra("iPassword", password.getText().toString());
setResult(RESULT_OK, i);
finish();
}
});
}
}
I understand that I need to somehow wait for the onActivityResult callback, but I've tried different solutions (using wait() and notify(), using singleton) but can't get it working...
I must wrap it, and not use it like this because I want to use the authenticate() function in much bigger code. Any solutions without using the above functions are also ok..
Thanks!
Wherever you are using authenticate() you aren't actually waiting for a response:
public void authenticate() // Changed return type to void
{
//String[] ret = new String[2];
Intent i = new Intent(getApplicationContext(), LoginActivity.class);
startAuth(i);
/*
* This code does nothing, the Intent you want is in onActivityResult()
ret[0] = i.getStringExtra("iUsername");
ret[1] = i.getStringExtra("iPassword");
return ret;
*/
}
You must break up your logic so that when onActivityResult() is called it resumes where authenticate() left off. Understand you cannot resume in the middle of a method.
So you must call authenticate() at the end of one method and wherever you used ret must now be a new method which you call from onActivityResult().
private final Object lock = new Object();
public synchronized void startAuth(Intent i)
{
m_intent = i;
Thread thread = new Thread()
{
#Override
public void run()
{
MainActivity.this.runOnUiThread(new Runnable()
{
public void run()
{
startActivityForResult(m_intent, 1);
}
});
}
};
thread.start();
}
// authenticate function
public String[] authenticate()
{
String[] ret = new String[2];
Intent i = new Intent(getApplicationContext(), LoginActivity.class);
startAuth(i);
// waiting for login
synchronized (lock)
{
try
{
lock.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
// writing results
ret[0] = m_sUser;
ret[1] = m_sPass;
return ret;
}
I create an activity with dynamic buttons in a loop. I get a list and create a button for each element in the list. The buttons go to the same activity afterward, but with each button I want to pass different string.
I did this in the loop:
tour_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(TourListActivity.this,
TourMenuActivity.class);
String info = tour.toString();
intent.putExtra(TOUR_INFO, info);
startActivity(intent);
}
});
But at the end, all the buttons get the same string (the string of the last button).
========================================
full code:
try {
JsonObject respObject = jsonParser.parse(response).getAsJsonObject();
JsonArray tourListArray = respObject.getAsJsonArray("tours");
System.out.println("tourListArray: " + tourListArray.toString());
for(int i = 0; i < tourListArray.size(); i++){
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
tour = tourListArray.get(i).getAsJsonObject();
String tourCode = tour.get("tourcode").getAsString();
Button tour_button = new Button(this);
tour_button.setText("Tour Code: " + tourCode);
tour_button.setGravity(Gravity.LEFT);
tour_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(TourListActivity.this,
TourMenuActivity.class);
String info = tour.toString();
intent.putExtra(TOUR_INFO, info);
startActivity(intent);
}
});
ll.addView(tour_button);
LinearLayout yourLL = (LinearLayout) findViewById(R.id.Tours_List);
yourLL.setOrientation(LinearLayout.VERTICAL);
yourLL.addView(ll);
}
} catch (JsonIOException e) {
e.printStackTrace();
}
When you create the button you can:
button.setTag(someString);
and then in the onClick you can:
public void onClick(View v) {
Intent intent = new Intent(TourListActivity.this,
TourMenuActivity.class);
String info = tour.toString();
intent.putExtra(TOUR_INFO, ((Button)v).getTag());
startActivity(intent);
}
The variable tour is defined outside the loop, so each button share the same variable.
At each iteration, you just change the reference stored by this variable.
You could to create a final variable inside your loop, and use it inside the OnClickListener:
for (int i = 0; i < tourListArray.size(); i++) {
...
final String tourInfo = tour.info;
tour_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(
TourListActivity.this,
TourMenuActivity.class
);
intent.putExtra(TOUR_INFO, tourInfo);
startActivity(intent);
}
});
...
}