None of the answers to questions on this topic have solved the issue for my specific case.
My app is hogging memory and causing the main thread to be unresponsive. I am using a listener to monitor Telephony states. When the state changes (or once per second) I want to grab the parameter associated and update a TextView with its value. I have tried using Threads and Runnables but the performance still sucks. Now I am trying AsyncTask but I don't understand it. I want this activity to run for at least 15 minutes with the listener running that whole time in the background; and once per second I want the values grabbed with the listener to be used to update TextViews on the UI thread.
public class Second extends Activity {
SignalStrengthListener signalStrengthListener;
TextView lteRsrp;
TextView lteRsrq;
TextView cellPciTextView;
Button startButton;
TelephonyManager tm;
List<CellInfo> cellInfoList;
String lte1, lte2;
int cellPci = 0;
// List<String[]> data;
// #Override
// public void run() {
// // Moves the current Thread into the background
// android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
// startTele();
//
// }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
setupUI();
// run();
new MyAsyncTask().execute();
setupButton();
}
public class SignalStrengthListener extends PhoneStateListener {
#Override
public void onSignalStrengthsChanged(android.telephony.SignalStrength signalStrength) {
//++++++++++++++++++++++++++++++++++
((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).listen(signalStrengthListener, SignalStrengthListener.LISTEN_SIGNAL_STRENGTHS);
tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String ltestr = signalStrength.toString();
String[] parts = ltestr.split(" ");
lte1 = parts[9];
lte2 = parts[10];
try {
cellInfoList = tm.getAllCellInfo();
for (CellInfo cellInfo : cellInfoList) {
if (cellInfo instanceof CellInfoLte) {
// cast to CellInfoLte and call all the CellInfoLte methods you need
// Gets the LTE PCI: (returns Physical Cell Id 0..503, Integer.MAX_VALUE if unknown)
cellPci = ((CellInfoLte) cellInfo).getCellIdentity().getPci();
}
}
} catch (Exception e) {
Log.d("SignalStrength", "+++++++++++++++++++++++++++++++ null array spot 3: " + e);
}
// lteRsrp.setText(String.valueOf(lte1));
// lteRsrq.setText(String.valueOf(lte2));
// cellPciTextView.setText(String.valueOf(cellPci));
super.onSignalStrengthsChanged(signalStrength);
//++++++++++++++++++++++++++++++++++++
}
}
private void setupUI() {
lteRsrp = (TextView) findViewById(R.id.lteRsrp);
lteRsrq = (TextView) findViewById(R.id.lteRsrq);
cellPciTextView = (TextView) findViewById(R.id.cellPciTextView);
startButton = (Button) findViewById(R.id.startButton);
}
public void startTele() {
//start the signal strength listener
signalStrengthListener = new SignalStrengthListener();
((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).listen(signalStrengthListener, SignalStrengthListener.LISTEN_SIGNAL_STRENGTHS);
tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
try {
cellInfoList = tm.getAllCellInfo();
} catch (Exception e) {
Log.d("SignalStrength", "+++++++++++++++++++++++++++++++++++++++++ null array spot 1: " + e);
}
}
private void setupButton() {
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(),Third.class);
startActivity(intent);
}
});
}
//??????????????????????????????????????????????????????????????????????????????????????????????
public class MyAsyncTask extends AsyncTask<Void, Void, Void> {
// WeakReference<TextView> lteRsrpWRef, lteRsrqWRef, ltePciWRef;
// public MyAsyncTask(TextView lteRsrp, TextView lteRsrq, TextView cellPciTextView) {
// lteRsrpWRef = new WeakReference<TextView>(lteRsrp);
// lteRsrqWRef = new WeakReference<TextView>(lteRsrq);
// ltePciWRef = new WeakReference<TextView>(cellPciTextView);
//
// }
#Override
public Void doInBackground(Void... params) {
startTele();
return null;
}
#Override
public void onPostExecute(Void aVoid) {
//super.onPostExecute(aVoid);
lteRsrp.setText(String.valueOf(lte1));
lteRsrq.setText(String.valueOf(lte2));
cellPciTextView.setText(String.valueOf(cellPci));
}
}
//??????????????????????????????????????????????????????????????????????????????????????????????
}
My attempt to use AsyncTask is at the bottom enclosed by "//????????????". I simply want to call startTele() which then calls the SignalStrengthListener from the doInBackground() in AsyncTask so that all that code will be run on a background thread. Then I want to get the values String lte1, String lte2, and int cellPci and use them to update TextView lteRsrp, lteRsrq, cellPciTextView; on the UI thread.
Here is my XML for Second.class:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffdc1d">
<TextView
android:layout_width="210dp"
android:layout_height="wrap_content"
android:text="0"
android:textSize="22sp"
android:textColor="#000000"
android:id="#+id/lteRsrp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="29dp"
android:layout_marginTop="80dp"
android:textAlignment="textEnd"
android:background="#ffdc1d"
android:textStyle="bold"
android:layout_marginBottom="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="= LTE RSRP"
android:textSize="22sp"
android:textColor="#000000"
android:id="#+id/textView2"
android:background="#ffdc1d"
android:textStyle="bold"
android:layout_alignTop="#+id/lteRsrp"
android:layout_toEndOf="#+id/startButton"
android:layout_marginBottom="20dp" />
<TextView
android:layout_width="210dp"
android:layout_height="wrap_content"
android:text="0"
android:textColor="#a71b1b"
android:textSize="22sp"
android:id="#+id/lteRsrq"
android:layout_below="#+id/lteRsrp"
android:layout_alignStart="#+id/lteRsrp"
android:textAlignment="textEnd"
android:textStyle="bold"
android:background="#ffdc1d"
android:layout_marginBottom="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="= LTE RSRQ"
android:textSize="22sp"
android:textColor="#a71b1b"
android:id="#+id/textView3"
android:layout_below="#+id/textView2"
android:layout_alignStart="#+id/textView2"
android:textStyle="bold"
android:background="#ffdc1d"
android:layout_marginBottom="20dp" />
<TextView
android:layout_width="210dp"
android:layout_height="wrap_content"
android:text="0"
android:textSize="22sp"
android:textColor="#075f09"
android:id="#+id/cellPciTextView"
android:layout_below="#+id/lteRsrq"
android:layout_alignStart="#+id/lteRsrq"
android:textAlignment="textEnd"
android:background="#ffdc1d"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="= LTE PCI"
android:textSize="22sp"
android:textColor="#075f09"
android:id="#+id/textView4"
android:layout_below="#+id/textView3"
android:layout_alignStart="#+id/textView3"
android:background="#ffdc1d"
android:textStyle="bold" />
<Button
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="Start"
android:textColor="#ffdc1d"
android:textSize="22sp"
android:id="#+id/startButton"
android:layout_marginBottom="47dp"
android:background="#f91616"
android:textAlignment="center"
android:textStyle="bold"
android:padding="4dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Press the START button to begin recording"
android:id="#+id/textView8"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textColor="#f91616"
android:textSize="22sp"
android:textStyle="italic"
android:textAlignment="center"
android:layout_marginTop="12dp" />
</RelativeLayout>
And here is my logcat messages:
So, how can I run my telephony listener in the background for 15 minutes while grabbing the LTE parameters RSRP, RSRQ, and PCI and updating the TextViews on the UI thread with these values once per second?
Related
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?
so I am trying to create an activity, and then add onclick listeners to it, but it wont let me refer. So the moment I open this activity in my app, my app crashes, saying 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference'
I have no idea why this is happening. I have correctly names them in accordance with the xml file as well.
Please help.
public class SubtaskActivity extends AppCompatActivity {
EditText etSubtaskName;
Button btnDone;
RadioGroup radgrpPri, radgrpTime;
RadioButton radbtnPriHigh, radbtnPriMed, radbtnPriLow, radbtnTimeMore, radbtnTimeMed, radbtnTimeLess;
boolean priHigh, priMed, priLow, timeMore, timeMed, timeLess;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btnDone = findViewById(R.id.btnDone);
radgrpPri = findViewById(R.id.radgrpPri);
radgrpTime = findViewById(R.id.radgrpTime);
radbtnPriHigh = findViewById(R.id.radbtnPriHigh);
radbtnPriMed = findViewById(R.id.radbtnPriMed);
radbtnPriLow = findViewById(R.id.radbtnPriLow);
radbtnTimeMore = findViewById(R.id.radbtnTimeMore);
radbtnTimeMed = findViewById(R.id.radbtnTimeMed);
radbtnTimeLess = findViewById(R.id.radbtnTimeLess);
etSubtaskName = findViewById(R.id.etSubtaskName);
radgrpPri.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (radbtnPriHigh.isChecked())
{
priHigh = true;
priLow = false;
priMed = false;
}
else if (radbtnPriMed.isChecked())
{
priHigh = false;
priLow = false;
priMed = true;
}
else if (radbtnPriLow.isChecked())
{
priHigh = false;
priLow = true;
priMed = false;
}
}
});
radgrpTime.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (radbtnTimeMore.isChecked())
{
timeMore = true;
timeMed = false;
timeLess = false;
}
else if (radbtnTimeMed.isChecked())
{
timeMore = false;
timeMed = true;
timeLess = false;
}
else if (radbtnTimeLess.isChecked())
{
timeMore = false;
timeMed = false;
timeLess = true;
}
}
});
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = etSubtaskName.getText().toString().trim();
Intent intent = new Intent(SubtaskActivity.this, TaskInfo.class);
intent.putExtra("subtaskName", name);
intent.putExtra("priHigh", priHigh);
intent.putExtra("priMed", priMed);
intent.putExtra("priLow", priLow);
intent.putExtra("timeMore", timeMore);
intent.putExtra("timeMed", timeMed);
intent.putExtra("timeLess", timeLess);
startActivity(intent);
}
});
}
}
XML File :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/it"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:background="#color/background"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/background"
android:orientation="vertical">
<TextView
android:id="#+id/tvSubtaskPriorityHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="16dp"
android:fontFamily="#font/roboto"
android:text="#string/priority_of_subtask"
android:textColor="#B8AEAE"
android:textSize="16sp" />
<RadioGroup
android:id="#+id/radgrpPri"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<RadioButton
android:id="#+id/radbtnPriHigh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:buttonTint="#color/red"
android:text="#string/high"
android:textColor="#color/white" />
<RadioButton
android:id="#+id/radbtnPriMed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:buttonTint="#color/yellow"
android:text="#string/medium"
android:textColor="#color/white" />
<RadioButton
android:id="#+id/radbtnPriLow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:buttonTint="#color/green"
android:text="#string/low"
android:textColor="#color/white" />
</RadioGroup>
<TextView
android:id="#+id/tvTimeWeightHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="32dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="16dp"
android:fontFamily="#font/roboto"
android:text="#string/time_this_subtask_may_consume"
android:textColor="#B8AEAE"
android:textSize="16sp" />
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/floating_hint_time_minutes"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:hintTextAppearance="#style/FlotatingHintStyle">
<EditText
android:id="#+id/etSubtaskName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:ems="10"
android:fontFamily="#font/roboto"
android:hint="#string/name_your_subtask"
android:inputType="textPersonName"
android:maxLength="20"
android:textColor="#color/white"
android:textColorHint="#B8AEAE"
android:textSize="14sp" />
</com.google.android.material.textfield.TextInputLayout>
<RadioGroup
android:id="#+id/radgrpTime"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<RadioButton
android:id="#+id/radbtnTimeMore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:buttonTint="#color/red"
android:text="#string/more"
android:textColor="#color/white" />
<RadioButton
android:id="#+id/radbtnTimeMed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:buttonTint="#color/yellow"
android:text="#string/medium"
android:textColor="#color/white" />
<RadioButton
android:id="#+id/radbtnTimeLess"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:buttonTint="#color/green"
android:text="#string/less"
android:textColor="#color/white" />
</RadioGroup>
</LinearLayout>
<Button
android:id="#+id/btnDone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="16dp"
android:layout_marginTop="32dp"
android:layout_marginRight="16dp"
android:gravity="center_horizontal"
android:text="#string/done"
app:backgroundTint="#color/orange_accent" />
</LinearLayout>
You didn't call in onCreate method setContentView(R.layout.youractivity). If you didn't, Android doesn't know what to render, so there are no views for you to provide.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.youractivity);
}
just set your (xml)layout file to setContentView in onCreate()
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
}
I have a class called AnimalMarker which should represent the bare minimum of a normal google maps Marker (latitude, longitutde, location) and an object Animal. And I'm using the Firebase Realtime Database to store those AnimalMarkers.
What I want to do, but don't know how to do it, is create a custom InfoWindow (I've created the new layout and an Adapter that should be passed in the MapActivity) that even though is binding to the google maps Markers, should take data from the corresponding AnimalMarker of that Marker.
The logic of my MapActivity is:
create an AnimalMarker using the latitude,longitute, and taking user input for adding an animal to it. now the AnimalMarker object has been created
add the AnimalMarker to the Firebase Realtime Database
when the DatabaseListener gets the update, it will call a method in the MapActivity to re-create the List of google-maps Markers and re-draw them.
I realise now that instead of saving just the google-maps Markers in a List, a Hashmap < AnimalMarker, Marker > would be better, and update the Hashmap when the database Listener notices the update But even so, I wouldn't know how to make the InfoWindowAdapter take the data from the associated AnimalMarker of a Marker.
Here is my code:
MapActivity
public class MapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener {
...
private void initListeners() {
Log.d(TAG, "initListeners: initializing SearchText");
firebaseAuth = FirebaseAuth.getInstance();
geocoder = new Geocoder(MapActivity.this);
markersDatabase = new MarkersDatabase();
myMarkersList = new ArrayList<>();
allMarkersList = new ArrayList<>();
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener(){
#Override
public void onMapLongClick(LatLng latLng) {
List<Address> addresses = new ArrayList<>();
try {
addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
String locationTitle = addresses.get(0).getAddressLine(0);
Log.d(TAG, "onMapLongClick: addresses = " + addresses.get(0));
AnimalMarker marker = new AnimalMarker(latLng.latitude, latLng.longitude, locationTitle, firebaseAuth.getCurrentUser().getUid());
markersDatabase.addMarker(marker);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(marker.getLatitude(), marker.getLongitude()), DEFAULT_ZOOM));
}
});
}
...
private void startMarkersListener() {
markersDatabase.readCurrentUserMarkers(new MarkersDatabaseListener() {
#Override
public void onCurrentUserMarkersCallBack(List<AnimalMarker> list) {
Log.d(TAG, "onCurrentUserMarkersCallBack: myMarkersList updated");
clearAllMyMarkers();
for (AnimalMarker animalMarker : list) {
Marker marker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(animalMarker.getLatitude(), animalMarker.getLongitude()))
.title(animalMarker.getLocation())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.visible(myMarkersVisible));
Log.d(TAG, "onCurrentUserMarkersCallBack: created a marker at: " + marker.getTitle());
myMarkersList.add(marker);
}
}
#Override
public void onAllMarkersCallBack(List<AnimalMarker> list) {
Log.d(TAG, "onCurrentUserMarkersCallBack ----> onAllMarkersCallBack: should never reach here");
}
});
}
MarkerInfoWindowAdapter
public class MarkerInfoWindowAdapter implements GoogleMap.InfoWindowAdapter{
private final View mWindow;
private Context context;
public MarkerInfoWindowAdapter(Context context) {
this.context = context;
mWindow = LayoutInflater.from(context).inflate(R.layout.marker_info_window, null);
}
private void renderWindowText(Marker marker, View view) {
// example code to come here
String title = marker.getTitle();
TextView titleTextView = (TextView) view.findViewById(R.id.miwLocation);
if(!title.equals("")) {
titleTextView.setText(title);
}
}
#Override
public View getInfoWindow(Marker marker) {
renderWindowText(marker, mWindow);
return mWindow;
}
#Override
public View getInfoContents(Marker marker) {
renderWindowText(marker, mWindow);
return mWindow;
}
}
layout of my desired information in the custom InfoWindow:
<?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:background="#drawable/white_border"
android:orientation="horizontal"
android:padding="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/miwLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_gravity="center_horizontal"
android:layout_marginStart="150dp"
android:layout_marginTop="5dp"
android:ellipsize="end"
android:maxLines="2"
android:text="miwLocation"
android:textColor="#000000"
android:textSize="20sp"
android:textStyle="bold" />
<ImageView
android:src="#drawable/dog_icon"
android:id="#+id/miwImage"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_below="#+id/miwLocation"
android:layout_alignParentStart="true"
android:layout_marginStart="18dp"
android:layout_marginTop="10dp" />
<TextView
android:id="#+id/miwAnimalName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/miwLocation"
android:layout_marginStart="30dp"
android:layout_marginTop="12dp"
android:layout_toEndOf="#+id/miwImage"
android:layout_toRightOf="#id/miwImage"
android:ellipsize="end"
android:maxLines="2"
android:text="miwAnimalName"
android:textColor="#000000"
android:textSize="17sp" />
<TextView
android:id="#+id/miwAnimalAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/miwAdultCB"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#id/miwImage"
android:text="3 yrs"
android:textColor="#000000"
android:textSize="20sp" />
<CheckBox
android:id="#+id/miwAdultCB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/miwAnimalName"
android:layout_marginLeft="20dp"
android:layout_marginTop="8dp"
android:layout_toRightOf="#id/miwImage"
android:text=" Adult"
android:textSize="20dp" />
<CheckBox
android:id="#+id/miwNeuteredCB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/miwAnimalName"
android:layout_marginLeft="20dp"
android:layout_marginTop="8dp"
android:layout_toRightOf="#id/miwAdultCB"
android:text=" Neutered"
android:textSize="20dp" />
</RelativeLayout>
</LinearLayout>
Image of it:
I've found the solution after understanding the answer in this post
custom info window adapter with custom data in map v2
The easiest approach would to create an anonymous Adapter and use the global HashMap< Marker, AnimalMarker > inside it.
Something like this
getMap().setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker arg0) {
// set layout, use Marker/AnimalMarker here
}
});
I have included a button known as "btnConfirm" in my activity layout, and has referred to it in the code below(mConfirm), however, when the button is clicked no action is triggered. I have even looked into logcat, where no new message is shown upon button click. The code below shows the action that the button was suppose to trigger - transmit the user entered information to parse, and redirect users to another activity page.
If you need any clarification, let me know.
Thanks in advance.
public class ProfileCreation extends Activity {
private static final int RESULT_LOAD_IMAGE = 1;
FrameLayout layout;
Button save;
protected EditText mName;
protected EditText mAge;
protected EditText mHeadline;
protected Button mConfirm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_creation);
Parse.initialize(this, "ID", "ID");
mName = (EditText)findViewById(R.id.etxtname);
mAge = (EditText)findViewById(R.id.etxtage);
mHeadline = (EditText)findViewById(R.id.etxtheadline);
mConfirm = (Button)findViewById(R.id.btnConfirm);
mConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = mName.getText().toString();
String age = mAge.getText().toString();
String headline = mHeadline.getText().toString();
age = age.trim();
name = name.trim();
headline = headline.trim();
if (age.isEmpty() || name.isEmpty() || headline.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(R.string.signup_error_message)
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else {
// create the new user!
setProgressBarIndeterminateVisibility(true);
ParseUser currentUser = ParseUser.getCurrentUser();
currentUser.put("name", name);
currentUser.put("age", age);
currentUser.put("headline", headline);
currentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// Success!
Intent intent = new Intent(ProfileCreation.this, MoodActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
setContentView(R.layout.activity_profile_creation);
save = (Button) findViewById(R.id.button2);
String picturePath = PreferenceManager.getDefaultSharedPreferences(this).getString("picturePath", "");
if (!picturePath.equals("")) {
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
SeekBar seekBar = (SeekBar) findViewById(R.id.seekBarDistance);
final TextView seekBarValue = (TextView) findViewById(R.id.seekBarDistanceValue);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
seekBarValue.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
SeekBar seekBarMinimum = (SeekBar) findViewById(R.id.seekBarMinimumAge);
final TextView txtMinimum = (TextView) findViewById(R.id.tMinAge);
seekBarMinimum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMinimum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
SeekBar seekBarMaximum = (SeekBar) findViewById(R.id.seekBarMaximumAge);
final TextView txtMaximum = (TextView) findViewById(R.id.tMaxAge);
seekBarMaximum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMaximum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Locate the image in res >
Bitmap bitmap = BitmapFactory.decodeFile("picturePath");
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
Object image = null;
try {
String path = null;
image = readInFile(path);
} catch (Exception e) {
e.printStackTrace();
}
// Create the ParseFile
ParseFile file = new ParseFile("picturePath", (byte[]) image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a New Class called "ImageUpload" in Parse
ParseObject imgupload = new ParseObject("Image");
// Create a column named "ImageName" and set the string
imgupload.put("Image", "picturePath");
// Create a column named "ImageFile" and insert the image
imgupload.put("ImageFile", file);
// Create the class and the columns
imgupload.saveInBackground();
// Show a simple toast message
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
private byte[] readInFile(String path) throws IOException {
// TODO Auto-generated method stub
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(
file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
}
xml code
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/dark_texture_blue" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="797dp"
android:gravity="center"
android:orientation="vertical" >
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/profilePicturePreview"
android:layout_width="132dp"
android:layout_height="120dp"
android:layout_below="#+id/textView5"
android:layout_centerHorizontal="true"
android:layout_marginTop="7dp"
android:alpha="1" />
<Button
android:id="#+id/button2"
android:layout_width="120dp"
android:layout_height="60dp"
android:layout_above="#+id/etxtage"
android:layout_alignLeft="#+id/etxtname"
android:alpha="0.8"
android:background="#330099"
android:text="Upload from Facebook"
android:textColor="#ffffff"
android:textSize="17sp"
android:textStyle="bold" />
<Button
android:id="#+id/btnPictureSelect"
android:layout_width="118dp"
android:layout_height="60dp"
android:layout_alignRight="#+id/etxtname"
android:layout_below="#+id/profilePicturePreview"
android:layout_marginRight="8dp"
android:alpha="0.8"
android:background="#000000"
android:onClick="pickPhoto"
android:text="Select photo from gallery"
android:textColor="#ffffff"
android:textSize="17sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView4"
android:layout_centerHorizontal="true"
android:layout_marginTop="9dp"
android:text="Preferred Name"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="39dp"
android:gravity="center"
android:text="Profile Creation"
android:textColor="#ffffff"
android:textSize="28sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button2"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp"
android:text="Age"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<EditText
android:id="#+id/etxtage"
android:layout_width="230dp"
android:layout_height="wrap_content"
android:layout_below="#+id/btnPictureSelect"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp"
android:ems="10"
android:hint="Please type your age here"
android:inputType="number"
android:maxLength="2"
android:textAlignment="center"
android:textColor="#f2f2f2"
android:textSize="18dp" />
<EditText
android:id="#+id/etxtname"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView6"
android:layout_centerHorizontal="true"
android:ems="10"
android:enabled="true"
android:hint="Please type your name here"
android:inputType="textPersonName"
android:textColor="#ffffff"
android:textSize="18sp" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/etxtname"
android:layout_centerHorizontal="true"
android:layout_marginTop="8dp"
android:text="Upload your Profile Picture"
android:textColor="#f2f2f2"
android:textSize="18sp"
android:textStyle="bold"
android:typeface="sans" />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_toLeftOf="#+id/textView3" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:textColor="#f2f2f2"
android:text="Male" />
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#f2f2f2"
android:text="Female" />
</RadioGroup>
<SeekBar
android:id="#+id/seekBarDistance"
android:layout_width="250dp"
android:progress="50"
android:layout_centerHorizontal="true"
android:layout_height="wrap_content"
android:layout_below="#+id/textView12"
android:layout_marginTop="11dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView5"
android:layout_below="#+id/etxtheadline"
android:layout_marginTop="38dp"
android:text="I am a"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold" />
<RadioGroup
android:id="#+id/radioGroup3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView4"
android:layout_alignTop="#+id/radioGroup2"
android:layout_marginTop="10dp" >
</RadioGroup>
<RadioGroup
android:id="#+id/radioGroup2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/etxtheadline"
android:layout_below="#+id/textView2" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Male"
android:textColor="#f2f2f2" />
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:textColor="#f2f2f2" />
</RadioGroup>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView1"
android:layout_alignBottom="#+id/textView1"
android:layout_alignRight="#+id/radioGroup2"
android:text="Looking for"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold" />
<SeekBar
android:id="#+id/seekBarMinimumAge"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView7"
android:layout_marginTop="11dp"
android:progress="25" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/etxtage"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Minimum Age Looking For"
android:textColor="#f2f2f2"
android:textSize="16sp"
android:textStyle="bold"
android:typeface="serif" />
<EditText
android:id="#+id/etxtheadline"
android:layout_width="270dp"
android:layout_height="70dp"
android:layout_alignLeft="#+id/button2"
android:layout_below="#+id/textView8"
android:ems="10"
android:hint="A quick description of yourself"
android:singleLine="true"
android:textAlignment="center"
android:textColor="#f2f2f2"
android:textSize="18dp" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/seekBarDistanceValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/tMinAge"
android:layout_below="#+id/seekBarDistance"
android:text="50"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f2f2f2"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioGroup1"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp"
android:text="Search Distance (100KM)"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/tMinAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/seekBarMinimumAge"
android:layout_centerHorizontal="true"
android:text="25"
android:textColor="#f2f2f2"
android:textSize="18sp" />
<TextView
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tMaxAge"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:text="Headline"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/textView14"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tMinAge"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:text="Maximum Age Looking For"
android:textColor="#f2f2f2"
android:textSize="16sp"
android:textStyle="bold"
android:typeface="serif" />
<SeekBar
android:id="#+id/seekBarMaximumAge"
android:layout_width="221dp"
android:progress="50"
android:layout_centerHorizontal="true"
android:layout_height="wrap_content"
android:layout_below="#+id/textView14"
android:layout_marginTop="11dp" />
<TextView
android:id="#+id/tMaxAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/seekBarMaximumAge"
android:layout_centerHorizontal="true"
android:text="50"
android:textColor="#f2f2f2"
android:textSize="18sp" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView16"
android:layout_centerHorizontal="true"
android:text="I agree to the terms and Conditions"
android:textColor="#D2D2D2"
android:textColorHint="#ffffff" />
<TextView
android:id="#+id/textView16"
android:layout_width="280dp"
android:layout_height="40dp"
android:layout_alignLeft="#+id/checkBox1"
android:layout_below="#+id/seekBarDistanceValue"
android:layout_marginTop="14dp"
android:gravity="center"
android:text="Click here to review the terms and conditions"
android:textColor="#99CCFF"
android:textSize="16sp" />
<Button
android:id="#+id/btnReset"
android:layout_width="120dp"
android:layout_height="60dp"
android:layout_marginBottom="7dp"
android:layout_below="#+id/checkBox1"
android:layout_toLeftOf="#+id/btnPictureSelect"
android:alpha="0.8"
android:background="#660000"
android:layout_marginTop="14dp"
android:text="Reset"
android:textColor="#ffffff"
android:textSize="17sp"
android:textStyle="bold" />
<Button
android:id="#+id/btnConfirm"
android:layout_width="120dp"
android:layout_height="60dp"
android:layout_below="#+id/checkBox1"
android:layout_toRightOf="#+id/seekBarDistanceValue"
android:alpha="0.8"
android:layout_marginTop="14dp"
android:layout_marginBottom="7dp"
android:background="#330099"
android:text="Confirm"
android:textColor="#ffffff"
android:textSize="17sp"
android:textStyle="bold" />
</RelativeLayout>
</ScrollView>
As I saw in your code ..You have set the same content view setContentView(R.layout.activity_profile_creation); twice..
1st one (perfect):
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_creation);`
2nd one(makes problem): Just before the save button
setContentView(R.layout.activity_profile_creation);
save = (Button) findViewById(R.id.button2);
Delete the second one i.e which is just before save button.
I am using the default login_activity.xml from ADT and I would like it to change orientation when the device is flipped. I have a separate login_activity.xml in the res/layout-land directory because that seems to have solved similar problems that people have found.
Currently, the app loads the correct xml based on the orientation of the device at runtime. If you flip the device afterwards, the orientation changes, but the layout remains the same. Each xml has a different layout that looks better for its respective orientation.
I'm wondering if this is just not possible to do, or if I have overlooked a working fix.
I would post images of the actual running app, but I need 10 reputation before I can do that.
Below are my LoginActivity.java and activity_login.xml files:
//LoginActivity.java
/** Activity which displays a login screen to the user, offering registration as well.*/
public class LoginActivity extends Activity {
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// Values for email and password at the time of the login attempt.
private String mUsername;
private String mPassword;
// UI references.
private EditText mUsernameView;
private EditText mPasswordView;
private View mLoginFormView;
private View mLoginStatusView;
private TextView mLoginStatusMessageView;
private mDMI app;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (mDMI) getApplication();
setContentView(R.layout.activity_login);
// Set up the login form.
mUsernameView = (EditText) findViewById(R.id.username);
mUsernameView.setText(mUsername);
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if ((id == R.id.login) || (id == EditorInfo.IME_NULL)) {
attemptLogin();
return true;
}
return false;
}
});
mLoginFormView = findViewById(R.id.login_form);
mLoginStatusView = findViewById(R.id.login_status);
mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
findViewById(R.id.getUniqueHardwareID).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String id = app.getDeviceId().getID();
AlertDialog ad = new AlertDialog.Builder(v.getContext()).create();
ad.setCancelable(false);
ad.setTitle("Device ID");
ad.setMessage("The Unqiue ID for this device is: \n" + id);
ad.setButton(DialogInterface.BUTTON_POSITIVE, "Ok", (Message) null);
ad.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
/**
* Attempts to sign in or register the account specified by the login form. If there are form errors (invalid email,
* missing fields, etc.), the errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mUsernameView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
mUsername = mUsernameView.getText().toString();
mPassword = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password.
if (TextUtils.isEmpty(mPassword)) {
mPasswordView.setError(getString(R.string.error_field_required));
focusView = mPasswordView;
cancel = true;
} else if (mPassword.length() < 4) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(mUsername)) {
mUsernameView.setError(getString(R.string.error_field_required));
focusView = mUsernameView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
Intent myIntent = new Intent(this.getBaseContext(), MainActivity.class); // hopefully this will switch to
// the
// MainActivity
startActivity(myIntent);
finish();
mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
showProgress(true);
mAuthTask = new UserLoginTask();
mAuthTask.execute((Void) null);
}
}
/**
* Shows the progress UI and hides the login form.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginStatusView.setVisibility(View.VISIBLE);
mLoginStatusView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
mLoginFormView.setVisibility(View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
/**
* Represents an asynchronous login/registration task used to authenticate the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
// TODO: register the new account here.
return true;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
Vertical Login Activity
//vertical activity_login.xml
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".LoginActivity" >
<!-- Login progress -->
<LinearLayout
android:id="#+id/login_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:orientation="vertical"
android:visibility="gone"
>
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp" />
<TextView
android:id="#+id/login_status_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:fontFamily="sans-serif-light"
android:text="#string/login_progress_signing_in"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<!-- Login form -->
<ScrollView
android:id="#+id/login_form"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="5" >
<LinearLayout
style="#style/LoginFormContainer"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_gravity="top|center_horizontal"
android:layout_weight="2"
android:scaleType="fitXY"
android:src="#drawable/spashscreen" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_gravity="center|bottom"
android:layout_weight="3"
android:orientation="vertical" >
<EditText
android:id="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/prompt_username"
android:inputType="text"
android:maxLines="1"
android:singleLine="true" />
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/prompt_password"
android:imeActionId="#+id/login"
android:imeActionLabel="#string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true" />
<EditText
android:id="#+id/serverInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/prompt_address" />
<Button
android:id="#+id/sign_in_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingLeft="32dp"
android:paddingRight="32dp"
android:text="#string/action_sign_in_short" />
<Button
android:id="#+id/getUniqueHardwareID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/show_device_id" />
</LinearLayout>
<!-- Make this uneditable if the mobile device has a value listed locally -->
</LinearLayout>
</ScrollView>
</merge>
Horizontal Activity Login
//horizontal activity_login.xml
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".LoginActivity" >
<!-- Login progress -->
<LinearLayout
android:id="#+id/login_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:visibility="gone"
>
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp" />
<TextView
android:id="#+id/login_status_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:fontFamily="sans-serif-light"
android:text="#string/login_progress_signing_in"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<!-- Login form -->
<ScrollView
android:id="#+id/login_form"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="5" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_weight="2"
android:scaleType="matrix"
android:src="#drawable/spashscreen" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_weight="3"
android:orientation="vertical" >
<EditText
android:id="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/prompt_username"
android:inputType="text"
android:maxLines="1"
android:singleLine="true" />
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/prompt_password"
android:imeActionId="#+id/login"
android:imeActionLabel="#string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true" />
<EditText
android:id="#+id/serverInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/prompt_address" />
<Button
android:id="#+id/sign_in_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingLeft="32dp"
android:paddingRight="32dp"
android:text="#string/action_sign_in_short" />
<Button
android:id="#+id/getUniqueHardwareID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/show_device_id" />
</LinearLayout>
</LinearLayout>
</ScrollView>
In Android Manifest for the given activity check if u have added orientation parameter to android:configChanges attribute. If yes remove it.