Passing data between activities for a voting app - java

I am new to android programming and have ran into a problem. I am trying to create a voting app where when a user opens up the application and the MainActivity is shown, from here they press a button to go into the second Screen (Screen2) which shows images of people and their names as buttons. When a persons name (in a button on Screen2) is pressed , a text field shows the number of times the button is pressed in an another activity (Screen4) . The problem here is that when i try to show this (Screen4), the app crashes. I am quite new to this so if you didn't understand my issue or need more information please let me know. Any help is appreciated. Thank you.
EDIT : After some help I used Intent to try send the data across but now when when the button in screen2 is pressed the app refreshes and then takes me back to the mainActivity and when this process is tried again the app crashes.
This is the new Screen2 :
package com.example.myapplication1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class Screen2 extends AppCompatActivity {
TextView showValue;
int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen2);
showValue = findViewById(R.id.VoteCountAnnie);//VoteCountAnnie is the On click for the Textview in a different activity.
}
public void AnCount(View v) {
//increase the count
counter++;
showValue.setText(Integer.toString(counter));
}
public void ButtonToGoToTheOtherActivity(View v) {
Intent intent = new Intent(this, Screen4.class);
intent.putExtra("valueOfCounter", counter); //the code for sending data to the other activity.
startActivity(intent);
}
}
This is the XML for screen 2 :
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".Screen2">
<Button
android:id="#+id/AnnieBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginLeft="32dp"
android:text="#string/annie_liou"
android:onClick="AnCount"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView5"
/>
This is my Screen4:
package com.example.myapplication1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Screen4 extends AppCompatActivity {
private Button Button3;
int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen4);
Button3 = (Button) findViewById(R.id.Button3);
Button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) { openActivity4();
}
}
);
counter = getIntent().getIntExtra("valueOfCounter", 0); // 0 is default value
}
public void openActivity4() {
Intent intent = new Intent(Screen4.this, MainActivity.class);
startActivity(intent);
}
}
Here is the XML for screen4:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/MainScreen"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Screen4">
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="193dp"
android:layout_marginLeft="193dp"
android:layout_marginEnd="109dp"
android:layout_marginRight="109dp"
android:layout_marginBottom="660dp"
android:text="This is 4th screen"
android:textSize="32sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.664"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/Button3" // return to main screen
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="532dp"
android:text="Return"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView5" />
<TextView
android:id="#+id/VoteCountAnnie" // textview where i want the increment to show
android:layout_width="121dp"
android:gravity="center"
android:layout_height="52dp"
android:layout_marginStart="116dp"
android:layout_marginLeft="116dp"
android:layout_marginTop="82dp"
android:layout_marginEnd="174dp"
android:layout_marginRight="174dp"
android:text="0"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView5" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is my main Activity Screen (not used for the clicking but if there is something wrong in this that could affect the other Screens please let me know) :
package com.example.myapplication1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button button;
private Button button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivity2();
}
});
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
openActivity3();
}
}
);
}
public void openActivity2() {
Intent intent = new Intent(this, Screen2.class);
startActivity(intent);
}
public void openActivity3() {
Intent intent = new Intent(this, Screen3.class);
startActivity(intent);
}
}
Here is the XML for screen 4:

This works same using intent .
Main Class :
package com.example.cameraone;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
public static String EXTRA_VOTE_KEY = "com.example.cameraone.EXTRA_VOTE_KEY";
private Button counter,show;
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState != null){
count = savedInstanceState.getInt(EXTRA_VOTE_KEY);
}
counter = findViewById(R.id.bt_counter);
show = findViewById(R.id.bt_show);
counter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
}
});
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
go();
}
});
/* Intent intent = new Intent(this,DisplayCount.class);
//intent.putExtras(intent);
startActivity(intent,bundle);*/
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(EXTRA_VOTE_KEY,count);
}
public void go(){
Intent intent = new Intent(this,DisplayCount.class);
intent.putExtra(EXTRA_VOTE_KEY,count);
startActivity(intent);
}
}
Activity of Main Class :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
tools:context=".MainActivity">
<Button
android:id="#+id/bt_counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="PressMe"
/>
<Button
android:id="#+id/bt_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/bt_counter"
android:text="Done"
/>
</RelativeLayout
Display Class :
package com.example.cameraone;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
public class DisplayCount extends AppCompatActivity{
private TextView textView;
private int count;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_count_activity);
textView = findViewById(R.id.tv_vote_count);
Intent intent = getIntent();
count = intent.getIntExtra(MainActivity.EXTRA_VOTE_KEY,0);
textView.setText(Integer.toString(count));
}
}
Activity of display class :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center">
<TextView
android:id="#+id/tv_vote_count"
android:layout_width="wrap_content"
android:inputType="number"
android:layout_height="wrap_content"
android:textStyle="bold"
android:maxLength="10"/>
</RelativeLayout>
Manifest :
include following in your manifest file :
<activity android: name =".DisplayCount"></activity>

add following to manifest :
// Main Activity //
- List item
package com.example.cameraone;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
public static String EXTRA_VOTE_KEY = "com.example.cameraone.EXTRA_VOTE_KEY";
private Button counter,show;
private int count = 0;
#Override
protected void onCreate(#Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = findViewById(R.id.bt_counter);
show = findViewById(R.id.bt_show);
counter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
}
});
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
go();
}
});
}
public void go(){
DisplayCount.setVoteCount(count);
Intent intent = new Intent(this, DisplayCount.class);
startActivity(intent);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(EXTRA_VOTE_KEY,count);
}
}
/** Class to display: **/
- List item
package com.example.cameraone;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
public class DisplayCount extends AppCompatActivity{
private TextView textView ;
private static int count ;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_count_activity);
textView = findViewById(R.id.tv_vote_count);
textView.setText(Integer.toString(count));`enter code here`
}
public static void setVoteCount(int c){
count = c;
}
}
/***** Activity files *****/
- List item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center">
<TextView
android:id="#+id/tv_vote_count"
android:layout_width="wrap_content"
android:inputType="number"
android:layout_height="wrap_content"
android:textStyle="bold"
android:maxLength="10"/>
</RelativeLayout>
/**** Activity That display's ****/
-List item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
tools:context=".MainActivity">
<Button
android:id="#+id/bt_counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="PressMe"
/>
<Button
android:id="#+id/bt_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/bt_counter"
android:text="Done"
/>
</RelativeLayout>

As Mike M. said you are using id of a textview which is in a different activity. In android we cannot access ids of views in a different activity. We can only access ids of view in the same activity in which we are.
So that is for the error you are getting.
For accessing Data from another activity you can pass the data like this:
public class Screen2 extends AppCompatActivity {
int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen1);
showValue = (TextView) findViewById(R.id.VoteCountAnnie);//VoteCountAnnie is the Id for the Textview in a different activity.
}
public void AnnieCountInc (View view) {
//increase the count
counter++;
showValue.setText(Integer.toString(counter));
}
//make another button with a method like
public void ButtonToGoToTheOtherActivity(View view){
Intent intent =new Intent(this,Screen4.class);
intent.putExtra("valueOfCounter",counter); //the code for sending data to the other activity.
startActivity(intent);
}
Then in your Screen4 activity you can get the value of "counter" in the onCreate method by:
counter = getIntent().getIntExtra("valueOfCounter",0); // 0 is default value
This is one method.
You can also use a static variable to pass on data easily by defining your counter varaible as
public static int counter;
Then you can access it directly and it will show you the value.

Related

Why are the buttons not working when i run the app?

My app doesn't response when i type
Android app project that has two (2) text fields and one (1) button. The button will
compare the input from the text fields and display a response (SAME if values are the same
and NOT THE SAME if they are not) if it is clicked. You may need to create a new activity
for this.
package com.demesaict203.fieldchecker;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button checkbtn = (Button)findViewById(R.id.checkBtn);
checkbtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
EditText firstttextEditText = (EditText) findViewById(R.id.firsttextEditText);
EditText secondtextEditText = (EditText) findViewById(R.id.secondtextEditText);
if (firstttextEditText.equals(secondtextEditText)){
Intent sameTextIntent = new Intent(getApplicationContext(),SameText.class);
startActivity(sameTextIntent);
}
else{
Intent notsameTextIntent = new Intent(getApplicationContext(),NotTheSame.class);
startActivity(notsameTextIntent);
}
}
});
}
}
Here is my XML code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/checkButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/firsttextEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/enter_word"
android:inputType="textPersonName"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:autofillHints="" tools:targetApi="o" />
<EditText
android:id="#+id/secondtextEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/enter_word"
android:importantForAutofill="no"
android:inputType="textPersonName"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/firsttextEditText" />
<Button
android:id="#+id/checkBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/check"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/secondtextEditText" />
</androidx.constraintlayout.widget.ConstraintLayout>
first of all, you can't compare two EditText references together to get the result of text values equality.
you can get the text wrote in the editText using getText() method
then start to compare both strings values.
also, I suggest declaring EditText out of scope setOnClickListener so that not declare new instances every time the user click button.
so your final java code can be like :
package com.demesaict203.fieldchecker;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText firstttextEditText = (EditText) findViewById(R.id.firsttextEditText);
EditText secondtextEditText = (EditText) findViewById(R.id.secondtextEditText);
Button checkbtn = (Button) findViewById(R.id.checkBtn);
checkbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String firstValue = firstttextEditText.getText().toString();
String secondValue = secondtextEditText.getText().toString();
if (firstValue.equals(secondValue)) {
Intent sameTextIntent = new Intent(getApplicationContext(), SameText.class);
startActivity(sameTextIntent);
} else {
Intent notsameTextIntent = new Intent(getApplicationContext(), NotTheSame.class);
startActivity(notsameTextIntent);
}
}
});
}
}
I suggest you learn more about EditText from here
you are comparing the EditText, not the text inside the edit text. maybe change your codes to something like this.
String firstttextEditText = findViewById(R.id.firsttextEditText)).getText().toString();
String secondtextEditText = findViewById(R.id.secondtextEditText).getText().toString();
if (firstttextEditText.equals(secondtextEditText)){
Intent sameTextIntent = new Intent(getApplicationContext(),SameText.class);
startActivity(sameTextIntent);
}
else{
Intent notsameTextIntent = new Intent(getApplicationContext(),NotTheSame.class);
startActivity(notsameTextIntent);
}

How to make different activities in android communicate properly and send intents?

I'm following this guide: https://developer.android.com/training/basics/firstapp/starting-activity.html
And trying to send a message between activities.I want the user to enter text in the main activity, press send and have it show up in a different activity. For some reason, after I play the app on my phone and press the "send" button that's supposed to transfer intent and message content to the next activity - it just shows a blank activity.
I think that I may not have needed to change content_main, as I got a little confused with this xml file and activity_main and was not sure where each chunks of code should go.
Current code:
MainActivity.java
package com.example.myfirstapp;
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.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** Called when the user clicks the Send button */
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.myfirstapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
public class DisplayMessageActivity extends AppCompatActivity {
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** Called when the user clicks the Send button */
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);
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage"
/>
</LinearLayout>
activity_display_message.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.myfirstapp.DisplayMessageActivity"
android:id="#+id/activity_display_message"
>
</RelativeLayout>
content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage"
/>
</LinearLayout>
Edit
public class DisplayMessageActivity extends AppCompatActivity {
public class MainActivity extends AppCompatActivity {
in question.
In the new Activity,i.e DisplayMessageActivity.java retrieve those values:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString(EXTRA_MESSAGE);
//The key argument here must match that used in the other activity
EditText editText = (EditText) findViewById(R.id.edit_message);
editText .setText(value)
}
}
Use this technique to pass variables from one Activity to the other.
You have to declare a TextView inside your activity_display_message.xml
<TextView
android:id="#+id/show_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Then in your DisplayMessageActivity.java
public class DisplayMessageActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle bundle = getIntent().getExtras();
String message = bundle.getString(EXTRA_MESSAGE);
TextView textView = (TextView) findViewById(R.id.show_message);
textView.setText(message);
}
}
If you want to get the extraString in DisplayMessageActivity, that you have sent from previous activity MainActivity try this
// try this in onCreate() of DisplayMessageActivity
String myExtraString = getIntent.getStringExtra(EXTRA_MESSAGE);
if(myExtraString == null )
{ // no extraString was attached to the intent
}

in this program passing ArrayList from one activity to another not working

first activity:
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;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private Button bt1;
private Button bt2;
private EditText ed1;
private EditText ed2;
private TextView tv3;
static ArrayList<String> s = new ArrayList<>();
static ArrayList<Integer> i = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt1 = (Button)findViewById(R.id.button);
ed1 = (EditText) findViewById(R.id.editText);
ed2 = (EditText)findViewById(R.id.editText2);
bt2 = (Button)findViewById(R.id.button2);
tv3 = (TextView)findViewById(R.id.textView3);
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
s.add(ed1.getText().toString());
i.add(Integer.parseInt(ed2.getText().toString()));
}
});
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent intent = new Intent(MainActivity.this, second.class);
intent.putExtra("key", s);
startActivity(intent);
}
catch(Exception e) {
tv3.setText(e.getMessage());
}
}
});
}
}
Second activity:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.widget.TextView;
import java.util.ArrayList;
public class second extends AppCompatActivity {
private TextView tv1;
private TextView tv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
tv1 = (TextView)findViewById(R.id.textView);
tv2 = (TextView)findViewById(R.id.textView2);
ArrayList<String> s = (ArrayList<String>)getIntent().getSerializableExtra("key");
for(int j=0;j<=s.size();j++) {
tv1.setText(s.get(j));
}
}
}
I don't understand the problem in this code. when I click on bt2 to pass the ArrayList from on activity to another then the app just shutdown. I am not able to understand the problem in this code.
Please help me,
I have also updated the manifest.xml for second class.
Are you sure
i.add(Integer.parseInt(ed2.getText().toString()));
in the onClick() call doesnt throw an Exception?
Use a try-catch block around your code in Listener.onClick().
Btw., you can easily use Lambda Exrpessions for ActionListeners.
https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
Please use following construct:-
While Sending:
intent.putStringArrayListExtra("key", s)
While Receiving:
ArrayList<String> s = getIntent().getStringArrayListExtra("key");
Replace your for loop with below, use j< s.size and not j<=s.size
for(int j=0;j<s.size();j++)
{
tv1.setText(s.get(j));
}
You can do like this :
Bundle info= new Bundle();
ArrayList<Product> mas = new ArrayList<Product>();
info.putSerializable("product", mas);
intent.putExtras(info);
And get the values with this:
ArrayList<Product> prod = getIntent().getSerializableExtra(key);
Product class like a serializable object
private class Product implements Serializable {
}
Here it is just how you can pass arraylist between activities.Hope you wil get an idea to solve your issues.
intent.putExtra("key", s);-- this is wrong, you are sending a string but not your arrayList
Try sending with-- intent.putStringArrayListExtra("key", s);
and receiving -- ArrayList<String> stringArray = getIntent().getStringArrayListExtra("key");
hope this will solve your problem...
In your second activity onCreate, add the following code:
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
// Add view
// Must add check extras if null.
Bundle extras = getIntent().getExtras();
ArrayList<String> s = extras.getStringArrayListExtra("key");
// do something
}
In your first activity, send intent with:
Intent intent = new Intent(MainActivity.this, second.class);
intent.putStringArrayListExtra("key", s);
startActivity(intent);
I've tried an sample app with your code. Hope this will help you.
Kindly check my codes.
First Activity
package com.arindam.testapp;
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;
import java.util.ArrayList;
public class FirstActivity extends AppCompatActivity {
Button bt1;
EditText ed1;
EditText ed2;
TextView tv3;
ArrayList<String> s = new ArrayList<>();
ArrayList<String> i = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
bt1 = (Button)findViewById(R.id.button);
ed1 = (EditText) findViewById(R.id.editText);
ed2 = (EditText)findViewById(R.id.editText2);
tv3 = (TextView)findViewById(R.id.textView);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
s.add(ed1.getText().toString());
i.add(ed2.getText().toString());
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("key", s);
intent.putExtra("value", i);
startActivity(intent);
}
catch(Exception e)
{
tv3.setText(e.getMessage());
}
}
});
}
}
First Activity Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#679667"
android:orientation="vertical"
tools:context="com.arindam.testapp.FirstActivity">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
</LinearLayout>
Second Activity
package com.arindam.testapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.util.ArrayList;
public class SecondActivity extends AppCompatActivity {
private TextView tv1;
private TextView tv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
tv1 = (TextView)findViewById(R.id.textView);
tv2 = (TextView)findViewById(R.id.textView2);
ArrayList<String> s = getIntent().getStringArrayListExtra("key");
for(int j=0;j<s.size();j++)
{
tv1.setText(s.get(j));
}
ArrayList<String> i = getIntent().getStringArrayListExtra("value");
for(int k=0;k<i.size();k++)
{
tv2.setText(i.get(k));
}
}
}
Second Activity Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#229597"
android:orientation="vertical"
tools:context="com.arindam.testapp.SecondActivity">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"/>
</LinearLayout>
If you want to work with key value pairs, go for hashMap.

Android Button findViewByID returns null

I had three button on my main form. I added a third. When I try to assign the button using findViewById a null is returned.
This is my main.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" android:weightSum="1" android:clickable="false">
<TextView android:layout_width="wrap_content"
style="#style/TitleText"
android:text="#string/app_name"
android:background="#drawable/black_gradient">
</TextView>
<Button android:id="#+id/btnvalidatemark"
android:background="#drawable/grad_btn_green"
style="#style/ButtonText" android:text="#string/validate_mark_button">
</Button>
<Button android:id="#+id/btncheckregistry"
android:background="#drawable/grad_btn_yellow"
style="#style/ButtonText" android:text="#string/check_registry_button">
</Button>
<Button android:id="#+id/btnregcreds"
android:background="#drawable/grad_btn_red"
style="#style/ButtonText" android:text="#string/registry_config_button">
</Button>
</TableLayout>
This is my Activity code:
package uid.android.uidchecker;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.util.Log;
public class UIDCheckerActivity
extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
Button validatebutton = (Button) findViewById(R.id.btnvalidatemark);
Button checkbutton = (Button) findViewById(R.id.btncheckregistry);
Button setcredbutton = (Button) findViewById(R.id.btnregcreds);
validatebutton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(UIDCheckerActivity.this, SelectFileActivity.class);
i.putExtra("func", "validatemark");
startActivity(i);
}
});
checkbutton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//Intent i = new Intent(UIDCheckerActivity.this, validatemark.class);
Intent i = new Intent(UIDCheckerActivity.this, SelectFileActivity.class);
i.putExtra("func", "checkregisrty");
startActivity(i);
}
});
setcredbutton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(UIDCheckerActivity.this, RegistryCredsActivity.class);
startActivity(i);
}
});
}
}

how to create button on android platform

I created a button in my Android project, but it's not working.
Here is my application (based on 'hello world'):
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
<Button android:id="#+id/button_roy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>
and this is my java roy.java
package aa.aa.aaaaaaa.royb;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
/**
* Created by royb on 05/11/13.
*/
public class roy extends Activity {
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button createBtn = (Button) findViewById(R.id.button_roy);
createBtn.setOnClickListener(new View.OnClickListener()
{
public void onClick (View v)
{
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
});
}
}
When I run it on my android device and click the button it doesn't do anything.
How can I make the toast display?
public class Roy extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button createBtn = (Button) findViewById(R.id.button_roy);
createBtn.setOnClickListener(new View.OnClickListener()
{
public void onClick (View v)
{
Toast.makeText(getApplicationContext,"HelloToast",Toast.LENGTH_SHORT).show();
}
}
}

Categories

Resources