Android TableLayout Exception while adding row at runtime - java

<?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.

Related

how to save selected radio button and spinner data by value using rest API?

I am using rest API and facing some issue when embedding an API. How do I save spinner and radio button data by value and using retrofit2.This API is for calculating BMR and BMR Please help!
Here is BMIquestions.java
public class BMIquestions extends AppCompatActivity implements View.OnClickListener{
Button nextbtn;
ImageButton date;
DatePickerDialog datePickerDialog;
EditText age, height, weight;
// Let's assume 1 = male and 0 = female
// Declare a RadioGroup object reference
RadioGroup rgGender;
// Declare RadioButton object references for Male and Female
RadioButton rbMale, rbFemale;
private String gender=null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmiquestions);
getSupportActionBar().hide();
nextbtn = findViewById(R.id.Next);
date = findViewById(R.id.calender);
age = findViewById(R.id.age);
height = findViewById(R.id.currentHeight);
weight = findViewById(R.id.currentHeight);
rgGender = findViewById(R.id.gender_group);
rbMale = findViewById(R.id.male);
rbFemale = findViewById(R.id.female);
rgGender.clearCheck();
rgGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
rbMale = group.findViewById(R.id.male);
rbFemale = group.findViewById(R.id.female);
if(rbMale.isSelected()){
rbMale.setTag("1");
rbMale.getTag().toString();
if(rbFemale.isSelected()){
rbFemale.setTag("0");
rbFemale.getTag().toString();
}
}
}
});
findViewById(R.id.female).setOnClickListener(this);
findViewById(R.id.male).setOnClickListener(this);
findViewById(R.id.Next).setOnClickListener(this);
String[] level = new String[]{"Not Very Activ", "Lightly Active", "Active", "Very Active"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(
this,
R.layout.drop_down_items,
level
);
AutoCompleteTextView autoCompleteTextView = findViewById(R.id.type);
autoCompleteTextView.setAdapter(adapter);
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(BMIquestions.this, autoCompleteTextView.getText().toString(), Toast.LENGTH_SHORT).show();
if(autoCompleteTextView.getText().toString().equals("Lightly Active")){
autoCompleteTextView.setTag("1.55");
}
}
});
date.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(View view) {
// Calender class 's instance and get current,date ,month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);//current year
int mMonth = c.get(Calendar.MONTH);//current month
int mDay = c.get(Calendar.DAY_OF_MONTH);//current date
final int noofyears = (int) (mYear - c.get(Calendar.YEAR)); //calculate age
//date picker dialog
datePickerDialog = new DatePickerDialog(BMIquestions.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
age.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
DatePicker dp = datePickerDialog.getDatePicker();
WindowManager.LayoutParams params = datePickerDialog.getWindow().getAttributes();
//params.gravity = Gravity.CENTER_HORIZONTAL;
params.width = 50; // dialogWidth;
params.height = 100; // dialogHeight;
datePickerDialog.show();
}
});
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.Next:
openHomePage();
break;
case R.id.male:
gender="0";
break;
case R.id.female:
rbFemale.setTag("0");
gender=rbFemale.getTag().toString();
break;
}
}
public void openHomePage() {
String userHeight = height.getText().toString();
String userWeight = weight.getText().toString();
String userAge = age.getText().toString();
HashMap<String, String> meMap = new HashMap<String, String>();
meMap.put("height", userHeight);
meMap.put("age", userAge);
meMap.put("gender", gender);
//meMap.put("activity_level",act);
meMap.put("current_weight",userWeight);
Call<QuestionResponse> call = RetrofitClient
.getInstance()
.getApi()
.calculation(meMap);
call.enqueue(new Callback<QuestionResponse>() {
#Override
public void onResponse(Call<QuestionResponse> call, Response<QuestionResponse> response) {
QuestionResponse questionResponse = response.body();
if (response.isSuccessful()) {
if (questionResponse.getStatus().equals("SUCCESS")) {
Toast.makeText(BMIquestions.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(BMIquestions.this, HomePage.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
} else {
Toast.makeText(BMIquestions.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(BMIquestions.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<QuestionResponse> call, Throwable t) {
Toast.makeText(BMIquestions.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Intent i=new Intent(BMIquestions.this,HomePage.class);
startActivity(i);
}
}
Here is activity_bmiquestions.xml
<?xml version="1.0" encoding="utf-8"?>
<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=".ui.questions.BMIquestions">
<TextView
android:id="#+id/targetWeight"
android:layout_width="386dp"
android:layout_height="wrap_content"
android:fontFamily="#font/roboto_regular"
android:gravity="center"
android:paddingStart="12dp"
android:paddingTop="60dp"
android:text="Tell us About Youself"
android:textColor="#color/black"
android:textSize="22sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="122dp"
android:fontFamily="#font/roboto_regular"
android:text="Gender:"
android:textColor="#color/black"
android:textSize="14dp" />
<RadioGroup
android:id="#+id/gender_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="142dp"
android:paddingStart="24dp"
android:orientation="horizontal"
>
<RadioButton
android:id="#+id/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
/>
<RadioButton
android:id="#+id/male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male" />
</RadioGroup>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="18dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal">
<EditText
android:id="#+id/age"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:hint="DD/MM/YYYY" />
<ImageButton
android:id="#+id/calender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:background="#drawable/ic_baseline_calendar_today_24" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="120dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="202dp"
android:fontFamily="#font/roboto_regular"
android:text="Height in centimeter"
android:textColor="#color/black"
android:textSize="14dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal">
<EditText
android:id="#+id/currentHeight"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:hint="Enter your height"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:text="cm"/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="17dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="202dp"
android:fontFamily="#font/roboto_regular"
android:text="When were you born ?"
android:textColor="#color/black"
android:textSize="14dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="120dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="202dp"
android:fontFamily="#font/roboto_regular"
android:text="Weight in kilogram"
android:textColor="#color/black"
android:textSize="14dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal">
<EditText
android:id="#+id/currentWeight"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:hint="Enter your weight" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="kg"
android:textColor="#color/black" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="440dp"
android:layout_marginStart="10dp">
<com.google.android.material.textfield.TextInputLayout
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
android:layout_width="330dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="80dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="80dp"
android:hint="Activity Level" >
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/type"
android:inputType="none">
</AutoCompleteTextView>
</com.google.android.material.textfield.TextInputLayout>
</RelativeLayout>
<android.widget.Button
android:id="#+id/Next"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="21dp"
android:background="#color/dark_grey"
android:text="Next"
android:textColor="#color/white"
android:textSize="15sp"
android:textStyle="bold"></android.widget.Button>
</RelativeLayout>
Here is Api Interface
public interface Api{
//GetCalculations
#POST("calculation")
Call<QuestionResponse> calculation(
#Body HashMap<String, String> body
);
}
Here is RetrofitClient.java
package com.example.signup.ui.api;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
//singeleton class defining retrofit client
//define base url
//initialize retrofit object
private static final String BASE_URL = "http://xxx.xxx.xxx.xxx:xxxx/api/";
private static RetrofitClient retrofitClient;
private static Retrofit retrofit;
// HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
// interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
private RetrofitClient() {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
//return instances when above method call
public static synchronized RetrofitClient getInstance() {
if (retrofitClient==null) {
retrofitClient = new RetrofitClient();
}
return retrofitClient;
}
public Api getApi() {
return retrofit.create(Api.class);
}
}
How can I fix this problem?

How to handle NULL results from JSON when I click on list view row?

Very little experience when it comes to Java. My app pulls data from an API to a list view just fine. Once clicked on the list view I want to display more details. My code is in different files and I can't figure out how handle null results when I set my text view text. Right now it is giving me a few errors. Thank you in advanced. I've tried debugging and my own research to no avail for over a day.
My error was: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference.
MainActivity.java:
public void showMemberDetailsScreen(int _id) {
mMembersListScreen.setVisibility(View.GONE);
mMemberDetailsScreen.setVisibility(View.VISIBLE);
if (NetworkUtils.isConnected(this)) {
GetDetailsTask task = new GetDetailsTask(this);
task.execute(_id);
} else {
Log.i(TAG, "onCreate: NOT CONNECTED");
}
}
/**
* Populate the member details screen with data.
*
* #param _name
* #param _birthday
* #param _gender
* #param _twitterId
* #param _numCommittees
* #param _numRoles
*/
public void populateMemberDetailsScreen(String _name, String _birthday, String _gender,
String _twitterId, String _numCommittees, String _numRoles) {
TextView tv = (TextView)mMembersListScreen.findViewById(R.id.text_name);
tv.setText(_name);
tv = (TextView)mMembersListScreen.findViewById(R.id.text_birthday);
tv.setText(_birthday);
tv = (TextView)mMembersListScreen.findViewById(R.id.text_gender);
tv.setText(_gender);
tv = (TextView)mMembersListScreen.findViewById(R.id.text_twitter_id);
tv.setText(_twitterId);
tv = (TextView)mMembersListScreen.findViewById(R.id.text_num_committees);
tv.setText(_numCommittees);
tv = (TextView)mMembersListScreen.findViewById(R.id.text_num_roles);
tv.setText(_numRoles);
}
OnItemClickListener mItemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> _parent, View _view, int _position, long _id) {
// TODO: Show the members detail screen
Log.i(TAG, "onItemClick: RAN");
showMemberDetailsScreen(_position);
Log.i(TAG, "onItemClick: POSITION = " + _position);
}
};
GetDetailsTask.java:
private static final String NAME = "name";
private static final String BIRTHDAY = "birthday";
private static final String GENDER = "gender";
private static final String TWITTER_ID = "twitter_id";
private static final String NUM_COMMITTEES = "num_committees";
private static final String NUM_ROLES = "num_roles";
private MainActivity mActivity;
public GetDetailsTask(MainActivity _activity) {
mActivity = _activity;
}
#Override
protected HashMap<String, String> doInBackground(Integer... _params) {
// Add member ID to the end of the URL
String data = NetworkUtils.getNetworkData(API_URL + _params[0]);
HashMap<String, String> retValues = new HashMap<String, String>();
try {
JSONObject response = new JSONObject(data);
String name = response.optString("name");
retValues.put(NAME, name);
String birthday = response.optString("birthday");
retValues.put(BIRTHDAY, birthday);
String gender = response.optString("gender_label");
retValues.put(GENDER, gender);
String twitterId = response.optString("twitterid");
retValues.put(TWITTER_ID, twitterId);
if (response.has("committeeassignments")) {
JSONArray committeeArray = response.optJSONArray("committeeassignments");
int numCommittees = committeeArray.length();
retValues.put(NUM_COMMITTEES, "" + numCommittees);
Log.i(TAG, "doInBackground: NUM COMMITTESS = " + numCommittees);
} else {
retValues.put(NUM_COMMITTEES, "" + 0);
}
if (response.has("roles")){
JSONArray rolesArray = response.optJSONArray("roles");
int numRoles = rolesArray.length();
retValues.put(NUM_ROLES, "" + numRoles);
} else {
retValues.put(NUM_ROLES, "" + 0);
}
} catch(JSONException e) {
e.printStackTrace();
}
return retValues;
}
#Override
protected void onPostExecute(HashMap<String, String> _result) {
super.onPostExecute(_result);
if (_result != null) {
String name = _result.get(NAME);
String birthday = _result.get(BIRTHDAY);
String gender = _result.get(GENDER);
String twitterId = _result.get(TWITTER_ID);
String numCommittees = _result.get(NUM_COMMITTEES);
String numRoles = _result.get(NUM_ROLES);
mActivity.populateMemberDetailsScreen(name, birthday, gender, twitterId, numCommittees, numRoles);
}
}
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/members_list_screen"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:visibility="gone" >
<ListView
android:id="#+id/members_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
<LinearLayout
android:id="#+id/member_details_screen"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:visibility="gone" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/name" />
<TextView
android:id="#+id/text_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/birthday" />
<TextView android:id="#+id/text_birthday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/gender" />
<TextView
android:id="#+id/text_gender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/twitter_id" />
<TextView android:id="#+id/text_twitter_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/num_committees" />
<TextView
android:id="#+id/text_num_committees"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/name" />
<TextView
android:id="#+id/text_num_roles"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
</LinearLayout>
You are trying to show your details screen but in your method you are finding view by id under your mMembersListScreen when you should use mMemberDetailsScreen. Try this:
public void populateMemberDetailsScreen(String _name, String _birthday, String _gender,
String _twitterId, String _numCommittees, String _numRoles) {
TextView tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_name);
tv.setText(_name);
tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_birthday);
tv.setText(_birthday);
tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_gender);
tv.setText(_gender);
tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_twitter_id);
tv.setText(_twitterId);
tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_num_committees);
tv.setText(_numCommittees);
tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_num_roles);
tv.setText(_numRoles);
}

Will only read and write one line

Program runs fine however I can not figure out why it will only read and write one line. It should be able to write multiple lines and read them into the textview. I have it setup so that when the user clicks add it automatically should read into the textview
public class MainActivity extends AppCompatActivity {
EditText Activity, Miles, Date;
TextView Log;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Activity = (EditText)(findViewById(R.id.editText));
Miles = (EditText)(findViewById(R.id.editText2));
Date = (EditText)(findViewById(R.id.editText3));
Log = (TextView)(findViewById(R.id.textView));
}
public void Add(View view)
{
String Myactivity = Activity.getText().toString() + "\t" + Miles.getText().toString() + "\t" + Date.getText().toString();
try {
FileOutputStream fileOutputStream = openFileOutput("myActivities.txt", MODE_PRIVATE);
fileOutputStream.write(Myactivity.getBytes());
fileOutputStream.close();
Toast.makeText(getApplicationContext(), "Activty Added", Toast.LENGTH_LONG);
FileInputStream fileInputStream = openFileInput("myActivities.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
String action;
while((action = bufferedReader.readLine())!= null)
{
stringBuffer.append(action + "\n");
}
Log.setText(stringBuffer.toString());
} catch (FileNotFoundException e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_LONG);
} catch (IOException e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_LONG);
}
}
}
<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="mbl404.phoenix.edu.week2appgk5343.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:hint="Please Enter Type of Workout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignEnd="#+id/editText2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText2"
android:hint="Please Enter Number of Miles"
android:layout_below="#+id/editText"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText3"
android:hint="Please Enter Date"
android:layout_below="#+id/editText2"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="Add"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_below="#+id/button"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
Add this in your textview xml
android:maxLines="100"
In your code:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_below="#+id/button"
android:maxLines="100" <!-- add android:maxLines to specify the number of lines in textview -->
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true" />
Updated:
while((action = bufferedReader.readLine())!= null)
{
Log.setText(Log.getText() + action + "\n");
}

My TextView in Android doesn't update

Although I've checked the solutions for the related questions in this website, I couldn't solve my problem. I'm trying to build a quiz app that takes the correct answer, adds 1 to the score and updates the score on the score TextView. I tried calling the score method through android:onClick and also tried the setOnClickListener methods but none of them seem to work.
This is my XML:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to the Canada Quiz"
android:textSize="16sp"
android:textColor="#000000"
android:textStyle="bold"
android:layout_marginBottom="16dp"
android:layout_gravity="center"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter name"
android:layout_marginBottom="8dp"
/>
<TextView
android:id="#+id/scoreText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:layout_marginBottom="16dp"
android:textColor="#000000"
android:textStyle="bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1. What is the capital of Canada?"
android:textSize="20dp"
android:textColor="#000000"
android:textStyle="bold"
/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/tokyo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tokyo"
android:layout_marginLeft="24dp"
android:textStyle="bold"
android:textSize="16dp"/>
<RadioButton
android:id="#+id/newYork"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New York"
android:layout_marginLeft="24dp"
android:textStyle="bold"
android:textSize="16dp"/>
<RadioButton
android:id="#+id/ottawa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ottawa"
android:layout_marginLeft="24dp"
android:textStyle="bold"
android:textSize="16dp"/>
<RadioButton
android:id="#+id/hongKong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hong Kong"
android:layout_marginLeft="24dp"
android:textStyle="bold"
android:onClick="calculateScore"
android:textSize="16dp"/>
</RadioGroup>
<Button
android:id="#+id/scoreButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Calculate score"
android:layout_marginTop="16dp"
/>
</LinearLayout>
</ScrollView>
And this is my Java:
public class MainActivity extends AppCompatActivity {
int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioButton rb = (RadioButton)findViewById(R.id.ottawa);
Button calculate = (Button) findViewById(R.id.scoreButton);
final TextView scoreShow = (TextView) findViewById(R.id.scoreText);
final boolean rbChecked = rb.isChecked();
calculate.setOnClickListener(new View.OnClickListener(){
public void onClick (View v){
if(rbChecked){
score += 1;
scoreShow.setText("Your score is: " + score + "/10");
}
}
});
}
// public void calculateScore(){
// RadioButton rb = (RadioButton)findViewById(R.id.ottawa);
// //Button calculate = (Button) findViewById(R.id.scoreButton);
// TextView scoreShow = (TextView) findViewById(R.id.scoreText);
//
// boolean rbChecked = rb.isChecked();
// if(rbChecked){
// score += 1;
// scoreShow.setText("Your score is: " + score + "/10");
// }
// }
}
Honestly, it really looks like it would work but it doesn't.
You are only storing the value of the checked state when the view is loaded and it never is updated.
Always check rb.isChecked() inside the click listener instead of storing the boolean value outside of it.
It should be:
if(rbChecked.isChecked()){
score += 1;
scoreShow.setText("Your score is: " + score + "/10");
}
you need to check for the state of radiobutton when user click on calculate button....your code should be like this...
calculate.setOnClickListener(new View.OnClickListener(){
public void onClick (View v){
rbChecked = rb.isChecked();
if(rbChecked){
score += 1;
scoreShow.setText("Your score is: " + score + "/10");
}
}
});

Cannot resolve method getText for a RadioGroup

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();
}
});

Categories