I'm new to android coding. I simply want to display data row by row from my database table.
Here is the part where I have created database/table and added data.
SQLiteDatabase glucoDB = openOrCreateDatabase("glucoDB",MODE_PRIVATE,null);
glucoDB.execSQL("CREATE TABLE IF NOT EXISTS Results(Timestamp VARCHAR, Level_using_hsv_range VARCHAR,Level_using_hsv_gradient VARCHAR,Level_using_lab_range VARCHAR,Level_using_lab_gradient VARCHAR);");
String query=new String("INSERT INTO Results VALUES ('" + currentDateTimeString + "', '" + str + "mg/dL', '" + glucose[1] + "mg/dL', '" + gvalue + "-" + largeg + "mg/dL', '" + LabRes2 + "mg/dL');");
glucoDB.execSQL(query);
Below is the activity code (ViewResults.java) for displaying database values.I can't figure out what I'm doing wrong. On exporting and running the app, the rest of the app works fine but the part where data is displayed shows a black screen and app exits instantly. Although if I display data using simple TextView and not TableLayout, it is displayed normally. So database part is working fine, there's something wrong with my TableLayout code.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_page);
int i=0,j=0;
SQLiteDatabase Glucodb = openOrCreateDatabase("glucoDB",MODE_PRIVATE,null);
Cursor resultSet = Glucodb.rawQuery("Select * from Results",null);
resultSet.moveToFirst();
TableLayout l1 = (TableLayout) findViewById(R.id.table2);
l1.setStretchAllColumns(true);
l1.bringToFront();
do
{ TableRow tr = new TableRow(getBaseContext());
TextView t1 = new TextView(getBaseContext());
TextView t2 = new TextView(getBaseContext());
TextView t3 = new TextView(getBaseContext());
TextView t4 = new TextView(getBaseContext());
TextView t5 = new TextView(getBaseContext());
t1.setBackgroundResource(R.drawable.border);
t1.setText(resultSet.getString(0));
t2.setText(resultSet.getString(1));
t3.setText(resultSet.getString(2));
t4.setText(resultSet.getString(3));
t5.setText(resultSet.getString(5));
tr.addView(t1);
tr.addView(t2);
tr.addView(t3);
tr.addView(t4);
tr.addView(t5);
l1.addView(tr);
}while(resultSet.moveToNext());
}
Below is the code of XML file associate with displaying results in table format.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TableLayout
android:id="#+id/table2"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_marginBottom="0dp"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:layout_weight="0.80"
android:stretchColumns="*" >
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:gravity="left"
android:text="Timestamp"
android:background="#drawable/border"
android:textStyle="bold" />
<TextView
android:gravity="center"
android:text="Gvalue1"
android:background="#drawable/border"
android:textStyle="bold" />
<TextView
android:gravity="center"
android:text="Gvalue2"
android:background="#drawable/border"
android:textStyle="bold" />
<TextView
android:gravity="center"
android:text="Gvalue3"
android:background="#drawable/border"
android:textStyle="bold" />
<TextView
android:gravity="center"
android:text="Gvalue4"
android:background="#drawable/border"
android:textStyle="bold" />
</TableRow>
</TableLayout>
</LinearLayout>
Related
I have created a database and want to register new user in case of absence of that user in database. So, firstly, app checks whether desired username and email exitsts in database or not. If not, it puts new user data into database. I have written code but it goes down when I try to register new user.
Here is my
MainActivity.java
public class MainActivity extends AppCompatActivity {
DBHelper dbHelper;
EditText email, username, password, passwordconf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
getSupportActionBar().hide();
dbHelper = new DBHelper(this);
}
public void clickButton2(View view) throws Exception {
SQLiteDatabase database = dbHelper.getWritableDatabase();
email = (EditText) findViewById(R.id.email);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
String userName = username.getText().toString();
String userEmail = email.getText().toString();
if (!ValidateUser(userName, userEmail)) {
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.KEY_LOGIN,
username.getText().toString());
contentValues.put(DBHelper.KEY_EMAIL,
email.getText().toString());
contentValues.put(DBHelper.KEY_PASSWORD,
password.getText().toString());
database.insert(DBHelper.TABLE_NAME, null, contentValues);
Toast.makeText(this, "you have registered successfully!",
Toast.LENGTH_SHORT).show();
Intent intent2 = new Intent(Main2Activity.this,
Main3Activity.class);
startActivity(intent2);
}
}
public boolean ValidateUser(String userName, String userEmail) {
SQLiteDatabase database = dbHelper.getWritableDatabase();
Cursor cursor = database.query(DBHelper.TABLE_NAME, null,
DBHelper.KEY_LOGIN + "=? OR " + DBHelper.KEY_EMAIL + "=?",
new String[]{userName, userEmail},
null, null, null);
int i = cursor.getCount();
database.close();
cursor.close();
if(i>0){
return true;
}else{
return false;
}
}
}
My Database Helper DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "Login_register";
public static final String TABLE_NAME = "users";
public static final String KEY_LOGIN = "login";
public static final String KEY_PASSWORD = "passsword";
public static final String KEY_EMAIL = "email";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + KEY_LOGIN + " TEXT," +
KEY_PASSWORD + " TEXT" + KEY_EMAIL + " TEXT"+")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
My layout XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="com.example.rauf.myapplication.Main2Activity"
android:background="#drawable/bii3">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:layout_editor_absoluteY="8dp"
tools:layout_editor_absoluteX="8dp"
android:paddingLeft="60dp"
android:paddingRight="58dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="600dp"
android:layout_weight="2"
android:gravity="center"
android:orientation="vertical"
android:paddingTop="42dp">
<ImageView
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_gravity="center"
android:src="#drawable/kamera" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:layout_weight="1"
android:paddingTop="35dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_gravity="center"
android:src="#drawable/message" />
<EditText
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:background="#00000000"
android:hint="email address"
android:layout_marginLeft="15dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#4a5a71">
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
<ImageView
android:id="#+id/log"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_gravity="center"
android:src="#drawable/usrusr"/>
<EditText
android:id="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:background="#00000000"
android:hint="username"
android:layout_marginLeft="15dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#4a5a71"></LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
<ImageView
android:id="#+id/red"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_gravity="center"
android:src="#drawable/pswrd"/>
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:background="#00000000"
android:hint="password"
android:layout_marginLeft="15dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#4a5a71"></LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
<ImageView
android:id="#+id/red2"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_gravity="center"
android:src="#drawable/pswrd"/>
<EditText
android:id="#+id/passwordconf"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:background="#00000000"
android:hint="password confirm"
android:layout_marginLeft="15dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#4a5a71">
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/button_background2"
android:text="SIGN UP"
android:onClick="clickButton2"
android:clickable="true"
android:layout_marginBottom="20dp"
android:textColor="#ffffff"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center"
android:onClick="clickFunction2"
android:layout_marginBottom="10dp"
android:text="Already have an Account ?"
android:textColor="#000000" />
</LinearLayout>
</LinearLayout>
Issue 1
You have omitted the comma that separates the KEY_PASSWORD and KEY_EMAIL columns in the CREATE TABLE sql.
Thus you are effectively saying CREATE TABLE users(login TEXT,passsword TEXTemail TEXT)
That is the table is created with a Column named login, with a type of TEXT and a column named password with a type of Textemail TEXT and importantly there is no column named email.
Thus any reference to column email will then result in that column not being found in the table.
To fix this issue :-
db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + KEY_LOGIN + " TEXT," +
KEY_PASSWORD + " TEXT" + KEY_EMAIL + " TEXT"+")");
should be :-
db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + KEY_LOGIN + " TEXT," +
KEY_PASSWORD + " TEXT," + KEY_EMAIL + " TEXT"+")");
Note! You should do one of the following before rerunning the App after making the above change:-
Delete the App's Data (via settings).
Uninstall the App (via settings).
Increase the Database Version number (i.e. change public static final int DATABASE_VERSION = 1; to public static final int DATABASE_VERSION = 2;)
Issue 2
In the clickButton2 method you get a writeable SQLIteDatabase instance via SQLiteDatabase database = dbHelper.getWritableDatabase();
You then invoke the ValidateUser and then subsequently try to insert a row using the same SQLiteDatabase instance.
However as the ValidateUser method closes the database, you will get an exception java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase:
You can easily fix this by one of the following :-
removing the database.close() line from the ValidateUser method
create/open another instance of the SQLiteDatabase before the insert e.g add a line before the insert such as database = dbHelper.getWritableDatabase();
Issue 3
If a user already exists and is thus validated they will remain in the MainActivity.
You will need to decide/determine the logic to be used to fix this issue.
I have this layout which presents my View correctly, I tried to match it with Java side to have the capability to build rows dynamically, but I kept failing into achieving that,
<TableLayout>
android:layout_width="match_parent"
android:layout_height="wrap_content"
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="200dp"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextViewaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaws" />
</LinearLayout>
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</TableRow>
</TableLayout>
I do want to make it in code, I have tried many times and this is my best attempt
public static void makeTablePostOrders(Context ct, TableLayout tableLayout_PostOrders,
List<String> postOrders)
{
TableRow.LayoutParams tableRowParams = new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(200,
LinearLayout.LayoutParams.MATCH_PARENT,1);
//randoms
for(int i = 0; i < postOrders.size()/2 ; i++)
{
//make tableRow
TableRow tableRow = new TableRow(ct);
// make LinearLayout
LinearLayout layout = new LinearLayout(ct);
layout.setLayoutParams(linearLayoutParams);
layout.setOrientation(LinearLayout.VERTICAL);
//make TextView
TextView tv = new TextView(ct);
tv.setText(postOrders.get(i));
tv.setTextColor(Color.BLACK);
// make button
// the button should send us to next view
Button bt_View = new Button(ct);
bt_View.setText("Select");
//adding views
layout.addView(tv,-2,-2);
tableRow.addView(layout);
tableRow.addView(bt_View,-2,-2);
tableLayout_PostOrders.addView(tableRow,i+1);
}
}
What I want is to make table ROWs with Text and a Button, yet the text should not pass the screen and always go down vertically if needed.
here is a picture, each row will have one of these.
The correct way to implement the design according to yr requirement is listview or recyclerview.
So best to use Listview/RecycleView instead of making list row on fly.
The xml for the list row will look like :
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".65"
android:text="You text will come here" />
<Button
android:id="#+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Button" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tbl_att_summary"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="1"
android:shrinkColumns="1">
<TableRow android:layout_marginTop="10dp"
android:layout_marginRight="2dp"
android:layout_marginBottom="-5dp"
android:layout_gravity="center_horizontal">
<TextView
android:text="Class"
android:paddingLeft="10dip" />
<TextView
android:text="Subject"
android:gravity="center_horizontal" />
<TextView
android:text="Time Period"
android:layout_gravity="center_horizontal|bottom"
android:gravity="center_horizontal"
android:layout_marginRight="10dp" />
<TextView
android:text="Work Days"
android:layout_marginRight="15dp" />
</TableRow>
<TableRow android:layout_marginTop="5dp"
android:id="#+id/header_row_att_summary">
<!-- first column for Class - Section -->
<TextView
android:layout_column="0"
android:id="#+id/txt_class_sec_att_summary"
android:textColor="#color/black"
android:textSize="20sp"
android:paddingLeft="10dp" />
<!-- Second column for subject -->
<TextView
android:layout_column="1"
android:id="#+id/txt_subjec_att_summary"
android:text="Chemistry"
android:textSize="20sp"
android:paddingRight="10dp"
android:layout_marginRight="5dp"
android:textColor="#color/black"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="5dp" />
<!-- third column for duration (time period) for the attendance -->
<TextView
android:id="#+id/txt_time_period_att_summary"
android:text="Feb-15"
android:textColor="#color/black"
android:textSize="20sp"
android:gravity="fill_horizontal|end"
android:paddingRight="10dp"
android:layout_marginRight="5dp"
android:layout_gravity="center_horizontal" />
<!-- fourth column for the total number of working days -->
<TextView
android:id="#+id/txt_working_days_att_summary"
android:text="18"
android:textColor="#color/black"
android:textSize="20sp"
android:gravity="fill_horizontal|end"
android:paddingRight="10dp"
android:layout_marginLeft="10dp"
android:layout_gravity="center_horizontal"
android:layout_marginRight="10dp" />
</TableRow>
<View
android:layout_height="2dip"
android:background="#FF909090"/>
<TableRow
android:layout_marginTop="5dp">
<TextView
android:background="#drawable/cell_shape"
android:layout_column="0"
android:paddingLeft="5dp"
android:text="Roll No"
android:layout_weight="0.2"
android:textStyle="bold" />
<TextView
android:background="#drawable/cell_shape"
android:paddingLeft="5dp"
android:text="Name"
android:textStyle="bold" />
<TextView
android:background="#drawable/cell_shape"
android:paddingLeft="5dp"
android:text="Days Present"
android:textStyle="bold" />
<TextView
android:background="#drawable/cell_shape"
android:paddingLeft="5dp"
android:text="Percentage"
android:textStyle="bold" />
</TableRow>
<TableRow
android:id="#+id/row_att_detail"
android:layout_marginTop="0dp">
<TextView
android:id="#+id/txt_roll_no"
android:background="#drawable/cell_shape"
android:paddingLeft="5dp" />
<TextView
android:id="#+id/txt_student_name"
android:background="#drawable/cell_shape"
android:paddingLeft="5dp" />
<TextView
android:id="#+id/txt_days_present"
android:background="#drawable/cell_shape"
android:paddingLeft="5dp"/>
<TextView
android:id="#+id/txt_percentage"
android:background="#drawable/cell_shape"
android:paddingLeft="5dp"/>
</TableRow>
</TableLayout>
Corresponding java code
public class ShowAttendanceSummary extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_attendance_summary);
// set up the header rows
TableRow header_row = (TableRow) findViewById(R.id.header_row_att_summary);
((TextView) header_row.findViewById(R.id.txt_class_sec_att_summary)).
setText((getIntent().getStringExtra("class") + "-" +
getIntent().getStringExtra("section")));
((TextView) header_row.findViewById(R.id.txt_subjec_att_summary)).
setText((getIntent().getStringExtra("subject")));
// showing month/year is slightly tricky. As we are passing strings like "current year",
// "last year", or "till date", we need get the year value
Integer yr = Calendar.getInstance().get(Calendar.YEAR);
System.out.print("year=" + Integer.toString(yr));
//Toast.makeText(getApplicationContext(), Integer.toString(yr), Toast.LENGTH_SHORT).show();
switch (getIntent().getStringExtra("year")) {
case "current_year":
((TextView) header_row.findViewById(R.id.txt_time_period_att_summary)).
setText((getIntent().getStringExtra("month") + "-" +
Integer.toString(yr)));
break;
case "last_year":
((TextView) header_row.findViewById(R.id.txt_time_period_att_summary)).
setText((getIntent().getStringExtra("month") + "-" +
Integer.toString(yr - 1)));
break;
case "till_date":
((TextView) header_row.findViewById(R.id.txt_time_period_att_summary)).
setText("Till Date");
break;
}
final TableLayout tableLayout = (TableLayout) findViewById(R.id.tbl_att_summary);
final ArrayList<TableRow> tableRows = new ArrayList<>();
// get the list of students
String tag = "AttendanceListSummary";
final String student_list_url = "http://" +
MiscFunctions.getInstance().getServerIP(getApplicationContext())
+ "/student/list/" +
getIntent().getStringExtra("class") + "/" +
getIntent().getStringExtra("section") + "/?format=json";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
(Request.Method.GET, student_list_url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++)
try {
JSONObject jo = response.getJSONObject(i);
// get the name of the student. We need to join first and last names
String f_name = jo.getString("fist_name");
String l_name = jo.getString("last_name");
String full_name = f_name + " " + l_name;
// get the roll number of the student
String roll_no = jo.getString("roll_number");
TableRow detail_row = (TableRow) findViewById(R.id.row_att_detail);
((TextView) detail_row.findViewById(R.id.txt_roll_no)).
setText(roll_no);
((TextView) detail_row.findViewById(R.id.txt_student_name)).
setText(full_name);
tableRows.add(detail_row);
tableLayout.addView(tableRows.get(i));
} catch (JSONException je) {
System.out.println("Ran into JSON exception " +
"while trying to fetch the list of students");
je.printStackTrace();
} catch (Exception e) {
System.out.println("Caught General exception " +
"while trying to fetch the list of students");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("inside volley error handler");
// TODO Auto-generated method stub
}
});
com.classup.AppController.getInstance().addToRequestQueue(jsonArrayRequest, tag);
JSONObject params = new JSONObject();
try {
params.put("class", getIntent().getStringExtra("class"));
params.put("section", getIntent().getStringExtra("section"));
params.put("subject", getIntent().getStringExtra("subject"));
params.put("month", getIntent().getStringExtra("month"));
params.put("year", getIntent().getStringExtra("year"));
} catch (JSONException je) {
System.out.println("unable to create json for selected subjects");
je.printStackTrace();
}
}
}
As it can be seen that I am trying to add rows to my TableLayout at runtime. However, I get the following exception:
classup W/System.err: java.lang.IllegalStateException: The specified
child already has a parent. You must call removeView() on the child's
parent first.
Can somebody have a look and suggest what mistake I am making here.
The exception you've got likely pertains to this block of your codes.
try {
JSONObject jo = response.getJSONObject(i);
// get the name of the student. We need to join first and last names
String f_name = jo.getString("fist_name");
String l_name = jo.getString("last_name");
String full_name = f_name + " " + l_name;
// get the roll number of the student
String roll_no = jo.getString("roll_number");
TableRow detail_row = (TableRow) findViewById(R.id.row_att_detail);
((TextView) detail_row.findViewById(R.id.txt_roll_no)).setText(roll_no);
((TextView) detail_row.findViewById(R.id.txt_student_name)).
setText(full_name);
tableRows.add(detail_row);
tableLayout.addView(tableRows.get(i));
}
Some notes that you should beware of:
Views can only be attached to the main view hierarchy only once. Thus, if you attempt to attach an already-attached view to the hierarchy again, you will get an exception.
If you add a child to a TableRow, you then don't need to add that TableRow to the main TableLayout again.
I am trying to have the user fill out a form then those fields auto-populate into an email. I was able to convert the EditText to strings as well as the spinner, but I am confused as to how to do it with RadioGroup. I want the text from the button which is selected to appear in the email. I know that getText won't work, but what will. Thank you
JAVA
//This happens when you press the submit button at the bottom of the form.
public void submit(View button) {
// Do click handling here
//What happens here is the input from each field is taken in and converted into
//Strings and placed into their correct variables.
final EditText FirstNameField = (EditText) findViewById(R.id.EditTextFirstName);
fName = FirstNameField.getText().toString();
final EditText LastNameField = (EditText) findViewById(R.id.EditTextLastName);
lName = LastNameField.getText().toString();
final EditText emailField = (EditText) findViewById(R.id.EditTextEmail);
email = emailField.getText().toString();
final EditText feedbackField = (EditText) findViewById(R.id.EditTextFeedbackBody);
feedback = feedbackField.getText().toString();
final Spinner feedbackSpinner = (Spinner) findViewById(R.id.SpinnerFeedbackType);
feedbackType = feedbackSpinner.getSelectedItem().toString();
final RadioGroup ApproveorReject = (RadioGroup) findViewById(R.id.radiochoice);
fAnswer = ApproveorReject.getText().toString();
//calls the sendEmail() from below to pull up a list of apps installed
//on the phone that can handle emailing.
sendEmail();
}
//This bit of code pulls up a list of apps that can handle emailing.
private void sendEmail() {
//When the user chooses an app of the list that pops up, these lines below
//will auto-populate the fields of the email with the input from above.
//The user can take one last look at the email before hitting that send button
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"recipient#example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, feedbackType);
i.putExtra(Intent.EXTRA_TEXT, lName + ", " + fName + "\n" + email + "\n" + feedback + fAnswer );
startActivity(Intent.createChooser(i, "Send mail..."));
}
}
XML
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical">
<RelativeLayout
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<TextView
android:id="#+id/TextViewTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="#string/feedbacktitle"
android:textSize="10pt">
</TextView>
<!--First Name-->
<EditText
android:id="#+id/EditTextFirstName"
android:layout_height="wrap_content"
android:hint="#string/feedbackfirst"
android:inputType="textPersonName"
android:layout_width="fill_parent"
android:layout_below="#+id/TextViewTitle">
</EditText>
<!--Last Name-->
<EditText
android:id="#+id/EditTextLastName"
android:layout_height="wrap_content"
android:hint="#string/feedbacklast"
android:inputType="textPersonName"
android:layout_width="fill_parent"
android:layout_below="#id/EditTextFirstName">
</EditText>
<!-- Email -->
<EditText
android:id="#+id/EditTextEmail"
android:layout_height="wrap_content"
android:hint="#string/feedbackemail"
android:inputType="textEmailAddress"
android:layout_width="fill_parent"
android:layout_below="#id/EditTextLastName">
</EditText>
<Spinner
android:id="#+id/SpinnerFeedbackType"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:entries="#array/Types_of_Errors"
android:layout_below="#+id/EditTextEmail">
</Spinner>
<EditText
android:id="#+id/EditTextFeedbackBody"
android:layout_height="wrap_content"
android:hint="#string/feedbackbody"
android:inputType="textMultiLine"
android:lines="5"
android:layout_width="fill_parent"
android:layout_below="#+id/SpinnerFeedbackType">
</EditText>
<RadioGroup
android:id="#+id/radiochoice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/EditTextFeedbackBody"
android:orientation="horizontal">
<RadioButton
android:id="#+id/AcceptRadio"
android:layout_width="wrap_content"
android:layout_marginStart="50dp"
android:layout_height="wrap_content"
android:text="#string/acceptbutton" />
<RadioButton
android:id="#+id/RejectRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/rejectbutton"
android:layout_marginStart="115dp" />
</RadioGroup>
<EditText
android:id="#+id/RejectResponse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/rejectreason"
android:layout_marginTop="410dp"
android:layout_alignParentEnd="true"
android:layout_marginRight="20dp"
android:inputType="text"/>
<Button
android:id="#+id/ButtonSend"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/sendform"
android:layout_centerHorizontal="true"
android:layout_marginTop="590dp"
android:onClick="submit"/>
</RelativeLayout>
Try this
RadioButton btn=(RadioButton)findViewById(ApproveorReject.getCheckedRadioButtonId());
String selectedText=btn.getText().toString();
Try
ApproveorReject.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton rb=(RadioButton)findViewById(checkedId);
String param = rb.getText();
}
});
EDIT: Thank you all for your help. I edited my Database class to contain the following
final EditText firstName = (EditText) findViewById(R.id.editText1); // First Name
final EditText middleName = (EditText) findViewById(R.id.editText2); // Middle Name
final EditText birthDate = (EditText) findViewById(R.id.editText4); // Birth Date
final String firstname = firstName.getText().toString(); // First Name
final String middlename = middleName.getText().toString(); // Middle Name
final String birthdate = birthDate.getText().toString(); // Birth Date
TextView firstNameText = (TextView)findViewById(R.id.firstname);
TextView middleNameText = (TextView)findViewById(R.id.middlename);
TextView birthDateText = (TextView)findViewById(R.id.birthdate);
firstNameText.setText(firstname);
middleNameText.setText(middlename);
birthDateText.setText(birthdate);
and my database.xml now shows
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:background="#aa0000"
android:gravity="center_horizontal"
android:layout_span="3"
android:id="#+id/firstname"/>
<TextView
android:background="#00aa00"
android:gravity="center_horizontal"
android:layout_span="3"
android:id="#+id/middlename"/>
<TextView
android:background="#0000aa"
android:gravity="center_horizontal"
android:layout_span="3"
android:id="#+id/birthdate"/>
</TableRow>
but when I run the emulator and I try to access that screen (by clicking a button from the previous screen) the application crashes? I set up the button correctly using the OnClickListener so I'm fairly sure the button is not the problem
If you're having trouble understanding the interface here's an example you can cut and paste.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First Name: "
android:id="#+id/firstLabel"
android:layout_marginTop="14dip"
android:layout_marginBottom="14dip"
/>
<EditText android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/firstEdit"
android:text="John"
android:layout_toRightOf="#id/firstLabel"
android:layout_alignParentRight="true"></EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Middle Name: "
android:id="#+id/middleLabel"
android:layout_below="#id/firstLabel"
android:layout_marginTop="14dip"
android:layout_marginBottom="14dip"/>
<EditText android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/middleEdit"
android:text="Phillip"
android:layout_below="#id/firstEdit"
android:layout_toRightOf="#id/middleLabel"
android:layout_alignParentRight="true"></EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Last Name: "
android:id="#+id/lastLabel"
android:layout_below="#id/middleLabel"
android:layout_marginTop="14dip"
android:layout_marginBottom="14dip"
/>
<EditText android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/lastEdit"
android:text="Doe"
android:layout_below="#id/middleEdit"
android:layout_toRightOf="#id/lastLabel"
android:layout_alignParentRight="true"></EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Birthdate: "
android:id="#+id/birthLabel"
android:layout_below="#id/lastLabel"
android:layout_marginTop="14dip"
android:layout_marginBottom="14dip"
/>
<EditText android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/birthEdit"
android:text="08/09/1977"
android:layout_toRightOf="#id/lastLabel"
android:layout_below="#id/lastEdit"
android:layout_alignParentRight="true"></EditText>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_below="#id/birthEdit">
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TextView
android:background="#aa0000"
android:gravity="center_horizontal"
android:layout_span="3"
android:text="something"
android:id="#+id/firstTable"/>
<TextView
android:background="#00aa00"
android:gravity="center_horizontal"
android:layout_span="3"
android:text="something1"
android:id="#+id/middleTable"/>
<TextView
android:background="#0000aa"
android:gravity="center_horizontal"
android:layout_span="3"
android:text="something2"
android:id="#+id/birthTable"/>
</TableRow>
</LinearLayout>
</RelativeLayout>
DatabaseExample.java
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class DatabaseExample extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Setup edit fields
EditText firstEdit = (EditText)findViewById(R.id.firstEdit);
EditText middleEdit = (EditText)findViewById(R.id.middleEdit);
EditText lastEdit = (EditText)findViewById(R.id.lastEdit);
EditText birthEdit = (EditText)findViewById(R.id.birthEdit);
//Get the text and store in variables
String firstName = firstEdit.getText().toString();
String middleName = middleEdit.getText().toString();
String lastName = lastEdit.getText().toString();
String birthDate = birthEdit.getText().toString();
//setup the text fields
TextView firstTable = (TextView)findViewById(R.id.firstTable);
TextView middleTable = (TextView)findViewById(R.id.middleTable);
TextView birthTable = (TextView)findViewById(R.id.birthTable);
//change the text fields
firstTable.setText(firstName);
middleTable.setText(middleName);
birthTable.setText(birthDate);
}
}
Once again this would be just the interface for inputting and displaying data. Instead of storing the data in String variables you would use SQLite, SharedPreferences, or write to a file on the SDCard.
Try as follows
final EditText firstName = (EditText) findViewById(R.id.editText1);
TextView firstNameTxt = (TextView)findViewById(R.id.firstname);
firstNameTxt.setText(firstName);
You cannot store values from the user in the strings.xml file. You must have a data store such as SharedPreferences or SQLite. Here is another link for help on data storage with Android.