exchange data between activities - android

I created 2 Activities, Main and Second. And I want to send text, put in the box EditText from Main to Second activity. Id of first EditText is UserName, and of the second is Description.
The code of the Main activity is:
package com.example.test;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.support.v4.app.NavUtils;
import android.content.Intent;
import android.widget.EditText;
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v) {
Intent intent = new Intent(Main.this, Second.class);
intent.putExtra("username", UserName.getText().toString());
intent.putExtra("gift", Description.getText().toString());
startActivity(intent);
}
public void ButtonOneClick(View v) {
switch (v.getId()) {
case R.id.button1:
Intent i = new Intent(this, Second.class);
startActivity(i);
break;
}
}
}
Full code of the Second Activity is:
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class Second extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
TextView txtInfo = (TextView)findViewById(R.id.TextOne);
String user = "ЖЫвотное";
String gift = "дырку от бублика";
user = getIntent().getExtras().getString("username");
gift = getIntent().getExtras().getString("gift");
txtInfo.setText(user + " , вам передали " + gift);
}
}
and errors:
main.java: Description cannot be resolved
main.java: UserName cannot be resolved
sorry for my english
Thanks for help
P.S. I'm studying java and programming for android just third day, please don't throw stones to me.

You'd then refer to your R class file, that is:
EditText desc = (EditText) findViewById(R.id.Description);
...

You have not included
EditText UserName = (EditText) findViewById(R.id.username);
EditText Description = (EditText) findViewById(R.id.description);
in your onCreate() method in MainActivity.

As you reference UserName and Description here refer to them as they are classes. Unless you have such classes an error will be stated because these classes can not be found (or "resolved").
You can even notice this by the syntax highlight. Do you see the words a displayed in a lght green/turquoise like Main or Intent?
public void onClick(View v) {
Intent intent = new Intent(Main.this, Second.class);
intent.putExtra("username", UserName.getText().toString());
intent.putExtra("gift", Description.getText().toString());
startActivity(intent);
}
Instead you want instances of the class EditText which you call userName and description. On these objects you can perform getText() and work your way along. :)
public void onClick(View v) {
Intent intent = new Intent(Main.this, Second.class);
EditText userName = (EditText) findViewById(R.id.username);
EditText description = (EditText) findViewById(R.id.description);
intent.putExtra("username", userName.getText().toString());
intent.putExtra("gift", description.getText().toString());
startActivity(intent);
}
Please notice I've changed the names of your variables to lowerCase starting camelCase. Though not an explicit rule it's considered good practise to start variable names with lower case letters ('userName,description,intent) while **C**lass references like (ÈditText,Main,Second`) are started with upper case letters.

you have not initialize the username & description in your java;
EditText us_name=(EditText) findViewById(R.id.user_name);
EditText us_desp=(EditText) findViewById(R.id.desp);

Related

how to add back button In Quiz App?

Please Give Me some Solution to add back button in quiz app
What I want to create is back button in my quiz app, the questions come from database. I want button to go to previous question without messing up.I am new to android can any one help me to solve the problem..
package in.gtarena.myquizapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import in.gtarena.myquizapp.db.DBAdapter;
import in.gtarena.myquizapp.model.Question;
public class ComputerActivity extends AppCompatActivity {
private List<Question> questionsList;
private Question currentQuestion;
private TextView txtQuestion,tvNoOfQs;
private RadioButton rbtnA, rbtnB, rbtnC,rbtnD;
private Button btnNext,btnBack;
private RadioGroup grp;
private int obtainedScore=0;
private int questionId=0;
private int answeredQsNo=0;
ArrayList<String> myAnsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_concept);
init();
btnBack = (Button) findViewById(R.id.btnBack);
grp=(RadioGroup)findViewById(R.id.radioGroup1);
//Initialize the database
final DBAdapter dbAdapter =new DBAdapter(this);
questionsList= dbAdapter.getQuestions();
currentQuestion =questionsList.get(questionId);
//Set question
setQuestionsView();
//Check and Next
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
Log.e("Answer ID", "Selected Positioned value - "+grp.getCheckedRadioButtonId());
if(answer!=null){
Log.e("Answer", currentQuestion.getANSWER() + " -- " + answer.getText());
//Add answer to the list
myAnsList.add(""+answer.getText());
if(currentQuestion.getANSWER().equals(answer.getText())){
obtainedScore++;
Log.e("comments", "Correct Answer");
Log.d("score", "Obtained score " + obtainedScore);
}else{
Log.e("comments", "Wrong Answer");
}
if(questionId < dbAdapter.rowCount()){
currentQuestion =questionsList.get(questionId);
setQuestionsView();
}else{
Intent intent = new Intent(ComputerActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", obtainedScore);
b.putInt("totalQs", questionsList.size());
b.putStringArrayList("myAnsList", myAnsList);
intent.putExtras(b);
startActivity(intent);
finish();
}
}else{
Log.e("comments", "No Answer");
}
//Need to clear the checked item id
grp.clearCheck();
}//end onClick Method
});
//Check and Back
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//WHAT SHOULD I DO HERE FOR GO BACK TO PREVIOUS QUESTION//
}
});
}
public void init(){
tvNoOfQs=(TextView)findViewById(R.id.tvNumberOfQuestions);
txtQuestion=(TextView)findViewById(R.id.tvQuestion);
rbtnA=(RadioButton)findViewById(R.id.radio0);
rbtnB=(RadioButton)findViewById(R.id.radio1);
rbtnC=(RadioButton)findViewById(R.id.radio2);
rbtnD=(RadioButton)findViewById(R.id.radio3);
btnNext=(Button)findViewById(R.id.btnNext);
myAnsList = new ArrayList<String>();
}
private void setQuestionsView()
{
rbtnA.setChecked(false);
rbtnB.setChecked(false);
rbtnC.setChecked(false);
rbtnD.setChecked(false);
answeredQsNo=questionId+1;
tvNoOfQs.setText("Questions "+answeredQsNo+" of "+questionsList.size());
txtQuestion.setText(currentQuestion.getQUESTION());
rbtnA.setText(currentQuestion.getOptionA());
rbtnB.setText(currentQuestion.getOptionB());
rbtnC.setText(currentQuestion.getOptionC());
rbtnD.setText(currentQuestion.getOptionD());
questionId++;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Are you using separate activity for every question?
If yes, then you can use onBackPressed method.
It would be easy for you to go back to question if you provide a id(ex.1,2,3..) for every question in database and take a variable named id and increment id every time you click the next button and fetch the question matching to the id and when you press back button the decrement id and fetch the question again...
Just decrement questionid in back button listener and call the questions again
You can do this by two approaches :
Create a button and than link that button to the previous activity
Create a method onBackPressed like this code :
#Override
public void onBackPressed() {
Intent intent = new Intent(OrderList.this, MainActivity.class);
startActivity(intent);
}
You can simply use the second code in any activity to lead you back to previous activity.
Hope this helps !!

Android R.id error

I have the following code and have an error in action_settings in R.id.action_settings. This is in the last method posted here so scroll down. I am not sure what is supposed to go in here. I am trying to create an app that has a login page at the start, with the potential to create a new user id in a registration page, take a picture in another page, and see a menu in another page.
package com.example.reynaldo.project1;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu (Menu menu){
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onButtonClick (View v){
if (v.getId() == R.id.Blogin) {
EditText a = (EditText) findViewById(R.id.TFemail);
String str = a.getText().toString();
EditText b = (EditText) findViewById(R.id.TFpassword);
String pass = b.getText().toString();
String password = helper.searchPass(str);
if (pass.equals(password)) {
Intent i = new Intent(MainActivity.this, Display.class);
i.putExtra("Email", str);
startActivity(i);
} else {
Toast temp = Toast.makeText(MainActivity.this, "Username and password don't match", Toast.LENGTH_SHORT);
temp.show();
}
}
if (v.getId() == R.id.Bsignup){
Intent i = new Intent (MainActivity.this, SignUp.class);
startActivity(i);
}
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
int id = item.getItemId();
if (id == R.id.action_settings){
return true;
}
return onOptionsItemSelected(item);
}
}
You have missed to import R.
import youPackage.R;
This way you can manually import R.
Please replace yourPackage with your package name of application. You can find it in your Manifest.xml file or with build.gradle file.
import com.example.reynaldo.project1.R
in your file and check you have a menu item with id action_settings and rebuild project.
Most likely your R.menu.main xml file does not contain an item having #+id/action_settings as its id. Check your R.menu.main xml file and make sure the action_settings id is set
import yourpackagename.R;
For Ex:
import com.example.reynaldo.project1.R;
Check in your menu file and make sure you have created item with
id = action_settings

Get the calculation of random numbers to compare with an EditText

Recently I have been trying how to get the calculation of two random numbers that are shown in MainActivity to compare later with the text field and indicate if the number inserted is correct or no.
Here the code:
MainActivity.java
package com.example.miguel.myfirstapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
Random random = new Random();
int randomNum = random.nextInt(101);
int randomNum2 = random.nextInt(101);
String messageRandomNum = String.valueOf(randomNum);
String messageRandomNum2 = String.valueOf(randomNum2);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textViewRandomNum = (TextView) findViewById(R.id.random_num);
textViewRandomNum.setText(messageRandomNum);
messageRandomNum2 = String.valueOf(randomNum2+ "= ");
TextView textViewRandomNum2 = (TextView) findViewById(R.id.random_num2);
textViewRandomNum2.setText(messageRandomNum2);
}
public int getCalculation(){
//Here is where I had tried to get the calculation of the same numbers that are shown in the screen
int calculation = randomNum + randomNum2;
return calculation;
}
public void sendMessage (View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
DisplayMessageActivity.java
package com.example.miguel.myfirstapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
public class DisplayMessageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
MainActivity mainActivity = new MainActivity();
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
int messageInt = Integer.parseInt(message);
TextView textView = new TextView(this);
textView.setTextSize(40);
//The comparison of editText and the calculation
if(messageInt == mainActivity.getCalculation()){
textView.setText("Correct!");
}else{
textView.setText("Incorrect!");
}
ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
layout.addView(textView);
}
}
Always is shown that the inserted number (although it is well) shows "Incorrect!". I don't know why the calculation does a sum of random numbers, but not the random numbers than are shown in the screen.
If you don't understand something, sorry, I'm a Spanish speaker.
Regards! ;)
In MainActivity you can send calculated result
public void sendMessage (View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
int calcualtedResult=getCalculation();
intent.putInt("calcualtedResult", calcualtedResult);
startActivity(intent);
}
In DisplayMessageActivity
you can get the intent
int calculatedRes=intent.getInt("calculatedResult");
if(messageInt == calculatedRes){
textView.setText("Correct!");
}else{
textView.setText("Incorrect!");
}
wrong thing in your code is that you create an object from MainActivity in your DisplayMessageActivity. this object differ from activity that call DisplayMessageActivity and hasn't your random numbers. you must send random numbers with intent to next Activity, like EXTRA_MESSAGE.

Passing String to another Activity not possible

I have tried a lot of times and in different ways to pass a string from one activity (LoginActivity) to another one (SettingsActivity). Of course I did a lot of research and tried each provided solution, but nothing could help me until now
LoginActivity.class:
package com.naderk.pds;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.kosalgeek.genasync12.AsyncResponse;
import com.kosalgeek.genasync12.PostResponseAsyncTask;
import com.naderk.pds.contexts.ContextServerActivity;
import java.util.HashMap;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
final String LOG = "LoginActivity";
Button btnLogin, btnRegister;
EditText etUsername, etPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnRegister = (Button) findViewById(R.id.bRegister);
btnLogin.setOnClickListener(this);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent seeTasksIntent= new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(seeTasksIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, 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);
}
#Override
public void onClick(View view) {
HashMap postData = new HashMap();
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
postData.put("txtUsername", username);
postData.put("txtPassword", password);
PostResponseAsyncTask task1 = new PostResponseAsyncTask(LoginActivity.this, postData, new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(LOG, s);
if(s.contains("success")){
Toast.makeText(LoginActivity.this, "Login successful", Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(LoginActivity.this, "Wrong username or password. Please register and try again.", Toast.LENGTH_LONG).show();
}
}
});
task1.execute("http://192.168.0.11/customer/");
visitactivity1();
}
public void visitactivity1() {
Intent i = new Intent(LoginActivity.this, SettingsActivity.class);
Bundle bundle = new Bundle();
bundle.putString("key", etUsername.getText().toString());
i.putExtras(bundle);
startActivity(i);
finish();
}
}
SettingsActivity.class:
package com.naderk.pds;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.content.Intent;
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
TextView textView = (TextView) findViewById(R.id.tvUserName);
Bundle bundle = getIntent().getExtras();
String stuff = bundle.getString("key");
textView.setText(stuff);
}
}
Logcat:
Exceeds 30.000 characters lol
I really hope that someone is able to help me.
Cheers!
Try this
public void visitactivity1() {
Intent i = new Intent(LoginActivity.this, SettingsActivity.class);
i.putExtra("key", etUsername.getText().toString());
startActivity(i);
finish();
}
and on the second activity
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
TextView textView = (TextView) findViewById(R.id.tvUserName);
String stuff = getIntent().getStringExtra("key");
textView.setText(stuff);
}
}
Hope it helps (:
You can add the putExtras
if(s.contains("success")){
Toast.makeText(LoginActivity.this, "Login successful", Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("passwordText", password.getText().toString());
intent.putExtra("usernameText",username.getText().toString());
startActivity(intent);
On your second activity implement the following within your onCreate() method
Intent intent = getIntent();
String password = intent.getStringExtra("passwordText");
String username = intent.getSringExtra("usernameText");
You can read this blog for more information about intents : What are intents
In summary is a tutorial about how to implement intents. It may help you in case you want to change your structure.
Finally, I´m not sure if this is the way you wanted to pass the data : instead use it as I recommend. I hope it helps !
postData.put("txtUsername", username);
postData.put("txtPassword", password);
You can use Bundle methods to to send and receive Strings across your Activity class.

Switching activities (at the same time resetting text field) don't change smoothly

I'm working on an android app. I created log in form in one activity and after log in it switches to another activity. I'm trying to reset EditText field while switching activity but while clicking on login button, it shows the edittext box before switching. It should switch smoothly, not showing the text box. Below my code, what can I do to make better?
package com.mtilab.blogspot.imtiapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;
import android.content.Intent;
public class MainActivity extends AppCompatActivity {
private TextView messageRef;
private EditText usernameRef, passwordRef;
private Button submitRef, signupRef;
//user and pass for test case
private String user = "admin", pass = "admin";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageRef = (TextView)findViewById(R.id.loginTV);
usernameRef = (EditText)findViewById(R.id.usernameET);
passwordRef = (EditText)findViewById(R.id.passwordET);
submitRef = (Button)findViewById(R.id.loginB);
signupRef = (Button)findViewById(R.id.registrationB);
//submitref is ref of login button
submitRef.setOnClickListener(
new View.OnClickListener(){
public void onClick(View vw){
if(usernameRef.getText().toString().equals(user) &&
passwordRef.getText().toString().equals(pass)){
Intent userIntent = new Intent(MainActivity.this, User.class);
startActivity(userIntent);
usernameRef.setText("");
passwordRef.setText("");
messageRef.setText("");
} else{
messageRef.setText("U R Not You!");
passwordRef.setText("");
}
}
}
);
}
// way 2 , when login button pressed
/*public void onClickLoginButton(View view) {
messageRef = (TextView)findViewById(R.id.loginTV);
usernameRef = (EditText)findViewById(R.id.usernameET);
passwordRef = (EditText)findeViewById(R.id.passwordET);
if(usernameRef.getText().toString().equals(user) &&
passwordRef.getText().toString().equals(pass)){
Intent userIntent = new Intent(this, User.class);
startActivity(userIntent);
usernameRef.setText("");
passwordRef.setText("");
messageRef.setText("");
}else{
messageRef.setText("U R Not You!");
passwordRef.setText("");
}
}*/
}
You can hide all Views before starting the next activity:
submitRef.setOnClickListener(
new View.OnClickListener(){
public void onClick(View vw){
if(usernameRef.getText().toString().equals(user) &&
passwordRef.getText().toString().equals(pass)){
usernameRef.setVisibility(View.INVISIBLE);
passwordRef.setVisibility(View.INVISIBLE);
messageRef.setVisibility(View.INVISIBLE);
// you might want to keep that
usernameRef.setText("");
passwordRef.setText("");
messageRef.setText("");
Intent userIntent = new Intent(MainActivity.this, User.class);
startActivity(userIntent);
} else{
messageRef.setText("U R Not You!");
passwordRef.setText("");
}
}
}
);
Using View.INVISIBLE will just hide the View, but it will still occupy space in the layout. If you do not want that, use View.GONE.
For more info, see the documentation.

Categories

Resources