Intent and Edit Text Issues - android

I am basically trying to create an application which consists of 2 activities.
In activity 1 , user can enter 2 values in 2 separate edit text fields and I have provided a spinner drop down item , using which user can select either of 2 values.
If user selects option as 1 and clicks on Submit button , user will be displayed a second activty with value displayed as per the id selected in spinner object in previous activity.
Like if user selects 1 , value in first edit text box gets shown and if he selects 2 , then second edit text box value is displayed.
Also, when user clicks on submit button in second activity , based on value he enters in edit text field of second activity , it will get displayed in either edit text box 1 or edit text box 2 of previous activity .
I am having issues understanding why my app is showing bizarre behaviour. Please guide me.
FIRST ACTIVITY FILE:
package spinnner.intents.understand;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class TwoAppsActivity extends Activity {
/** Called when the activity is first created. */
String [] items = {"1","2"};
//String ch;
TextView tv;
EditText et1,et2;
Spinner spinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv=(TextView) findViewById(R.id.txt);
et1=(EditText) findViewById(R.id.edittxt1); // value 1
et2=(EditText) findViewById(R.id.edittxt2); // value 2
spinner=(Spinner) findViewById(R.id.spin1); // select
//
Intent i3 = getIntent();
if(i3.getStringExtra("spinner.intents.understand.value1")!=null)
{
et1.setText(i3.getStringExtra("spinner.intents.understand.value1"));
}
else if(i3.getStringExtra("spinner.intents.understand.value2")!=null)
{
et2.setText(i3.getStringExtra("spinner.intents.understand.value2"));
}
else
{
Toast.makeText(getApplicationContext(), "Enter some text ", Toast.LENGTH_LONG).show();
}
// spinner logic
ArrayAdapter<String> as1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, items);
as1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(as1);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
tv.setText(items[arg2]);
Toast.makeText(getApplicationContext(), " You selected : "+items[arg2],Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "You selected nothing", Toast.LENGTH_LONG).show();
}
});
//
}
public void Submit(View v)
{
Intent i = new Intent(this,Second.class);
startActivity(i);
//str1 = et1.getText().toString();
//Toast.makeText(getApplicationContext(), str1, Toast.LENGTH_LONG).show();
// str2 = et2.getText().toString();
//Toast.makeText(getApplicationContext(), str2, Toast.LENGTH_LONG).show();
//
if(spinner.getSelectedItem().toString()=="1")
{
Toast.makeText(getApplicationContext(), "I am in 1st option", Toast.LENGTH_LONG).show();
i.putExtra("spinner.intents.understand.value1", et1.getEditableText().toString());
i.putExtra("spinner.intents.understand.Id1", "1");
}
else if(spinner.getSelectedItem().toString()=="2")
{
Toast.makeText(getApplicationContext(), "I am in 2nd option", Toast.LENGTH_LONG).show();
i.putExtra("spinner.intents.understand.value2", et2.getEditableText().toString());
i.putExtra("spinner.intents.understand.Id2", "2");
}
else
{
Toast.makeText(getApplicationContext(), "You selected nothing!!!", Toast.LENGTH_LONG).show();
}
}
}
SECOND ACTIVITY FILE
package spinnner.intents.understand;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Second extends Activity{
/** Called when the activity is first created. */
TextView Tv;
EditText Et;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
//
Tv=(TextView) findViewById(R.id.txtS1);
Et=(EditText) findViewById(R.id.edittxtS1);
//
Intent i1 = getIntent();
if((i1.getStringExtra("spinner.intents.understand.Id1"))=="1")
{
Toast.makeText(getApplicationContext(), "I am in value 1", Toast.LENGTH_LONG).show();
Et.setText(i1.getStringExtra("spinner.intents.understand.value1"));
}
else if((i1.getStringExtra("spinner.intents.understand.Id2"))=="2")
{
Toast.makeText(getApplicationContext(), "I am in value 2", Toast.LENGTH_LONG).show();
Et.setText(i1.getStringExtra("spinner.intents.understand.value2"));
}
else
{
Toast.makeText(getApplicationContext(), "Some mismatch", Toast.LENGTH_SHORT).show();
}
}
public void submit(View v)
{
Intent i2 = new Intent(this,TwoAppsActivity.class);
startActivity(i2);
if(i2.getStringExtra("Id1")=="1")
{
i2.putExtra("spinner.intents.understand.value1", Et.getEditableText().toString());
}
else if(i2.getStringExtra("Id2")=="2")
{
i2.putExtra("spinner.intents.understand.value2", Et.getEditableText().toString());
}
else
{
Toast.makeText(getApplicationContext(), "No data to display", Toast.LENGTH_LONG).show();
}
}
}
MAIN.XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<TextView
android:id="#+id/txt1"
android:text="Enter value 1:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/edittxt1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/txt2"
android:text="Enter value 2:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/edittxt2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/txt3"
android:text="Select"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Spinner
android:id="#+id/spin1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btnsubmit1"
android:text="Submit"
android:onClick="Submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
SECOND ACTIVITY XML FILE
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/txtS1"
android:text="Value:"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/edittxtS1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/btnsubmit2"
android:text="Submit"
android:onClick="submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
ANDROID MANIFEST XML FILE
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="spinnner.intents.understand"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".TwoAppsActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Second">
</activity>
</application>
</manifest>
I am also willing to mail my project if my code appears too messed up.

You shouldn't use == nor != to compare two strings. Use equals instead:
if(spinner.getSelectedItem().toString().equals("1"))
Regards.

Related

How to send the data from the current activity to the previous activity?

I've created two activities. The first accepts the name of a student through an edit text and has a submit button. When the submit button is pressed, the next activity opens which has an edit text (to accept the marks) along with a back button.
I wish to return the marks entered to the first activity, when the back button of second activity is pressed so that the marks are displayed in the first edit text.
Kindly provide me with the code for the two activities.
You can use activity for result . An example is given here
Hello Akanksha Gahalout, if i understand your question, you want to pass Data between two activities and vice versa , if so, you should use Intent and use PutExtrat() method to pass data from one Activity to another,then you can recuperate data from the second Activity with using Bundle and getExtras() method.
Here's an example :
FirstActivity.xml :
<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:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<EditText
android:id="#+id/EditTextFirstActivity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/StudentName"
android:ellipsize="start"
android:gravity="center_horizontal"
android:labelFor="#+id/EditText1" />
<Button
android:id="#+id/buttonFirstActivity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/OK" />
<TextView
android:id="#+id/TextViewFirstActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#000000"
android:ellipsize="start"
android:gravity="center_horizontal"
android:textSize="20sp" />
</LinearLayout>
FirstActivity.java :
package dz.A;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class FirstActivity extends Activity implements OnClickListener {
private TextView textView;
private EditText editTextFirstActivity;
private Button buttonFirstActivity;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_activity);
editTextFirstActivity = (EditText) findViewById(R.id.EditTextFirstActivity);
textView = (TextView) findViewById(R.id.TextViewFirstActivity);
buttonFirstActivity = (Button) findViewById(R.id.buttonFirstActivity);
buttonFirstActivity.setOnClickListener(this);
Intent iin = getIntent();
Bundle b = iin.getExtras();
if (b != null) {
String marks = (String) b.get("STUDENT_MARKS");
textView.setText(marks);
}
}
#Override
public void onClick(View v) {
if (v == buttonFirstActivity) {
Log.i("OK", "onClickOK");
Intent i = new Intent(this, SecondActivity.class);
Log.i("OK", "IntentOK");
Log.i("OK", "startActivity(i)OK");
String studentName = editTextFirstActivity.getText().toString()
.trim();
Log.i("OK", "studentNameOK : " + studentName);
i.putExtra("STUDENT_NAME", "Student Name : " + studentName);
Log.i("OK", "i.putExtraOK");
startActivity(i);
finish();
Log.i("OK", "finish()OK");
}
}
}
SecondActivity.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/EditTextSecondActivity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="start"
android:gravity="center_horizontal"
android:hint="#string/Marks"
android:inputType="number"
android:labelFor="#+id/EditText1" />
<Button
android:id="#+id/buttonSecondActivity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/sendMarks" />
<TextView
android:id="#+id/TextViewSecondActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#000000"
android:textSize="20sp" />
</LinearLayout>
SecondActivity.java :
package dz.A;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SecondActivity extends Activity implements OnClickListener {
private TextView textViewSecondActivity;
private EditText editTextSecondActivity;
private Button buttonSecondActivity;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
textViewSecondActivity = (TextView) findViewById(R.id.TextViewSecondActivity);
editTextSecondActivity = (EditText) findViewById(R.id.EditTextSecondActivity);
buttonSecondActivity = (Button) findViewById(R.id.buttonSecondActivity);
buttonSecondActivity.setOnClickListener(this);
Intent iin = getIntent();
Bundle b = iin.getExtras();
if (b != null) {
String studentName = (String) b.get("STUDENT_NAME");
textViewSecondActivity.setText(studentName);
}
}
#Override
public void onClick(View v) {
if (v == buttonSecondActivity) {
String marks = editTextSecondActivity.getText().toString().trim();
Intent i = new Intent(this, FirstActivity.class);
i.putExtra("STUDENT_MARKS", "Student Marks : " + marks);
startActivity(i);
finish();
}
}
}
AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="dz.A"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="23" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="dz.A.FirstActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="dz.A.SecondActivity"/>
</application>
</manifest>
String.xml :
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Project</string>
<string name="hello_world">Hello world!</string>
<string name="OK">OK</string>
<string name="Marks">Marks</string>
<string name="sendMarks">sendMarks</string>
<string name="StudentName">StudentName</string>
</resources>
I hope that helps you.

Testing a transition between two activities and going back to the first activity

I am developing an app that requires the user to press a button and it goes to another activity. The problem is that I cannot continue from there. I want to be able to simulate a button press and go back to the previous activity it was on. Here is my code.
package com.example.guy.smsclassproject;
import android.os.Looper;
import android.test.ActivityInstrumentationTestCase2;
import android.test.UiThreadTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
/**
* Created by ksl130230 on 11/5/2015.
*/
public class DraftsActivityTest extends ActivityInstrumentationTestCase2<DraftsActivity> {
private DraftsActivity tester;
private EditText searchText;
private Button searchButton;
private DraftsDatabase draftsDatabase;
private MessageObject messageObject1;
private MessageObject messageObject2;
private MessageObject messageObject3;
Button[] draftButtons;
ArrayList<MessageObject> messagesToBeDisplayed;
public DraftsActivityTest() {
super(DraftsActivity.class);
}
#Override
#UiThreadTest
public void setUp() throws Exception {
super.setUp();
if (Looper.myLooper() == null)
{
Looper.prepare();
}
draftsDatabase = new DraftsDatabase();
draftsDatabase.clearData();
messageObject1 = new MessageObject("hi", "5554",null, true);
messageObject2 = new MessageObject("hi hi", "5555554",null, true);
messageObject3 = new MessageObject("sup", "5435555554",null, true);
draftsDatabase.addMessage(messageObject1);
draftsDatabase.addMessage(messageObject2);
draftsDatabase.addMessage(messageObject3);
tester = getActivity();
messagesToBeDisplayed = tester.messagesToBeDisplayed;
searchText = (EditText) tester.findViewById(R.id.searchText);
searchButton = (Button) tester.findViewById(R.id.searchButton);
}
#SmallTest
#UiThreadTest
public void testSearch() {
searchText.setText("hij");
searchButton.performClick();
messagesToBeDisplayed = tester.messagesToBeDisplayed;
assertEquals("Messages with the word hi", 0, messagesToBeDisplayed.size());
searchText.setText("sup");
searchButton.performClick();
messagesToBeDisplayed = tester.messagesToBeDisplayed;
assertEquals("Messages with the word sup", 1, messagesToBeDisplayed.size());
searchText.setText("yo");
searchButton.performClick();
messagesToBeDisplayed = tester.messagesToBeDisplayed;
assertEquals("Messages with the word yo", 0, messagesToBeDisplayed.size());
searchText.setText("i");
searchButton.performClick();
messagesToBeDisplayed = tester.messagesToBeDisplayed;
assertEquals("Messages with the word i", 2, messagesToBeDisplayed.size());
}
#SmallTest
#UiThreadTest
public void testRedisplay()
{
assertNotNull(tester.draftButtons[0]);
tester.draftButtons[0].performClick();
messagesToBeDisplayed = tester.messagesToBeDisplayed;
assertEquals("Size of the list after deletion is 2", 2, messagesToBeDisplayed.size()); //presses the first button, which deletes it from the drafts
getActivity();
String buttonText0 = tester.draftButtons[0].getText().toString();
if(buttonText0.equals("5555554: hi hi")) assertSame("Text redisplayed on the first button", buttonText0, messageObject2.toString()); //gets the text of the current button, since the messageobject1 was in draftsButtons0 before, not it should have messageobject2
assertNotNull(tester.draftButtons[1]);
String buttonText1 = tester.draftButtons[1].getText().toString();
if(buttonText1.equals("5435555554: sup"))
assertSame("Text redisplayed on the second button", buttonText1, messageObject3.toString());
}
#SmallTest
#UiThreadTest
public void testMessageButtons()
{
assertNotNull(tester.draftButtons[0]);
tester.draftButtons[0].performClick();
//THE PROBLEM IS LOCATED HERE.
//As soon as I press the button, the app goes to another activity.
//I want it to go back from the activity.
assertNotNull(tester.draftButtons[1]);
tester.draftButtons[1].performClick();
messagesToBeDisplayed = tester.messagesToBeDisplayed;
assertEquals("The draftsDatabase now only contains 1 message", 1, messagesToBeDisplayed.size());
assertNotNull(tester.draftButtons[0]);
tester.draftButtons[0].performClick();
assertNull(draftsDatabase); //after you press all the buttons, the draftsDatabase should be empty because all the messages have been deleted
}
}
This is my code of application which I recently made. If user press a button it goes to another activity from this you will be to simulate a button press and go back to the previous activity and I also have made some modification that you can pass data from text view to second activity
MainActivity
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
Intent i = new Intent(this, Main2Activity.class);
final EditText inputText = (EditText) findViewById(R.id.inputText);
String mesg = inputText.getText().toString();
i.putExtra("mm",mesg );
startActivity(i);
}
}
Main2Activity
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.transition.Transition;
import android.transition.TransitionManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class Main2Activity extends AppCompatActivity {
ViewGroup RLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Bundle data = getIntent().getExtras();
if(data == null){
return;
}
String mm = data.getString("mm");
final TextView textVieww = (TextView) findViewById(R.id.textVieww);
textVieww.setText(mm);
RLayout = (ViewGroup) findViewById(R.id.RLayout);
RLayout.setOnTouchListener(
new RelativeLayout.OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
moveButton();
return true;
}
});
}
public void onClickk(View view) {
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.user.razaali.third" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Main2Activity"
android:label="#string/title_activity_main2" >
</activity>
</application>
</manifest>
activity_main.xml
<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=".MainActivity"
android:background="#53ff00">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="First Screen"
android:id="#+id/textView"
android:layout_above="#+id/inputText"
android:layout_centerHorizontal="true"
android:layout_marginBottom="33dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="onClick" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/inputText"
android:width="250dp"
android:layout_above="#+id/button"
android:layout_centerHorizontal="true"
android:layout_marginBottom="32dp" />
</RelativeLayout>
activity_main2.xml
<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.razaali.third.Main2Activity"
android:background="#fff306"
android:id="#+id/RLayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Secound Screen"
android:id="#+id/textVieww"
android:layout_above="#+id/button2"
android:layout_centerHorizontal="true"
android:layout_marginBottom="51dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change"
android:id="#+id/button2"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="onClickk" />
</RelativeLayout>

I created an Android application with two activities, but cannot switch back from the second activity to the first

I created an Android application with two activities, but somehow the buttons on the second activity do not seem to work properly. The button on the first activity (a map activity and a button to add infromat which takes users to the second activity with an information entry screen) works fine, neither button on the second activity seems to have any effect... I can't even get an OnClick Toast message to work.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback , LocationListener {
public void AddMapInfo(View view) {
Intent intent = new Intent(this, InformationInputActivity.class);
LatLng providedLocation = current;
Bundle args = new Bundle();
args.putParcelable("provided_location", providedLocation);
intent.putExtra("bundle", args);
startActivityForResult(intent, 1);
}
public void onActivityResult (int requestCode, int resultCode, Intent data){
Toast.makeText(this, "back with cheese!", Toast.LENGTH_LONG).show();
if (requestCode != 1){
Toast.makeText(this, "Oops... This shouldn't happen", Toast.LENGTH_LONG).show();
}
else{
setContentView(R.layout.activity_maps);
InformationPoint informationPoint = (InformationPoint) data.getSerializableExtra("information_point");
informationPoint.display(mymap);
}
}
}
The second activity brings on the layout for the screen, and it sets the proper options for the EditText field, so I know it gets control... but that's about it. There is no Toast message from any of the methods (I still get the Toasts when the location update info is received on the first activity instead), and neither the radio button or submit buttons seem to work, I'm also not getting the result and control back in the first activity. (Previously, I used to be able to get a Toast on ever on checked option on the radio button, but now that doesn't seem to work either). Trying to send the activity result aborts the application (since I added finish() to the second activity).
/* java */
package com.example.m.googlemapappfirst;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.model.LatLng;
import org.w3c.dom.Text;
public class InformationInputActivity extends ActionBarActivity {
EditText editText;
String content = "";
LatLng providedLocation;
public InfoType infoType = InfoType.NO_INFO;
InformationPoint informationPoint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information_input);
Intent intent = getIntent();
Bundle bundle = getIntent().getParcelableExtra("bundle");
providedLocation = bundle.getParcelable("provided_location");
String message = String.valueOf(providedLocation);
editText = (EditText)findViewById(R.id.description);
editText.setHorizontallyScrolling(false);
editText.setMaxLines(5);
Toast.makeText(this, "enter cheese info", Toast.LENGTH_LONG);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
Toast.makeText(this,"you selected your cheese", Toast.LENGTH_LONG);
}
#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_information_input, 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);
}
public void AddPictureHandler(View view){
Toast.makeText(this, "i like to take pictures of cheese", Toast.LENGTH_LONG).show();
}
public void SubmitHandler(View view){
content = editText.getText().toString();
Toast.makeText(this, "add cheese info", Toast.LENGTH_LONG).show();
if(infoType == InfoType.NO_INFO){
Toast.makeText(this, "Please select an Information type", Toast.LENGTH_LONG).show();
}
else if(content.equals("")){
Toast.makeText(this, "Please write a description", Toast.LENGTH_LONG).show();
}
informationPoint = new InformationPoint(providedLocation, infoType, content);
Intent returnIntent = new Intent(this, MapsActivity.class);
returnIntent.putExtra("information_point", informationPoint);
this.setResult(1, returnIntent);
finish(); /* added after original post, this makes app crash consistently */
}
}
Here's the xml layout file for the second activity:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.m.googlemapappfirst.InformationInputActivity">
<TextView android:text="#string/instructions"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="#+id/radio_swiss"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/swiss"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_american"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/american"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_gruyere"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/gruyere"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_cheddar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cheddar"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
<TextView android:text="#string/instructions2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/description"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:layout_weight="1"
android:hint="#string/type_here"
android:inputType="text"
android:imeOptions="actionDone"
android:maxLines ="4"
android:maxLength ="2000"
android:scrollHorizontally="false"
/>
<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="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="horizontal">
<Button
android:id="#+id/take_picture_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Picture"
android:onClick="AddPictureHandler" />
<Button
android:id="#+id/submit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Report Information"
android:onClick="SubmitHandler" />
</LinearLayout>
I didn't see any problem but missing invocation of show() after toast creation, just like this:
Toast.makeText(this, "Oops... This shouldn't happen", Toast.LENGTH_LONG).show();

Android app keeps 'closing', but no errors being shown in logcat

This is my main class that will be forwarding the username to my GoalActivity class. I cannot figure out where the issue is. It keeps crashing for an unknown reason to me. I've followed various tutorials, and I cannot figure out the issue. It seems that I retrieve the username correctly, and then convert it into a string. Then create an Intent and pass the username value with a key.
MainActivity.java
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.agray.carpediem.LoginDataBaseAdapter;
import com.example.agray.carpediem.R;
import com.example.agray.carpediem.SignUPActivity;
public class MainActivity extends Activity
{
Button btnSignIn,btnSignUp;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//create instance of SQLite Database
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
//create reference to the buttons used
btnSignIn=(Button)findViewById(R.id.buttonSignIN);
btnSignUp=(Button)findViewById(R.id.buttonSignUP);
// Signup button w/onclick listener
btnSignUp.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity
Intent intentSignUP=new Intent(getApplicationContext(),SignUPActivity.class);
//start the activity w/intent
startActivity(intentSignUP);
}
});
}
// Methods to handleClick Event of Sign In Button
public void signIn(View View)
{
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
//get the References of views
final EditText editTextUserName=
(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=
(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);
Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);
//Signin Button w/ onClickListener
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//store username and password as strings
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
//fetch the Password from the DB for respective username
String storedPassword=loginDataBaseAdapter.getSingleEntry(userName);
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword))
{
Toast.makeText(MainActivity.this, "Congrats: Login is Successful " + userName,
Toast.LENGTH_LONG).show();
dialog.dismiss();
// final EditText editTextUserName=
// (EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
// String userName=editTextUserName.getText().toString();
//create intent that will start the goals activity w/some data
Intent intro = new Intent(getApplicationContext(), GoalActivity.class);
//put the username into intent
intro.putExtra("USER_NAME", userName);
startActivity(intro);
}
else
{
Toast.makeText(MainActivity.this, "Access Denied: User Name or Password " +
"does not match",
Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
#Override
protected void onDestroy() {
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}
}
Here is my GoalActivity class that receives info from the MainActivity class.
GoalActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class GoalActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.goals_page);
//get the username from the intent
String enteredUserName = getIntent().getStringExtra("USER_NAME");
final TextView tv = (TextView)findViewById(R.id.user_name_forwarded);
tv.setText(enteredUserName);
}
}
login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/editTextUserNameToLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="User Name"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editTextPasswordToLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword"
android:hint="Password" />
<Button
android:id="#+id/buttonSignIn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Sign In" />
</LinearLayout>
goals_page.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/welcome_goals"
android:textSize="50sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/user_name_forwarded"
android:text="#string/emptyString"
android:layout_weight="0.09"/>
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.agray.carpediem" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="CarpeD"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.agray.carpediem.MainActivity"
android:label="CarpeD" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SignUPActivity"/>
<activity android:name=".GoalActivity"/>
</application>
</manifest>
Try this, e.g. in ActivityA:
Intent i = new Intent(ActivityA.this, ActivityB.class);
i.putExtra("USER_NAME", userNameString);
startActivity(i);
In ActivityB:
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
String USERNAME = extras.getString("USER_NAME");
Solved. It was a very careless mistake. I had updated all the other activities in the Manifest but the activity tag for the GoalActivity.java. Thanks guys for all your help!

How to set dynamic string as user select in android?

I'm beginner in Android. I'm trying to make an app where when user tap on button he should go to another activity let say if user tap on button 1 he see new activity with information-A and if he press button 2 he see information-B in same activity he saw information A.
How can I set that.
If I am understanding your question correctly, here's a solution.
You can use the putExtras method of Intent to pass data in key/value pairs to the next activity.
Add the following to activity 1 layout:
<Button
android:id="#+id/btnA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button A"
android:onClick="goToActivityFromButtonA" />
<Button
android:id="#+id/btnB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/btnA"
android:text="Button B"
android:onClick="goToActivityFromButtonB" />
Add the following methods to Activity 1:
public void goToActivityFromButtonA(View view) {
Intent intent = new Intent(this, ActivityTwo.class);
intent.putExtra("buttonData", "You clicked button A");
startActivity(intent);
}
public void goToActivityFromButtonB(View view) {
Intent intent = new Intent(this, ActivityTwo.class);
intent.putExtra("buttonData", "You clicked button B");
startActivity(intent);
}
Add the following to Activity 2 layout:
<TextView
android:id="#+id/txtText"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Add the following to the onCreate method of activity 2:
TextView txtText = (TextView)findViewById(R.id.txtText);
txtText.setText(getIntent().getExtras().getString("buttonData"));
I just created a sample project for you:
https://drive.google.com/file/d/0B0S6sddMC_rMSUNieUxkR2lFRzQ/view?usp=sharing
you have first create ui for first activity like this
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".FirstActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="77dp"
android:text="Button 1" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="110dp"
android:layout_marginLeft="38dp"
android:layout_toRightOf="#+id/button1"
android:text="Button 2" />
</RelativeLayout>
ui of second activity like this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="second actvity" />
</LinearLayout>
activity first code where i set index with intent for both button click(you also put string double ling and message with intent)
package com.example.teststart;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class FirstActivity extends Activity implements OnClickListener{
Button b1,b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
b1=(Button)findViewById(R.id.button1);
b2=(Button)findViewById(R.id.button2);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id=v.getId();
switch(id){
case R.id.button1:
Intent i1=new Intent(FirstActivity.this,secondactivity.class);
i1.putExtra("one", 1);
startActivity(i1);
break;
case R.id.button2:
Intent i2=new Intent(FirstActivity.this,secondactivity.class);
i2.putExtra("one", 2);
startActivity(i2);
break;
}
}
}
and second activity i get that integer value to identify which button is clicked and fire operation on that condition
package com.example.teststart;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class secondactivity extends Activity{
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactvity);
tv=(TextView)findViewById(R.id.textView1);
Bundle extras = getIntent().getExtras();
int index = extras.getInt("one");
if(index==1){
tv.setText("nformation-A "+index);
}else if(index==2){
tv.setText("nformation-B "+index);
}
}
}

Categories

Resources