pass two strings from one activity to another - java

I am working on a tic tac toe application for android. In the Two player section, I've created an activity which will ask the two players to enter their names. For that I've used two EditTexts. The problem is That my app force closes while starting the next activity. Here is my code:
//Activity 1:
EditText player1field,player2field;
Button startbutton;
Intent startbuttonintent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_options);
setupActionBar();
player1field = (EditText) findViewById(R.id.player1field);
player2field = (EditText) findViewById(R.id.player2field);
startbuttonintent = new Intent(this, Activity2.class);
startbutton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String player1name = player1field.getText().toString();
String player2name = player2field.getText().toString();
startbuttonintent.putExtra("PLAYER1NAME",player1name);
startbuttonintent.putExtra("PLAYER2NAME",player2name);
startActivity(startbuttonintent);
}
});
}
this is activity 2
//Activity2
Intent startbuttonintent = getIntent();
TextView p1name,p2name;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_3m);
String player1name = startbuttonintent.getStringExtra("PLAYER1NAME");
String player2name = startbuttonintent.getStringExtra("PLAYER2NAME");
p1name = (TextView) findViewById(R.id.p1name);
p2name = (TextView) findViewById(R.id.p2name);
p1name.setText(player1name);
p2name.setText(player2name);
}
This code is not giving me any errors but my app force closes when I run it.
Please help me.
Thanks in advance.

Try this:
Activity 1:
EditText player1field,player2field;
Button startbutton;
Intent startbuttonintent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_options);
setupActionBar();
player1field = (EditText) findViewById(R.id.player1field);
player2field = (EditText) findViewById(R.id.player2field);
startbutton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String player1name = player1field.getText().toString();
String player2name = player2field.getText().toString();
startbuttonintent = new Intent(this, Activity2.class);
startbuttonintent.putExtra("PLAYER1NAME",player1name);
startbuttonintent.putExtra("PLAYER2NAME",player2name);
startActivity(startbuttonintent);
}
});
}
You have call this method before onclick which is causing error.
And fetch the intent text like this:
//Activity2
TextView p1name,p2name;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_3m);
Bundle extras = getIntent().getExtras();
String player1name = extras.getString("PLAYER1NAME");
String player2name = extras.getString("PLAYER2NAME");
p1name = (TextView) findViewById(R.id.p1name);
p2name = (TextView) findViewById(R.id.p2name);
p1name.setText(player1name);
p2name.setText(player2name);
}

String intArray[] = {"one","two"};
Intent in = new Intent(this, B.class);
in.putExtra("my_array", intArray);
startActivity(in);
For Reading :
Bundle extras = getIntent().getExtras();
String[] arrayInB = extras.getStringArray("my_array");

Take yout getIntent method inside onCreate method
//Activity2
TextView p1name,p2name;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_3m);
Intent startbuttonintent = getIntent();
String player1name = startbuttonintent.getStringExtra("PLAYER1NAME");
String player2name = startbuttonintent.getStringExtra("PLAYER2NAME");
p1name = (TextView) findViewById(R.id.p1name);
p2name = (TextView) findViewById(R.id.p2name);
p1name.setText(player1name);
p2name.setText(player2name);
}

Move Intent startbuttonintent = getIntent(); to inside your onCreate() method
getIntent() is a method in Activity, so you can't call it in a static class level initialization. You must call it only after your Activity object is ready, like when in the onCreate() method

#Chinmay Dabke Please get the id of the button "startbutton"
by using
startbutton = (Button)findviewbyId(R.id.startbutton);

Try This....in Activity1
Bundle bundle = new Bundle();
bundle .putString("PLAYER1NAME",player1name);
bundle .putString("PLAYER2NAME",player2name);
intent1.putExtras(bundle);
in Activity2
Bundle b = getArguments();
String player1name = b.getString("PLAYER1NAME");
String player2name = b.getString("PLAYER2NAME");

Related

How to pass an edittext string from an activity to a method in another activity?

I have 2 EditTexts and I want to copy the String of these EditTexts and use them in a method in another activity.
I was making an app which types some details in two EditTexts and have a button which copies the String of these two EditTexts and paste or use it in a RecyclerView in another Activity.
I tried the Intent and Bundle medthods but could not solve it and actually it was hard to arrange the structure of codes.
This is the activity I want to pass from:
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (etTitle.length() != 0 || etDes.length() != 0){
addData();
}else {
Toast.makeText(DataInput.this, "Please Add Data !", Toast.LENGTH_SHORT).show();
}
}
});
}
private void addData() {
String titled = etTitle.getText().toString();
String desed = etDes.getText().toString();
Intent inte = new Intent();
Bundle bund = new Bundle();
bund.putString("title", titled);
bund.putString("des", desed);
inte.putExtras(bund);
startActivity(inte);
}
This is the activity I want to receive with:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), DataInput.class);
startActivity(intent);
}
});
recyclerView = findViewById(R.id.rv);
dAdapter = new DataAdapter(dataList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(dAdapter);
}
public void sendData() {
Bundle bundle = getIntent().getExtras();
String addedTitle = bundle.getString("title");
String addedDes = bundle.getString("dec");
Data data = new Data(addedTitle, addedDes);
dataList.add(data);
dAdapter.notifyDataSetChanged();
}
All I want is to pass the intent and bundle from addData method in the first Activity to the sendData method in the second Activity, so I can use the Strings to pass them in Data constructor.
Use bundle or intent.
// From activity1 to activity2
Intent intent = new Intent(Activity1.this, Activity2.class);
Bundle bundle = new Bundle();
bundle.putString(<key>, <value>);
intent.putExtras(bundle);
startActivity(intent);
// in activity 2 onCreate
Bundle bundle = intent.getExtras();
if (bundle != null) {
// get the value from bundle based on key
}
Here is the short example pass data from activity to activity
I would recommend you to change your implementation in following way so that we can avoid key mismatch issue accidently.
#Override
public void onClick(View v) {
if (etTitle.length() != 0 || etDes.length() != 0){
String title = etTitle.getText().toString();
String description = etDes.getText().toString();
Activity2.launch(this,title,description);
} else {
Toast.makeText(DataInput.this, "Please Add Data !", Toast.LENGTH_SHORT).show();
}
}
In calling activity you may create helper method say launch like below.
public static final String KEY_TITLE = "title";
public static final String KEY_DESCRIPTION = "description";
public static void launch(Context context, String title, String description) {
Intent intent = new Intent(context, Activity2.class);
Bundle data = new Bundle();
data.putString(KEY_TITLE, title);
data.putString(KEY_DESCRIPTION, description);
intent.putExtras(data);
context.startActivity(intent);
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = intent.getExtras();
if (bundle != null) {
String title = bundle.getString(KEY_TITLE);
String description = bundle.getString(KEY_DESCRIPTION);
}
}
To retrieve the text from an EditText you can use editText.getText().toString()
To retrieve the text from an EditText use
String value = editText.getText().toString();
And then pass the key value pair either through intent or bundle
Intent in = new Intent(Activity1.this, Activity2.class);
in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
in.putExtra("key", value);
startActivity(in);
to receive put this in new activity
String string_name = getIntent().getExtras().getString("key");
Update:
There is key mismatch, you are sending key as "des" and receiving as "dec"

Passing a String to other activity did not work

So I have a textEdit field in MainActivity2. And I will pass the String of it to MainActivity8. You go to MainActivity8 if you click a Button.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2activity);
((Button) findViewById(R.id.weiter)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity2.this, MainActivity8.class);
EditText et1 = (EditText) findViewById(R.id.editText2);
String Link1 = et1.getText().toString();
EditText et = (EditText) findViewById(editText1);
String Kat1 = et.getText().toString();
if (Link1.matches("") || Kat1.matches("")){
et.setHintTextColor(RED);
et1.setHintTextColor(RED);
}
else {
startActivity(i);
}
Intent intent = new Intent(MainActivity2.this, MainActivity8.class);
intent.putExtra("Kate1", Kat1);
}
});
And MainActivity8 looks like this:
public class MainActivity8 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main8);
Intent intent = getIntent();
String Kategorie1 = intent.getExtras().getString("Kategorie1");
TextView tv = (TextView) findViewById(R.id. textView2);
tv.setText(Kategorie1);
}
}
So everytime when I click the Button my App is crashing. And i don't know whats wrong. I get this from the Android Monitor:
12-30 11:45:29.046 29591-29591/com.example.luca.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.luca.myapplication, PID: 29591
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.luca.myapplication/com.example.luca.myapplication.MainActivity8}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
Can you give me a tip whats wrong?
at first you are send your data using "Kate1" keyword
intent.putExtra("Kate1", Kat1);
and fetching data using key "Kategorie1" which is different
change
intent.getExtras().getString("Kategorie1");
to
intent.getExtras().getString("Kate1");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2activity);
((Button) findViewById(R.id.weiter)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText et1 = (EditText) findViewById(R.id.editText2);
String Link1 = et1.getText().toString();
EditText et = (EditText) findViewById(editText1);
String Kat1 = et.getText().toString();
if (Link1.matches("") || Kat1.matches("")){
et.setHintTextColor(RED);
et1.setHintTextColor(RED);
}
else {
Intent intent = new Intent(MainActivity2.this, MainActivity8.class);
intent.putExtra("Kate1", Kat1);
startActivity(intent );
}
}
});
and MainActivity8.class
public class MainActivity8 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main8);
String Kategorie1 =getIntent().getStringExtra("Kate1");
TextView tv = (TextView) findViewById(R.id. textView2);
tv.setText(Kategorie1);
}
}
You start intent i but not put extra value in intent i you put value Intent "intent".
your key is "Kate1" and on another activity you used "Kategorie1".
put same key brother.
check null before getString
Bundle bundle= getIntent().getExtras();
if (bundle!= null) {
link = bundle.getString("Kate1");
}
getIntent().getStringExtra("your putString value"));
This will work.
Actually the intent with which you are starting the activity ,in that intent's bundle you are not adding the string to be sent.
from your code,you are creating an intent i like this
Intent i = new Intent(MainActivity2.this, MainActivity8.class);
and starting the activity using that intent "i" , but you are not putting the string in that intent object.
so just your proper code should be like shown below :
((Button) findViewById(R.id.weiter)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity2.this, MainActivity8.class);
EditText et1 = (EditText) findViewById(R.id.editText2);
String Link1 = et1.getText().toString();
EditText et = (EditText) findViewById(editText1);
String Kat1 = et.getText().toString();
if (Link1.matches("") || Kat1.matches("")){
et.setHintTextColor(RED);
et1.setHintTextColor(RED);
}
else {
i.putExtra("Kate1",Kat1);
startActivity(i);
}
//remove this intent,as not required
}
});
and in the MainActivity8 , try to get the string with the same key Kate1
intent.getExtras().getString("Kate1");

Problems setting TextView value to a String got from Intent

So... My problem is that when I try to send Intent putExtra , get it in the new class and then put it into a TextView it returns null...
Here is my code:
final String phonenum = text.getText().toString();
Intent i = new Intent(sms_verification.this, sms_verification_two.class);
i.putExtra("num", num);
i.putExtra("phonenum" , phonenum);
startActivity(i);
And then the "sms_verification_two"
Button next;
EditText code;
TextView phone;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sms_verification2);
next = (Button)findViewById(R.id.button);
code = (EditText)findViewById(R.id.editText2);
phone = (TextView)findViewById(R.id.textView);
String phonenum = getIntent().getStringExtra("phonenum");
String num = getIntent().getStringExtra("num");
phone.setText(phonenum);
Try using this approach on your sms_verification_two activity
String phonenum = "";
String num = "";
Bundle extras = getIntent().getExtras();
if (extras != null) {
phonenum = extras.getString("phonenum");
num = extras.getString("num");
}
phone.setText(phonenum + num);
Make sure the data you put in the intent isn't null. The code itself looks fine to me.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button goToNextActivity=(Button) findViewById(R.id.bSendID);
final EditText etNum=(EditText) findViewById(R.id.etNumID);
final EditText etPhoneum=(EditText) findViewById(R.id.etPhoneumID);
goToNextActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String textFromEtNum=etNum.getText().toString();
String textFromEtPhoneum=etPhoneum.getText().toString();
Intent i = new Intent(getApplicationContext(), secondActivity.class);
i.putExtra("num", textFromEtNum);
i.putExtra("phonenum" , textFromEtPhoneum);
startActivity(i);
}
});
}
}
second activity:
public class secondActivity extends AppCompatActivity {
Button next;
EditText code;
TextView phone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
next = (Button)findViewById(R.id.button);
code = (EditText)findViewById(R.id.editText2);
phone = (TextView)findViewById(R.id.textView);
String phonenum = getIntent().getStringExtra("phonenum");
String num = getIntent().getStringExtra("num");
phone.setText(phonenum + " " + num);
}
}
First Activity
**if your text variable TextView or EditText then write**
String phonenum = text.getText().toString();
Intent i = new Intent(sms_verification.this, sms_verification_two.class);
i.putExtra("nums", num);
i.putExtra("phonenums" , phonenum);
startActivity(i);
Second Activity
public class sms_verification_two extends AppCompatActivity {
Button next;
EditText code;
TextView phone;
String phonenumss = "",numss = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
next = (Button)findViewById(R.id.button);
code = (EditText)findViewById(R.id.editText2);
phone = (TextView)findViewById(R.id.textView);
if(getIntent().getStringExtra("phonenums") != null){
phonenumss = getIntent().getStringExtra("phonenums");
}
if(getIntent().getStringExtra("nums") != null){
numss = getIntent().getStringExtra("nums");
}
phone.setText(" " +phonenumss + " " + numss);
}
}

How to send an ArrayList<String> to Another Activity and display there?

How to send an ArrayList to Another Activity and display there ?
I Want to get data from another activity and send it to another activity and get there printed. I am only able to pass single string but not an array of strings
Code On Java File,
Main Activity:
EditText et1 , et2 , et3 , et4 ;
public final static String MESSAGE_KEY = "com.example.prabhav.myapplication.message";
ArrayList<String> ar , tr = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_on);
}
public void sm (View v)
{
et1= (EditText) findViewById(R.id.name);
String msg1 = et1.getText().toString();
et2= (EditText) findViewById(R.id.dob);
String msg2 = et2.getText().toString();
et3= (EditText) findViewById(R.id.emailinput);
String msg3 = et3.getText().toString();
et4= (EditText) findViewById(R.id.clgi);
String msg4 = et4.getText().toString();
ar.add(msg1);
ar.add(msg2);
ar.add(msg3);
ar.add(msg4);
tr=ar;
Intent intent = new Intent(this,SecAct.class);
intent.putExtra("myarray",tr);
startActivity(intent);
}
Another Activity:
Spinner s;
public final static String MESSAGE_KEY = "com.example.prabhav.myapplication.message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent= getIntent();
ArrayList<String> ls = (ArrayList<String>) getIntent().getSerializableExtra("myarray");
ArrayAdapter<String> adptr=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,ls);
s= (Spinner) findViewById(R.id.sp);
s.setAdapter(adptr);
// setContentView(R.layout.sec_lay);
}
Once try as follows
MainActivity
Intent i = new Intent(this,SecAct.class);
i.putStringArrayListExtra("myarray", tr);
startActivity(i);
2nd Activity
ArrayList<String> list=(ArrayList<String>)getIntent().getStringArrayListExtra("myarray");
//use the list as you wish
Hope this will helps you.
try sending the arrayList using putParcelableArrayList like this:
Intent intent = new Intent(this,SecAct.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("myArray", (ArrayList<? extends android.os.Parcelable>) tr);
intent.putExtras(bundle);
startActivity(intent);
And you can get the arrayList in the second activity like this:
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
tr= bundle.getParcelableArrayList("myArray");}
i hope this will help

Passing value from one activity to another doesn't work

I tried looking on other questions but nothing seems to work. Trying to pass the value stored in sUsername from activity Username.java to MainActivity.java (username).
This is Username.java:
public class Username extends ActionBarActivity implements View.OnClickListener {
EditText eUsername;
Button login;
String sUsername;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_username);
eUsername = (EditText) findViewById (R.id.username);
sUsername = eUsername.getText().toString();
login = (Button)findViewById(R.id.login);
login.setOnClickListener(this);
}
private void loginClick() {
Intent intent = new Intent(this, MainActivity.class );
intent.putExtra("containsUsername", sUsername); //first argument is the name of the string being passed
startActivity(intent);
}
public void onClick (View v) {
switch (v.getId()) {
case R.id.login:
loginClick();
break;
}
}
and this is MainActivity.java
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String username = bundle.getString("containsUsername");
WebView listOfSongs = (WebView) findViewById (R.id.webview);
String url = "http://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user="+username+"&api_key=68f82cd7b37e7b23800c2025066531c9&format=json";
listOfSongs.loadUrl(url);
}
your loginCheck Method should be like this:
private void loginClick() {
sUsername = eUsername.getText().toString();
Intent intent = new Intent(this, MainActivity.class );
intent.putExtra("containsUsername", sUsername); //first argument is the name of the string being
startActivity(intent);
}
As in on create your edittext might be empty.
Please check your edittext is empty or not. Chnage your method longClick.
private void loginClick(){
if(!sUsername.isEmpty()) {
Intent intent = new Intent(this, MainActivity.class );
intent.putExtra("containsUsername", sUsername);
startActivity(intent);
} else {
Toast.makeText(Username.this, "Please enter username.", Toast.LENGTH_LONG).show();
}
}

Categories