I am trying to make a basic contact form app where people can fill in the needed information and press the send button and have the information sent to a specific E-mail. I have put it together but for some reason it is not working. The Java file has code in it from a similar app. The Java file has spinner code in it so I turned it into notes.. not sure if it's messing something up. Here is the code please let me know what I can do to make it work.
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: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=".MainActivity" >
<EditText
android:id="#+id/etName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:ems="10"
android:hint="Enter First and Last Name"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/etPhone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/etName"
android:layout_marginTop="14dp"
android:ems="10"
android:hint="Enter Phone #"
android:inputType="phone" />
<EditText
android:id="#+id/etEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/etPhone"
android:layout_marginTop="17dp"
android:ems="10"
android:hint="Enter E-mail"
android:inputType="textEmailAddress" />
<EditText
android:id="#+id/etAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/etEmail"
android:layout_marginTop="18dp"
android:ems="10"
android:hint="Enter Additional Information Here"
android:lines="3"
android:inputType="textMultiLine" />
<Button
android:id="#+id/send"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="#+id/etAdd"
android:text="Send" />
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/etPhone"
android:layout_alignParentTop="true"
android:gravity="center"
android:text="Contact Form"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
Here is the MainActivity.java file:
package com.example.contactform1;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener, OnItemSelectedListener{
/** Called when the activity is first created. */
EditText etname, etphone, etemail, etadd;
//Spinner subject;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etname = (EditText) findViewById (R.id.etName);
etphone = (EditText) findViewById(R.id.etPhone);
etemail = (EditText) findViewById(R.id.etEmail);
etadd = (EditText)findViewById(R.id.etAdd);
//subject=(Spinner)findViewById(R.id.spinner);
//String subjects[]=new String[]{"Default","Klacht","Vraag","Opmerking","Applicatie"};
//subject.setOnItemSelectedListener(this);
//ArrayAdapter<String> sa = new ArrayAdapter<String>(getApplicationContext(),
//android.R.layout.simple_spinner_item, subjects);
//sa.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
//subject.setAdapter(sa);;
final Button buttonSend= (Button)findViewById(R.id.send);
buttonSend.setOnClickListener(this);
}
public void onClick(View v)
{
//if(etname.getText().toString().length()==0)
//{
//etname.setError( "Vul uw naam in" );
//}
//else if(etphone.getText().toString().length()==0)
//{
//etphone.setError( "Vul uw email in" );
//}
//else if(etemail.getText().toString().length() != 10)
//{
//etemail.setError( "Vul een geldig telefoonnummer in" );
//}
//else if(etadd.getText().toString().length()==0)
//{
//etadd.setError( "Vul uw bericht in" );
//}
//else if(subject.getSelectedItemPosition()==0)
//{
//Toast.makeText(MainActivity.this,"Please select the Subject",Toast.LENGTH_SHORT).show();
//}
//else
//{
//String body=
//"Name : "+etname.getText().toString()+"<br>Mobile :"+etphone.getText().toString()+
//"<br>Email :"+etemail.getText().toString();//+"<br>Bericht :"+etadd.getText().toString();
//Intent email = new Intent(Intent.ACTION_SEND);
//email.putExtra(Intent.EXTRA_EMAIL, new String[]{"email here"});
//email.putExtra(Intent.EXTRA_SUBJECT, subject.getSelectedItem().toString());
//email.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(body));
//email.setType("message/rfc822");
//startActivityForResult(Intent.createChooser(email, "marketing"),1);
}
// }
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
new AlertDialog.Builder(MainActivity.this)
.setMessage("Your requested has been Accepted\nThank You")
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
})
.show();
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
LogCat info:
12-04 18:19:15.574: W/IInputConnectionWrapper(28530): showStatusIcon on inactive InputConnection
12-04 18:19:21.190: D/AbsListView(28530): Get MotionRecognitionManager
12-04 18:19:21.220: D/AbsListView(28530): onVisibilityChanged() is called, visibility : 4
12-04 18:19:21.220: D/AbsListView(28530): unregisterIRListener() is called
12-04 18:19:21.230: D/AbsListView(28530): onVisibilityChanged() is called, visibility : 0
12-04 18:19:21.230: D/AbsListView(28530): unregisterIRListener() is called
12-04 18:19:21.240: D/AbsListView(28530): unregisterIRListener() is called
12-04 18:19:21.320: D/AbsListView(28530): unregisterIRListener() is called
12-04 18:19:21.330: D/AbsListView(28530): unregisterIRListener() is called
12-04 18:19:21.360: D/AbsListView(28530): unregisterIRListener() is called
12-04 18:19:21.390: D/AbsListView(28530): unregisterIRListener() is called
12-04 18:19:22.591: D/AbsListView(28530): unregisterIRListener() is called
12-04 18:19:22.861: W/IInputConnectionWrapper(28530): showStatusIcon on inactive InputConnection
12-04 18:19:22.982: D/AbsListView(28530): onDetachedFromWindow
12-04 18:19:22.982: D/AbsListView(28530): unregisterIRListener() is called
12-04 18:19:37.546: E/ViewRootImpl(28530): sendUserActionEvent() mView == null
12-04 18:19:40.499: W/IInputConnectionWrapper(28530): showStatusIcon on inactive InputConnection
12-04 18:19:40.519: E/OpenGLRenderer(28530): SFEffectCache:clear(), mSize = 0
I have the form appearing now but the information that you input is not getting sent to the email. I am getting prompted to a screen indication which email service i should use to execute this app. I just want the information entered to be directly sent to the email that is provided in the app.
Thanks in advance!
You're seeing that screen with the list of email clients because that's how Intents work.
An intent won't directly execute the action you want it to, all it can do is hand off the data to another Activity (perhaps in a different application) that can handle the data.
Related
I was creating an app then a question come out:
how can i keep user in activity?
I've put two editTexts with input of int.
i want user be kept in activity until he/she puts valid numbers in edittexts.
any ideas?
The solution is very simple all you need to do is get the string values from the edit text box and have a condition in your setonclicklistener that checks the strings if they match to a certain value, if yes the intent from current activity will take you to next if not it will show an error on the edit text box (by using .setError()) and return.
Here is the Java Class Code:
package com.example.text_to_speech;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
public class ActivityA extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity);
EditText editText1,editText2;
Button button;
editText1=findViewById(R.id.ed1);
editText2=findViewById(R.id.ed2);
button=findViewById(R.id.check_input);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!editText1.getText().toString().equals("Don"))
{
Toast.makeText(ActivityA.this, "You Can't Leave this Activity, Input Correct Fields", Toast.LENGTH_SHORT).show();
editText1.setError("Input Correct values");
return;
}
if(!editText1.getText().toString().equals("Tom"))
{
Toast.makeText(ActivityA.this, "You Can't Leave this Activity, Input Correct Fields", Toast.LENGTH_SHORT).show();
editText2.setError("Input Correct values");
return;
}
Intent intent=new Intent(ActivityA.this,MainActivity.class);
startActivity(intent);
}
});
}
}
XML Code:
<RelativeLayout
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"
tools:context=".ActivityA">
<EditText
android:layout_margin="10dp"
android:id="#+id/ed1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Input Data Here"
android:textColor="#000000"
android:textSize="20sp" />
<EditText
android:layout_margin="10dp"
android:layout_below="#id/ed1"
android:id="#+id/ed2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Input Data Here"
android:textColor="#000000"
android:textSize="20sp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ed2"
android:id="#+id/check_input"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="20dp"
android:text="Go to Next Activity"
/>
</RelativeLayout>
Output:
I am trying to make an app to list the schools in my area and I made a table in a database to contain these schools. I made a list view with clickable items to list the names of the schools and when I click on the item to move to another activity and send the clicked school name in order to list more information about the school, the app stops working. The following is one of the activities that contains this list view:
package com.example.welcome.madrasti;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class ListOfSchoolsPublic extends AppCompatActivity {
Intent redirect;
Intent item;
ListView list;
ArrayList<String> _sa;
DBAdapter db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_schools_public);
openDB();
list= (ListView) findViewById(R.id.usersList);
redirect = getIntent();
Cursor cursor = db.getAllRows();
_sa= new ArrayList<String>();
//cursor.moveToFirst();
Log.d("CURSORCOUNT","Number of rows in the Cursor is = " + String.valueOf(cursor.getCount()));
while(cursor.moveToNext()) {
if(cursor.getString(DBAdapter.COL_SChOOL_TYPE_TABLE_2).equals("حكومية"))
_sa.add(cursor.getString(DBAdapter.COL_SCHOOLNAME_TABLE_2));
}
cursor.close();
#SuppressWarnings("rawtypes")
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,_sa);
list.setAdapter(new TempLyaout(ListOfSchoolsPublic.this,_sa));
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
String selectedItem = (String) arg0.getItemAtPosition(position);
itemInfo(selectedItem);
}
});
}
///////////////////////////////////////////////////////////////
public void itemInfo(String selectedItem){
item = new Intent(getApplicationContext(), NewSchool.class);
item.putExtra("schoolName",selectedItem);
startActivity(item);
}
///////////////////////////////////////////////////////////////
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}// end onDestroy method
///////////////////////////////////////////////////////////////
private void openDB() {
db = new DBAdapter(ListOfSchoolsPublic.this);
db.open();
} // end openDB method
//////////////////////////////////////////////////////////////
private void closeDB() {
db.close();
} // end closeDB method
}
The following is the activity that each list item should move to:
package com.example.welcome.madrasti;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class NewSchool extends AppCompatActivity {
Intent intent;
Intent nextPage;
Button next;
DBAdapter db;
TextView t1;
TextView t2;
TextView t3;
TextView t4;
TextView t5;
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_school);
t1=(TextView)findViewById(R.id.textView9) ;
t2=(TextView)findViewById(R.id.textView11) ;
t3=(TextView)findViewById(R.id.textView12) ;
t4=(TextView)findViewById(R.id.textView17) ;
t5=(TextView)findViewById(R.id.textView18) ;
next = (Button) findViewById(R.id.button);
intent = getIntent();
name = intent.getStringExtra("schoolName");
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
goNext();
}
});
Cursor cursor = db.getAllRows();
while(cursor.moveToNext()) {
if(cursor.getString(DBAdapter.COL_SCHOOLNAME_TABLE_2).equals(name)){
t1.setText(DBAdapter.COL_SCHOOLNAME_TABLE_2);
t2.setText(DBAdapter.COL_FOUNDATION_DATE_TABLE_2);
t3.setText(DBAdapter.COL_BUY_BOOKS_TABLE_2);
t4.setText(DBAdapter.COL_HEALTH_TABLE_2);
t5.setText(DBAdapter.COL_LOCATION_TABLE_2);
}
}
cursor.close();
}
public void goNext(){
nextPage = new Intent(getApplicationContext(),NewShoolAct2.class);
nextPage.putExtra("schoolName",name);
startActivity(nextPage);
}
///////////////////////////////////////////////////////////////
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}// end onDestroy method
///////////////////////////////////////////////////////////////
private void openDB() {
db = new DBAdapter(NewSchool.this);
db.open();
} // end openDB method
//////////////////////////////////////////////////////////////
private void closeDB() {
db.close();
} // end closeDB method
}
The following is the XML of the previous activity:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/login_background"
tools:context="com.example.welcome.madrasti.NewSchool">
<AbsoluteLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="0dp">
<TextView
android:id="#+id/textView"
android:layout_width="80dp"
android:layout_height="30dp"
android:layout_x="244dp"
android:layout_y="54dp"
android:text="إسم المدرسة:"
android:textAlignment="center"
android:textStyle="bold"
tools:layout_editor_absoluteX="dp"
tools:layout_editor_absoluteY="10dp" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="240dp"
android:layout_y="127dp"
android:text="تاريخ التأسيس:"
android:textAlignment="center"
android:textStyle="bold"
tools:layout_editor_absoluteX="297dp"
tools:layout_editor_absoluteY="144dp" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="231dp"
android:layout_y="185dp"
android:text="كيفية شراء الكتب:"
android:textAlignment="center"
android:textStyle="bold"
tools:layout_editor_absoluteX="284dp"
tools:layout_editor_absoluteY="210dp" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="215dp"
android:layout_y="265dp"
android:text="وضع المرافق الصحية:"
android:textAlignment="center"
android:textStyle="bold"
tools:layout_editor_absoluteX="265dp"
tools:layout_editor_absoluteY="288dp" />
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="244dp"
android:layout_y="340dp"
android:text="موقع المدرسة:"
android:textAlignment="center"
android:textStyle="bold"
tools:layout_editor_absoluteX="300dp"
tools:layout_editor_absoluteY="368dp" />
<Button
android:id="#+id/button"
android:layout_width="98dp"
android:layout_height="34dp"
android:layout_x="133dp"
android:layout_y="434dp"
android:background="#drawable/button"
android:text="التالي"
android:textAlignment="center"
android:textColor="#ffff"
android:textStyle="bold"
tools:layout_editor_absoluteX="45dp"
tools:layout_editor_absoluteY="426dp" />
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="11dp"
android:layout_y="77dp"
android:text="TextView"
tools:layout_editor_absoluteX="18dp"
tools:layout_editor_absoluteY="59dp" />
<TextView
android:id="#+id/textView11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="12dp"
android:layout_y="148dp"
android:text="TextView"
tools:layout_editor_absoluteX="12dp"
tools:layout_editor_absoluteY="150dp" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="32345dp"
android:layout_y="32418dp"
android:text="TextView"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="235dp" />
<TextView
android:id="#+id/textView17"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="15dp"
android:layout_y="299dp"
android:text="TextView"
tools:layout_editor_absoluteX="21dp"
tools:layout_editor_absoluteY="37dp" />
<TextView
android:id="#+id/textView18"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="16dp"
android:layout_y="372dp"
android:text="TextView"
tools:layout_editor_absoluteX="17dp"
tools:layout_editor_absoluteY="381dp" />
<TextView
android:id="#+id/textView20"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="16dp"
android:layout_y="219dp"
android:text="TextView"
tools:layout_editor_absoluteX="10dp"
tools:layout_editor_absoluteY="215dp" />
</AbsoluteLayout>
</android.support.constraint.ConstraintLayout>
The following is the log cat when the app is crashed:
04-13 17:57:49.245 5828-5828/? E/libprocessgroup: failed to make and chown /acct/uid_10059: Read-only file system
04-13 17:57:49.245 5828-5828/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
04-13 17:57:49.245 5828-5828/? I/art: Late-enabling -Xcheck:jni
04-13 17:57:49.435 5828-5838/? I/art: Debugger is no longer active
04-13 17:57:49.492 5828-5828/? I/InstantRun: starting instant run server: is main process
04-13 17:57:49.602 5828-5843/? W/art: Suspending all threads took: 11.737ms
04-13 17:57:49.605 5828-5843/? I/art: Background sticky concurrent mark sweep GC freed 2038(168KB) AllocSpace objects, 0(0B) LOS objects, 25% free, 832KB/1117KB, paused 13.068ms total 21.305ms
04-13 17:57:49.630 5828-5828/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
04-13 17:57:49.779 5828-5847/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
04-13 17:57:49.784 5828-5828/? D/Atlas: Validating map...
04-13 17:57:49.810 5828-5847/? D/libEGL: loaded /system/lib/egl/libEGL_emulation.so
loaded /system/lib/egl/libGLESv1_CM_emulation.so
04-13 17:57:49.820 5828-5847/? D/libEGL: loaded /system/lib/egl/libGLESv2_emulation.so
04-13 17:57:49.848 5828-5847/? I/OpenGLRenderer: Initialized EGL, version 1.4
04-13 17:57:49.878 5828-5847/? D/OpenGLRenderer: Enabling debug mode 0
04-13 17:57:49.896 5828-5847/? W/EGL_emulation: eglSurfaceAttrib not implemented
04-13 17:57:49.896 5828-5847/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xe2c15340, error=EGL_SUCCESS
What is the problem please? how to fix it?
Use intents and read basic android first. There are number of options already available for this.
You can Store your string into some other class like this:
Store string:
String selectedItem = (String) arg0.getItemAtPosition(position);
Share.love=selectedItem ;
Get string:
in Your next Activity
Textview textview=(Textview)findviewbyid(R.id.yourname);
textview.setText(Share.love);
Make class
public class Share {
public static String love = "";
}
Try the following example (It uses putExtra() to pass a string to another activity):
Demo15.class:------------
public class Demo15 extends AppCompatActivity {
private Button b;
private EditText edt;
private final String EXTRA_TEXT_ = "extra_text_";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo17);
edt = (EditText) findViewById(R.id.edt);
b = (Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Demo15.this, Demo16.class);
if (!edt.getText().toString().isEmpty()) {
i.putExtra(EXTRA_TEXT_, edt.getText().toString());
}
startActivity(i);
}
});
}
}
Demo16.class:-------
public class Demo16 extends AppCompatActivity {
private TextView tv;
private final String EXTRA_TEXT_ = "extra_text_";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo18);
tv = (TextView) findViewById(R.id.tv);
if (getIntent() != null) {
if (getIntent().getStringExtra(EXTRA_TEXT_) != null) {
tv.setText(getIntent().getStringExtra(EXTRA_TEXT_));
}
}
}
}
demo17.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:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter text to pass"
android:id="#+id/edt"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start the other activity"
android:textAllCaps="false"
android:layout_marginTop="50dp"
android:id="#+id/b"/>
</LinearLayout>
demo18.xml:---------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="####"
android:id="#+id/tv"/>
</android.support.constraint.ConstraintLayout>
Use bundle with intents as android standards.
Example:
Intent intent=new Intent(CurrentActivity.this,NewActivity.class);
intent.putExtra("schoolname","Name of school");
startActivity
I am in the process of learning Android development and was trying to crash my application at runtime. I made a button that calls a method when clicked and then made sure that the method does not exist.
The application starts up fine. As soon as i click the button, the application closes just as intended. The only unexpected thing was that my device did not show any error message like application has closed unexpectedly or that the application force closed.
Did I accidentally turn off some setting in the Developer Options or is it just my device that doesn't like showing error messages ? Any more information needed ?
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:id="#+id/activity_main"
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:orientation="vertical"
tools:context="com.example.android.justjava.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Quantity"
android:textAllCaps="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/quantity_text_view"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:textColor="#000000"
android:text="0"
android:textSize="16sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Price"
android:textAllCaps="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/price_text_view"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:textColor="#000000"
android:text="$0"
android:textSize="16sp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="true"
android:text="ORDER"
android:onClick="submitOrder"/>
</LinearLayout>
MainActivity.java:
package com.example.android.justjava;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import java.text.NumberFormat;
/**
* This app displays an order form to order coffee.
*/
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrders(View view) {
int quantity = 5 ;
display(quantity) ;
displayPrice(quantity * 50) ;
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int number) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + number);
}
private void displayPrice(int number) {
TextView priceTextView = (TextView) findViewById(R.id.price_text_view);
priceTextView.setText(NumberFormat.getCurrencyInstance().format(number));
}
}
Logcat:
01-20 16:08:54.087 28870-28893/? I/OpenGLRenderer: Initialized EGL,
version 1.4 01-20 16:08:54.087 28870-28893/? D/OpenGLRenderer: Swap
behavior 1 01-20 16:08:58.044 28870-28870/com.example.android.justjava
V/BoostFramework: BoostFramework() : mPerf =
com.qualcomm.qti.Performance#b82000f 01-20 16:08:58.119
28870-28870/com.example.android.justjava D/AndroidRuntime: Shutting
down VM 01-20 16:08:58.120 28870-28870/com.example.android.justjava
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.justjava, PID: 28870
java.lang.IllegalStateException: Could not find method
submitOrder(View) in a parent or ancestor Context for android:onClick
attribute defined on view class
android.support.v7.widget.AppCompatButton
at
android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
at
android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5642)
at android.view.View$PerformClick.run(View.java:22338)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6209)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 01-20
16:08:58.120 28870-28870/com.example.android.justjava D/AppTracker:
App Event: crash 01-20 16:08:58.132 28870-28870/? I/Process: Sending
signal. PID: 28870 SIG: 9
It's based on this Udacity course.
In your XML button, its submitOrder not submitOrders. See the extra S :
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="true"
android:text="ORDER"
android:onClick="submitOrder"/>
So, change this:
public void submitOrders(View view) {
With this:
public void submitOrder(View view) {
Remove s from method name submitOrders
public void submitOrder(View view) {
int quantity = 5 ;
display(quantity) ;
displayPrice(quantity * 50) ;
}
Or You can remove android:onClick="submitOrder"
<Button
android:id="#+id/order"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="true"
android:text="ORDER"/>
than in your java file
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button order = (Button)findViewById(R.id.order);
order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int quantity = 5 ;
display(quantity) ;
displayPrice(quantity * 50) ;
}
});
}
I'm a little newbie on android, and my button it's not working properly when i run my app.
Here is my java code:
package com.example.neak.phore;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
import cz.msebera.android.httpclient.Header;
public class MainActivity extends ActionBarActivity {
Button btLoginL;
EditText etEmail, etPassL;
TextView tvRegistrarGo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btLoginL = (Button) findViewById(R.id.btLoginL);
etEmail = (EditText) findViewById(R.id.etEmailL);
etPassL = (EditText) findViewById(R.id.etPassL);
tvRegistrarGo = (TextView) findViewById(R.id.tvRegistrarGo);
final String email = etEmail.getText().toString();
final String pass = etPassL.getText().toString();
btLoginL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EnviarDatos(email, pass);
}
});
tvRegistrarGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registrar = new Intent(MainActivity.this, Registrar.class);
startActivity(registrar);
}
});
}
public void EnviarDatos(String email, String pass){
String URL = "192.168.2.15/android/login.php";
RequestParams params = new RequestParams();
params.put("email",email);
params.put("pass", pass);
AsyncHttpClient clienteL = new AsyncHttpClient();
clienteL.put(URL, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int i, Header[] headers, byte[] bytes) {
getDataJson(new String(bytes));
}
#Override
public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
Toast.makeText(getApplicationContext(), "Fallo en la conexion", Toast.LENGTH_SHORT);
}
});
}
public ArrayList<String> getDataJson(String response){
ArrayList<String> Logstat = new ArrayList<>();
try{
JSONArray recoger = new JSONArray(response);
String status;
status=recoger.getJSONObject(0).getString("estado");
comprobar(status);
} catch (Exception e) {
e.printStackTrace();
}
return Logstat;
}
public void comprobar(String status){
if(status.equals("0")){
Toast.makeText(getApplicationContext(),"Usuario o contraseña incorrectos",Toast.LENGTH_SHORT);
}else{
Toast.makeText(getApplicationContext(),"Login correcto",Toast.LENGTH_SHORT);
}
}
}
And here is my xml code:
<?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: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="#25ae90"
tools:context="com.example.neak.phore.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:hint="Nombre de usuario"
android:id="#+id/etEmailL"
android:layout_marginTop="116dp"
android:background="#ffffff"
android:padding="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="12dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:hint="Contraseña"
android:id="#+id/etPassL"
android:layout_below="#+id/etEmailL"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:padding="10dp"
android:background="#ffffff"
android:layout_marginBottom="10dp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Entrar"
android:id="#+id/btLoginL"
android:background="#ffffff"
android:layout_below="#+id/etPassL"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="33dp"
android:textColor="#25ae90" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Aun no eres miembro? Registrate!"
android:id="#+id/tvRegistrarGo"
android:layout_below="#+id/btLoginL"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp"
android:textStyle="bold"
android:textSize="15dp"
android:textColor="#ffffff" />
</RelativeLayout>
The problem is when i run the app, the button does nothing, but if i change the button Onclick for
tvRegistrarGo.setText("Prueba");
the button works! I'm working with:
this sdk version and this build tools version
This is the logcat i get when i pressed one hundred times the button, but if i press once the edit text with the onclick it appears on the logcat:
01-26 23:21:51.309 6706-6706/? I/art: Late-enabling -Xcheck:jni
01-26 23:21:51.476 6706-6742/com.example.neak.phore D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
01-26 23:21:51.482 6706-6706/com.example.neak.phore D/Atlas: Validating map...
01-26 23:21:51.528 6706-6742/com.example.neak.phore I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.01.00.042.030_msm8974_LA.BF.1.1.1_RB1__release_AU ()
OpenGL ES Shader Compiler Version: E031.25.03.06
Build Date: 05/17/15 Sun
Local Branch: mybranch10089422
Remote Branch: quic/LA.BF.1.1.1_rb1.22
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.01.00.042.030 + 6151be1 + NOTHING
01-26 23:21:51.529 6706-6742/com.example.neak.phore I/OpenGLRenderer: Initialized EGL, version 1.4
01-26 23:21:51.555 6706-6742/com.example.neak.phore D/OpenGLRenderer: Enabling debug mode 0
01-26 23:21:51.627 6706-6706/com.example.neak.phore I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#1dfc7494 time:17054805
01-26 23:22:48.574 6706-6706/com.example.neak.phore I/Timeline: Timeline: Activity_launch_request id:com.example.neak.phore time:17111752
01-26 23:22:48.715 6706-6706/com.example.neak.phore I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#815ccf4 time:17111893
01-26 23:22:52.005 6706-6706/com.example.neak.phore I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#1dfc7494 time:17115184
The problem is that you are reading the values of your EditTexts before the user has a chance to enter them.
Change this:
final String email = etEmail.getText().toString();
final String pass = etPassL.getText().toString();
btLoginL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EnviarDatos(email, pass);
}
to this
btLoginL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EnviarDatos(
etEmail.getText().toString(),
etPassL.getText().toString() );
}
I am trying to get EditText value through below code. The activity is used for adding two strings. In the layout, I already put onSave and onCancel method. But when I press button linked to onSave, it shows null pointer exception error.
Activity:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class AddTimeActivity extends Activity {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.time_item);
}
public void onCancel(View view){
this.setResult(RESULT_CANCELED);
finish();
}
public void onSave(View view){
Intent intent = getIntent();
EditText timeView = (EditText)view.findViewById(R.id.time_view);
String time = timeView.getText().toString();
intent.putExtra(TimeTrackerActivity.TIME_KEY, time);
EditText notesView = (EditText)view.findViewById(R.id.notes_view);
String notes = notesView.getText().toString();
intent.putExtra(TimeTrackerActivity.NOTES_KEY, notes);
this.setResult(RESULT_OK, intent);
finish();
}
}
Layout:
...
<EditText
android:id="#+id/timeView"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</EditText>
<EditText
android:id="#+id/notes_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:gravity="top"
android:layout_weight="1"
android:layout_marginBottom="10dp"/>
...
<Button
android:onClick="onSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save" />
<Button
android:onClick="onCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel" />
...
Error Message from Debugger
E/AndroidRuntime(1123): Caused by: java.lang.NullPointerException
E/AndroidRuntime(1123): at com.timetracker.AddTimeActivity.onSave(AddTimeActivity.java:34)
I tried to check and the value of timeView through debugger and it is null.
Could anybody help?
You are looking for the id time_view (findViewById(R.id.time_view)), but you declare in the XML the ID timeView (android:id="#+id/timeView"). Make them the same and it should fix it.
Also, you should not call it on the view, but on the activity, e.g:
EditText timeView = (EditText)findViewById(R.id.time_view);
Your xml has
android:id="#+id/timeView"
But your code has
EditText timeView = (EditText)view.findViewById(R.id.time_view);
Change above line to.
EditText timeView = (EditText)view.findViewById(R.id.timeView);